Unreviewed, rolling out r156451.
[WebKit-https.git] / Source / WebCore / rendering / RenderLayerCompositor.h
1 /*
2  * Copyright (C) 2009, 2013 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 COMPUTER, 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 #ifndef RenderLayerCompositor_h
27 #define RenderLayerCompositor_h
28
29 #if USE(ACCELERATED_COMPOSITING)
30
31 #include "ChromeClient.h"
32 #include "GraphicsLayerClient.h"
33 #include "GraphicsLayerUpdater.h"
34 #include "RenderLayer.h"
35 #include <wtf/HashMap.h>
36
37 namespace WebCore {
38
39 class FixedPositionViewportConstraints;
40 class GraphicsLayer;
41 class GraphicsLayerUpdater;
42 class RenderEmbeddedObject;
43 class RenderWidget;
44 class ScrollingCoordinator;
45 class StickyPositionViewportConstraints;
46 #if ENABLE(VIDEO)
47 class RenderVideo;
48 #endif
49 class TiledBacking;
50
51 typedef unsigned LayerTreeFlags;
52
53 enum CompositingUpdateType {
54     CompositingUpdateAfterStyleChange,
55     CompositingUpdateAfterLayout,
56     CompositingUpdateOnHitTest,
57     CompositingUpdateOnScroll,
58     CompositingUpdateOnCompositedScroll
59 };
60
61 enum {
62     CompositingReasonNone                                   = 0,
63     CompositingReason3DTransform                            = 1 << 0,
64     CompositingReasonVideo                                  = 1 << 1,
65     CompositingReasonCanvas                                 = 1 << 2,
66     CompositingReasonPlugin                                 = 1 << 3,
67     CompositingReasonIFrame                                 = 1 << 4,
68     CompositingReasonBackfaceVisibilityHidden               = 1 << 5,
69     CompositingReasonClipsCompositingDescendants            = 1 << 6,
70     CompositingReasonAnimation                              = 1 << 7,
71     CompositingReasonFilters                                = 1 << 8,
72     CompositingReasonPositionFixed                          = 1 << 9,
73     CompositingReasonPositionSticky                         = 1 << 10,
74     CompositingReasonOverflowScrollingTouch                 = 1 << 11,
75     CompositingReasonStacking                               = 1 << 12,
76     CompositingReasonOverlap                                = 1 << 13,
77     CompositingReasonNegativeZIndexChildren                 = 1 << 14,
78     CompositingReasonTransformWithCompositedDescendants     = 1 << 15,
79     CompositingReasonOpacityWithCompositedDescendants       = 1 << 16,
80     CompositingReasonMaskWithCompositedDescendants          = 1 << 17,
81     CompositingReasonReflectionWithCompositedDescendants    = 1 << 18,
82     CompositingReasonFilterWithCompositedDescendants        = 1 << 19,
83     CompositingReasonBlendingWithCompositedDescendants      = 1 << 20,
84     CompositingReasonPerspective                            = 1 << 21,
85     CompositingReasonPreserve3D                             = 1 << 22,
86     CompositingReasonRoot                                   = 1 << 23
87 };
88 typedef unsigned CompositingReasons;
89
90 // RenderLayerCompositor manages the hierarchy of
91 // composited RenderLayers. It determines which RenderLayers
92 // become compositing, and creates and maintains a hierarchy of
93 // GraphicsLayers based on the RenderLayer painting order.
94 // 
95 // There is one RenderLayerCompositor per RenderView.
96
97 class RenderLayerCompositor : public GraphicsLayerClient, public GraphicsLayerUpdaterClient {
98     WTF_MAKE_FAST_ALLOCATED;
99 public:
100     explicit RenderLayerCompositor(RenderView&);
101     ~RenderLayerCompositor();
102
103     // Return true if this RenderView is in "compositing mode" (i.e. has one or more
104     // composited RenderLayers)
105     bool inCompositingMode() const { return m_compositing; }
106     // This will make a compositing layer at the root automatically, and hook up to
107     // the native view/window system.
108     void enableCompositingMode(bool enable = true);
109
110     bool inForcedCompositingMode() const { return m_forceCompositingMode; }
111
112     // Returns true if the accelerated compositing is enabled
113     bool hasAcceleratedCompositing() const { return m_hasAcceleratedCompositing; }
114
115     bool canRender3DTransforms() const;
116
117     // Copy the accelerated compositing related flags from Settings
118     void cacheAcceleratedCompositingFlags();
119
120     // Called when the layer hierarchy needs to be updated (compositing layers have been
121     // created, destroyed or re-parented).
122     void setCompositingLayersNeedRebuild(bool needRebuild = true);
123     bool compositingLayersNeedRebuild() const { return m_compositingLayersNeedRebuild; }
124
125     // GraphicsLayers buffer state, which gets pushed to the underlying platform layers
126     // at specific times.
127     void scheduleLayerFlush(bool canThrottle);
128     void flushPendingLayerChanges(bool isFlushRoot = true);
129     
130     // flushPendingLayerChanges() flushes the entire GraphicsLayer tree, which can cross frame boundaries.
131     // This call returns the rootmost compositor that is being flushed (including self).
132     RenderLayerCompositor* enclosingCompositorFlushingLayers() const;
133
134     // Called when the GraphicsLayer for the given RenderLayer has flushed changes inside of flushPendingLayerChanges().
135     void didFlushChangesForLayer(RenderLayer*, const GraphicsLayer*);
136
137     // Called when something outside WebKit affects the visible rect (e.g. delegated scrolling). Might schedule a layer flush.
138     void didChangeVisibleRect();
139     
140     // Rebuild the tree of compositing layers
141     void updateCompositingLayers(CompositingUpdateType, RenderLayer* updateRoot = 0);
142     // This is only used when state changes and we do not exepect a style update or layout to happen soon (e.g. when
143     // we discover that an iframe is overlapped during painting).
144     void scheduleCompositingLayerUpdate();
145
146     // Update the maps that we use to distribute layers to coresponding RenderRegions.
147     void updateRenderFlowThreadLayersIfNeeded();
148     
149     // Update the compositing state of the given layer. Returns true if that state changed.
150     enum CompositingChangeRepaint { CompositingChangeRepaintNow, CompositingChangeWillRepaintLater };
151     bool updateLayerCompositingState(RenderLayer*, CompositingChangeRepaint = CompositingChangeRepaintNow);
152
153     // Update the geometry for compositing children of compositingAncestor.
154     void updateCompositingDescendantGeometry(RenderLayer* compositingAncestor, RenderLayer*, bool compositedChildrenOnly);
155     
156     // Whether layer's backing needs a graphics layer to do clipping by an ancestor (non-stacking-context parent with overflow).
157     bool clippedByAncestor(RenderLayer*) const;
158     // Whether layer's backing needs a graphics layer to clip z-order children of the given layer.
159     bool clipsCompositingDescendants(const RenderLayer*) const;
160
161     // Whether the given layer needs an extra 'contents' layer.
162     bool needsContentsCompositingLayer(const RenderLayer*) const;
163
164     bool supportsFixedRootBackgroundCompositing() const;
165     bool needsFixedRootBackgroundLayer(const RenderLayer*) const;
166     GraphicsLayer* fixedRootBackgroundLayer() const;
167     
168     // Return the bounding box required for compositing layer and its childern, relative to ancestorLayer.
169     // If layerBoundingBox is not 0, on return it contains the bounding box of this layer only.
170     LayoutRect calculateCompositedBounds(const RenderLayer*, const RenderLayer* ancestorLayer) const;
171
172     // Repaint the appropriate layers when the given RenderLayer starts or stops being composited.
173     void repaintOnCompositingChange(RenderLayer*);
174     
175     void repaintInCompositedAncestor(RenderLayer*, const LayoutRect&);
176     
177     // Notify us that a layer has been added or removed
178     void layerWasAdded(RenderLayer* parent, RenderLayer* child);
179     void layerWillBeRemoved(RenderLayer* parent, RenderLayer* child);
180
181     // Get the nearest ancestor layer that has overflow or clip, but is not a stacking context
182     RenderLayer* enclosingNonStackingClippingLayer(const RenderLayer* layer) const;
183
184     // Repaint parts of all composited layers that intersect the given absolute rectangle (or the entire layer if the pointer is null).
185     void repaintCompositedLayers(const IntRect* = 0);
186
187     // Returns true if the given layer needs it own backing store.
188     bool requiresOwnBackingStore(const RenderLayer*, const RenderLayer* compositingAncestorLayer, const IntRect& layerCompositedBoundsInAncestor, const IntRect& ancestorCompositedBounds) const;
189
190     RenderLayer* rootRenderLayer() const;
191     GraphicsLayer* rootGraphicsLayer() const;
192     GraphicsLayer* scrollLayer() const;
193
194 #if ENABLE(RUBBER_BANDING)
195     GraphicsLayer* headerLayer() const;
196     GraphicsLayer* footerLayer() const;
197 #endif
198
199     enum RootLayerAttachment {
200         RootLayerUnattached,
201         RootLayerAttachedViaChromeClient,
202         RootLayerAttachedViaEnclosingFrame
203     };
204
205     RootLayerAttachment rootLayerAttachment() const { return m_rootLayerAttachment; }
206     void updateRootLayerAttachment();
207     void updateRootLayerPosition();
208     
209     void setIsInWindow(bool);
210
211     void clearBackingForAllLayers();
212     
213     void layerBecameComposited(const RenderLayer*) { ++m_compositedLayerCount; }
214     void layerBecameNonComposited(const RenderLayer*);
215     
216 #if ENABLE(VIDEO)
217     // Use by RenderVideo to ask if it should try to use accelerated compositing.
218     bool canAccelerateVideoRendering(RenderVideo&) const;
219 #endif
220
221     // Walk the tree looking for layers with 3d transforms. Useful in case you need
222     // to know if there is non-affine content, e.g. for drawing into an image.
223     bool has3DContent() const;
224     
225     // Most platforms connect compositing layer trees between iframes and their parent document.
226     // Some (currently just Mac) allow iframes to do their own compositing.
227     static bool allowsIndependentlyCompositedFrames(const FrameView*);
228     bool shouldPropagateCompositingToEnclosingFrame() const;
229
230     static RenderLayerCompositor* frameContentsCompositor(RenderWidget*);
231     // Return true if the layers changed.
232     static bool parentFrameContentLayers(RenderWidget*);
233
234     // Update the geometry of the layers used for clipping and scrolling in frames.
235     void frameViewDidChangeLocation(const IntPoint& contentsOffset);
236     void frameViewDidChangeSize();
237     void frameViewDidScroll();
238     void frameViewDidAddOrRemoveScrollbars();
239     void frameViewDidLayout();
240     void rootFixedBackgroundsChanged();
241
242     void scrollingLayerDidChange(RenderLayer*);
243     void fixedRootBackgroundLayerChanged();
244
245     String layerTreeAsText(LayerTreeFlags);
246
247     virtual float deviceScaleFactor() const OVERRIDE;
248     virtual float pageScaleFactor() const OVERRIDE;
249     virtual void didCommitChangesForLayer(const GraphicsLayer*) const OVERRIDE;
250     virtual void notifyFlushBeforeDisplayRefresh(const GraphicsLayer*) OVERRIDE;
251
252     void layerTiledBackingUsageChanged(const GraphicsLayer*, bool /*usingTiledBacking*/);
253     
254     bool keepLayersPixelAligned() const;
255     bool acceleratedDrawingEnabled() const { return m_acceleratedDrawingEnabled; }
256
257     void deviceOrPageScaleFactorChanged();
258
259     void windowScreenDidChange(PlatformDisplayID);
260
261     GraphicsLayer* layerForHorizontalScrollbar() const { return m_layerForHorizontalScrollbar.get(); }
262     GraphicsLayer* layerForVerticalScrollbar() const { return m_layerForVerticalScrollbar.get(); }
263     GraphicsLayer* layerForScrollCorner() const { return m_layerForScrollCorner.get(); }
264 #if ENABLE(RUBBER_BANDING)
265     GraphicsLayer* layerForOverhangAreas() const { return m_layerForOverhangAreas.get(); }
266
267     GraphicsLayer* updateLayerForTopOverhangArea(bool wantsLayer);
268     GraphicsLayer* updateLayerForBottomOverhangArea(bool wantsLayer);
269     GraphicsLayer* updateLayerForHeader(bool wantsLayer);
270     GraphicsLayer* updateLayerForFooter(bool wantsLayer);
271 #endif
272
273     void updateViewportConstraintStatus(RenderLayer*);
274     void removeViewportConstrainedLayer(RenderLayer*);
275
276     void resetTrackedRepaintRects();
277     void setTracksRepaints(bool);
278
279     void setShouldReevaluateCompositingAfterLayout() { m_reevaluateCompositingAfterLayout = true; }
280
281     bool viewHasTransparentBackground(Color* backgroundColor = 0) const;
282
283     bool hasNonMainLayersWithTiledBacking() const { return m_layersWithTiledBackingCount; }
284
285     CompositingReasons reasonsForCompositing(const RenderLayer*) const;
286
287     void setLayerFlushThrottlingEnabled(bool);
288     void disableLayerFlushThrottlingTemporarilyForInteraction();
289     
290     void didPaintBacking(RenderLayerBacking*);
291
292 private:
293     class OverlapMap;
294
295     // GraphicsLayerClient implementation
296     virtual void notifyAnimationStarted(const GraphicsLayer*, double) OVERRIDE { }
297     virtual void notifyFlushRequired(const GraphicsLayer*) OVERRIDE;
298     virtual void paintContents(const GraphicsLayer*, GraphicsContext&, GraphicsLayerPaintingPhase, const IntRect&) OVERRIDE;
299
300     virtual bool isTrackingRepaints() const OVERRIDE;
301     
302     // GraphicsLayerUpdaterClient implementation
303     virtual void flushLayers(GraphicsLayerUpdater*) OVERRIDE;
304     virtual void customPositionForVisibleRectComputation(const GraphicsLayer*, FloatPoint&) const OVERRIDE;
305     
306     // Whether the given RL needs a compositing layer.
307     bool needsToBeComposited(const RenderLayer*, RenderLayer::ViewportConstrainedNotCompositedReason* = 0) const;
308     // Whether the layer has an intrinsic need for compositing layer.
309     bool requiresCompositingLayer(const RenderLayer*, RenderLayer::ViewportConstrainedNotCompositedReason* = 0) const;
310     // Whether the layer could ever be composited.
311     bool canBeComposited(const RenderLayer*) const;
312
313     // Make or destroy the backing for this layer; returns true if backing changed.
314     bool updateBacking(RenderLayer*, CompositingChangeRepaint shouldRepaint);
315
316     void clearBackingForLayerIncludingDescendants(RenderLayer*);
317
318     // Repaint the given rect (which is layer's coords), and regions of child layers that intersect that rect.
319     void recursiveRepaintLayer(RenderLayer*, const IntRect* = 0);
320
321     void addToOverlapMap(OverlapMap&, RenderLayer*, IntRect& layerBounds, bool& boundsComputed);
322     void addToOverlapMapRecursive(OverlapMap&, RenderLayer*, RenderLayer* ancestorLayer = 0);
323
324     void updateCompositingLayersTimerFired(Timer<RenderLayerCompositor>*);
325
326     // Returns true if any layer's compositing changed
327     void computeCompositingRequirements(RenderLayer* ancestorLayer, RenderLayer*, OverlapMap*, struct CompositingState&, bool& layersChanged, bool& descendantHas3DTransform);
328     
329     // Recurses down the tree, parenting descendant compositing layers and collecting an array of child layers for the current compositing layer.
330     void rebuildCompositingLayerTree(RenderLayer*, Vector<GraphicsLayer*>& childGraphicsLayersOfEnclosingLayer, int depth);
331
332     // Recurses down the tree, updating layer geometry only.
333     void updateLayerTreeGeometry(RenderLayer*, int depth);
334     
335     // Hook compositing layers together
336     void setCompositingParent(RenderLayer* childLayer, RenderLayer* parentLayer);
337     void removeCompositedChildren(RenderLayer*);
338
339     bool layerHas3DContent(const RenderLayer*) const;
340     bool isRunningAcceleratedTransformAnimation(RenderObject*) const;
341
342     bool hasAnyAdditionalCompositedLayers(const RenderLayer* rootLayer) const;
343
344     void ensureRootLayer();
345     void destroyRootLayer();
346
347     void attachRootLayer(RootLayerAttachment);
348     void detachRootLayer();
349     
350     void rootLayerAttachmentChanged();
351
352     void updateOverflowControlsLayers();
353
354     void notifyIFramesOfCompositingChange();
355
356     bool isFlushingLayers() const { return m_flushingLayers; }
357     
358     Page* page() const;
359     TiledBacking* pageTiledBacking() const;
360     
361     GraphicsLayerFactory* graphicsLayerFactory() const;
362     ScrollingCoordinator* scrollingCoordinator() const;
363
364     // Whether a running transition or animation enforces the need for a compositing layer.
365     bool requiresCompositingForAnimation(RenderObject*) const;
366     bool requiresCompositingForTransform(RenderObject*) const;
367     bool requiresCompositingForVideo(RenderObject*) const;
368     bool requiresCompositingForCanvas(RenderObject*) const;
369     bool requiresCompositingForPlugin(RenderObject*) const;
370     bool requiresCompositingForFrame(RenderObject*) const;
371     bool requiresCompositingForFilters(RenderObject*) const;
372     bool requiresCompositingForBlending(RenderObject* renderer) const;
373     bool requiresCompositingForScrollableFrame() const;
374     bool requiresCompositingForPosition(RenderObject*, const RenderLayer*, RenderLayer::ViewportConstrainedNotCompositedReason* = 0) const;
375     bool requiresCompositingForOverflowScrolling(const RenderLayer*) const;
376     bool requiresCompositingForIndirectReason(RenderObject*, bool hasCompositedDescendants, bool has3DTransformedDescendants, RenderLayer::IndirectCompositingReason&) const;
377
378     void addViewportConstrainedLayer(RenderLayer*);
379     void registerOrUpdateViewportConstrainedLayer(RenderLayer*);
380     void unregisterViewportConstrainedLayer(RenderLayer*);
381
382     FixedPositionViewportConstraints computeFixedViewportConstraints(RenderLayer*) const;
383     StickyPositionViewportConstraints computeStickyViewportConstraints(RenderLayer*) const;
384
385     bool requiresScrollLayer(RootLayerAttachment) const;
386     bool requiresHorizontalScrollbarLayer() const;
387     bool requiresVerticalScrollbarLayer() const;
388     bool requiresScrollCornerLayer() const;
389 #if ENABLE(RUBBER_BANDING)
390     bool requiresOverhangAreasLayer() const;
391     bool requiresContentShadowLayer() const;
392 #endif
393
394     bool hasCoordinatedScrolling() const;
395     bool shouldCompositeOverflowControls() const;
396
397     void scheduleLayerFlushNow();
398     bool isThrottlingLayerFlushes() const;
399     void startLayerFlushTimerIfNeeded();
400     void layerFlushTimerFired(Timer<RenderLayerCompositor>*);
401
402     void paintRelatedMilestonesTimerFired(Timer<RenderLayerCompositor>*);
403
404 #if !LOG_DISABLED
405     const char* logReasonsForCompositing(const RenderLayer*);
406     void logLayerInfo(const RenderLayer*, int depth);
407 #endif
408
409     bool mainFrameBackingIsTiled() const;
410
411 private:
412     RenderView& m_renderView;
413     OwnPtr<GraphicsLayer> m_rootContentLayer;
414     Timer<RenderLayerCompositor> m_updateCompositingLayersTimer;
415
416     bool m_hasAcceleratedCompositing;
417     ChromeClient::CompositingTriggerFlags m_compositingTriggers;
418
419     int m_compositedLayerCount;
420     bool m_showDebugBorders;
421     bool m_showRepaintCounter;
422     bool m_acceleratedDrawingEnabled;
423
424     // When true, we have to wait until layout has happened before we can decide whether to enter compositing mode,
425     // because only then do we know the final size of plugins and iframes.
426     mutable bool m_reevaluateCompositingAfterLayout;
427
428     bool m_compositing;
429     bool m_compositingLayersNeedRebuild;
430     bool m_flushingLayers;
431     bool m_shouldFlushOnReattach;
432     bool m_forceCompositingMode;
433     bool m_inPostLayoutUpdate; // true when it's OK to trust layout information (e.g. layer sizes and positions)
434
435     bool m_isTrackingRepaints; // Used for testing.
436
437     unsigned m_layersWithTiledBackingCount;
438
439     RootLayerAttachment m_rootLayerAttachment;
440
441     // Enclosing clipping layer for iframe content
442     OwnPtr<GraphicsLayer> m_clipLayer;
443     OwnPtr<GraphicsLayer> m_scrollLayer;
444
445     HashSet<RenderLayer*> m_viewportConstrainedLayers;
446     HashSet<RenderLayer*> m_viewportConstrainedLayersNeedingUpdate;
447
448     // Enclosing layer for overflow controls and the clipping layer
449     OwnPtr<GraphicsLayer> m_overflowControlsHostLayer;
450
451     // Layers for overflow controls
452     OwnPtr<GraphicsLayer> m_layerForHorizontalScrollbar;
453     OwnPtr<GraphicsLayer> m_layerForVerticalScrollbar;
454     OwnPtr<GraphicsLayer> m_layerForScrollCorner;
455 #if ENABLE(RUBBER_BANDING)
456     OwnPtr<GraphicsLayer> m_layerForOverhangAreas;
457     OwnPtr<GraphicsLayer> m_contentShadowLayer;
458     OwnPtr<GraphicsLayer> m_layerForTopOverhangArea;
459     OwnPtr<GraphicsLayer> m_layerForBottomOverhangArea;
460     OwnPtr<GraphicsLayer> m_layerForHeader;
461     OwnPtr<GraphicsLayer> m_layerForFooter;
462 #endif
463
464     OwnPtr<GraphicsLayerUpdater> m_layerUpdater; // Updates tiled layer visible area periodically while animations are running.
465
466     Timer<RenderLayerCompositor> m_layerFlushTimer;
467     bool m_layerFlushThrottlingEnabled;
468     bool m_layerFlushThrottlingTemporarilyDisabledForInteraction;
469     bool m_hasPendingLayerFlush;
470
471     Timer<RenderLayerCompositor> m_paintRelatedMilestonesTimer;
472
473 #if !LOG_DISABLED
474     int m_rootLayerUpdateCount;
475     int m_obligateCompositedLayerCount; // count of layer that have to be composited.
476     int m_secondaryCompositedLayerCount; // count of layers that have to be composited because of stacking or overlap.
477     double m_obligatoryBackingStoreBytes;
478     double m_secondaryBackingStoreBytes;
479 #endif
480 };
481
482
483 } // namespace WebCore
484
485 #endif // USE(ACCELERATED_COMPOSITING)
486
487 #endif // RenderLayerCompositor_h