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