layer_tree_host.h revision bbcdd45c55eb7c4641ab97aef9889b0fc828e7d3
1// Copyright 2011 The Chromium Authors. All rights reserved.
2// Use of this source code is governed by a BSD-style license that can be
3// found in the LICENSE file.
4
5#ifndef CC_TREES_LAYER_TREE_HOST_H_
6#define CC_TREES_LAYER_TREE_HOST_H_
7
8#include <limits>
9#include <vector>
10
11#include "base/basictypes.h"
12#include "base/cancelable_callback.h"
13#include "base/containers/hash_tables.h"
14#include "base/memory/ref_counted.h"
15#include "base/memory/scoped_ptr.h"
16#include "base/memory/weak_ptr.h"
17#include "base/time/time.h"
18#include "cc/animation/animation_events.h"
19#include "cc/base/cc_export.h"
20#include "cc/base/scoped_ptr_vector.h"
21#include "cc/input/input_handler.h"
22#include "cc/input/scrollbar.h"
23#include "cc/input/top_controls_state.h"
24#include "cc/layers/layer_lists.h"
25#include "cc/output/output_surface.h"
26#include "cc/scheduler/rate_limiter.h"
27#include "cc/trees/layer_tree_host_client.h"
28#include "cc/trees/layer_tree_host_common.h"
29#include "cc/trees/layer_tree_settings.h"
30#include "cc/trees/occlusion_tracker.h"
31#include "cc/trees/proxy.h"
32#include "third_party/skia/include/core/SkColor.h"
33#include "ui/base/latency_info.h"
34#include "ui/gfx/rect.h"
35
36namespace WebKit { class WebGraphicsContext3D; }
37
38#if defined(COMPILER_GCC)
39namespace BASE_HASH_NAMESPACE {
40template <>
41struct hash<WebKit::WebGraphicsContext3D*> {
42  size_t operator()(WebKit::WebGraphicsContext3D* ptr) const {
43    return hash<size_t>()(reinterpret_cast<size_t>(ptr));
44  }
45};
46}  // namespace BASE_HASH_NAMESPACE
47#endif  // COMPILER
48
49namespace cc {
50
51class AnimationRegistrar;
52class HeadsUpDisplayLayer;
53class Layer;
54class LayerTreeHostImpl;
55class LayerTreeHostImplClient;
56class PrioritizedResourceManager;
57class PrioritizedResource;
58class Region;
59class RenderingStatsInstrumentation;
60class ResourceProvider;
61class ResourceUpdateQueue;
62class TopControlsManager;
63struct RenderingStats;
64struct ScrollAndScaleSet;
65
66// Provides information on an Impl's rendering capabilities back to the
67// LayerTreeHost.
68struct CC_EXPORT RendererCapabilities {
69  RendererCapabilities();
70  ~RendererCapabilities();
71
72  unsigned best_texture_format;
73  bool using_partial_swap;
74  bool using_set_visibility;
75  bool using_egl_image;
76  bool allow_partial_texture_updates;
77  bool using_offscreen_context3d;
78  int max_texture_size;
79  bool avoid_pow2_textures;
80  bool using_map_image;
81  bool using_shared_memory_resources;
82};
83
84class CC_EXPORT LayerTreeHost : NON_EXPORTED_BASE(public RateLimiterClient) {
85 public:
86  static scoped_ptr<LayerTreeHost> Create(
87      LayerTreeHostClient* client,
88      const LayerTreeSettings& settings,
89      scoped_refptr<base::SingleThreadTaskRunner> impl_task_runner);
90  virtual ~LayerTreeHost();
91
92  void SetLayerTreeHostClientReady();
93
94  // Returns true if any LayerTreeHost is alive.
95  static bool AnyLayerTreeHostInstanceExists();
96
97  void set_needs_filter_context() { needs_filter_context_ = true; }
98  bool needs_offscreen_context() const {
99    return needs_filter_context_;
100  }
101
102  // LayerTreeHost interface to Proxy.
103  void WillBeginFrame() { client_->WillBeginFrame(); }
104  void DidBeginFrame();
105  void UpdateClientAnimations(base::TimeTicks monotonic_frame_begin_time);
106  void AnimateLayers(base::TimeTicks monotonic_frame_begin_time);
107  void DidStopFlinging();
108  void Layout();
109  void BeginCommitOnImplThread(LayerTreeHostImpl* host_impl);
110  void FinishCommitOnImplThread(LayerTreeHostImpl* host_impl);
111  void WillCommit();
112  void CommitComplete();
113  scoped_ptr<OutputSurface> CreateOutputSurface();
114  virtual scoped_ptr<LayerTreeHostImpl> CreateLayerTreeHostImpl(
115      LayerTreeHostImplClient* client);
116  void DidLoseOutputSurface();
117  bool output_surface_lost() const { return output_surface_lost_; }
118  enum CreateResult {
119    CreateSucceeded,
120    CreateFailedButTryAgain,
121    CreateFailedAndGaveUp,
122  };
123  CreateResult OnCreateAndInitializeOutputSurfaceAttempted(bool success);
124  void DidCommitAndDrawFrame() { client_->DidCommitAndDrawFrame(); }
125  void DidCompleteSwapBuffers() { client_->DidCompleteSwapBuffers(); }
126  void DeleteContentsTexturesOnImplThread(ResourceProvider* resource_provider);
127  virtual void AcquireLayerTextures();
128  // Returns false if we should abort this frame due to initialization failure.
129  bool InitializeOutputSurfaceIfNeeded();
130  bool UpdateLayers(ResourceUpdateQueue* queue,
131                    size_t contents_memory_limit_bytes);
132
133  LayerTreeHostClient* client() { return client_; }
134  const base::WeakPtr<InputHandler>& GetInputHandler() {
135    return input_handler_weak_ptr_;
136  }
137
138  void Composite(base::TimeTicks frame_begin_time);
139
140  // Only used when compositing on the main thread.
141  void ScheduleComposite();
142
143  // Composites and attempts to read back the result into the provided
144  // buffer. If it wasn't possible, e.g. due to context lost, will return
145  // false.
146  bool CompositeAndReadback(void* pixels, gfx::Rect rect_in_device_viewport);
147
148  void FinishAllRendering();
149
150  void SetDeferCommits(bool defer_commits);
151
152  // Test only hook
153  virtual void DidDeferCommit();
154
155  int source_frame_number() const { return source_frame_number_; }
156
157  void SetNeedsDisplayOnAllLayers();
158
159  void CollectRenderingStats(RenderingStats* stats) const;
160
161  RenderingStatsInstrumentation* rendering_stats_instrumentation() const {
162    return rendering_stats_instrumentation_.get();
163  }
164
165  const RendererCapabilities& GetRendererCapabilities() const;
166
167  void SetNeedsAnimate();
168  virtual void SetNeedsCommit();
169  virtual void SetNeedsFullTreeSync();
170  void SetNeedsRedraw();
171  void SetNeedsRedrawRect(gfx::Rect damage_rect);
172  bool CommitRequested() const;
173
174  void SetAnimationEvents(scoped_ptr<AnimationEventsVector> events,
175                          base::Time wall_clock_time);
176
177  void SetRootLayer(scoped_refptr<Layer> root_layer);
178  Layer* root_layer() { return root_layer_.get(); }
179  const Layer* root_layer() const { return root_layer_.get(); }
180
181  const LayerTreeSettings& settings() const { return settings_; }
182
183  void SetDebugState(const LayerTreeDebugState& debug_state);
184  const LayerTreeDebugState& debug_state() const { return debug_state_; }
185
186  void SetViewportSize(gfx::Size device_viewport_size);
187  void SetOverdrawBottomHeight(float overdraw_bottom_height);
188
189  gfx::Size device_viewport_size() const { return device_viewport_size_; }
190  float overdraw_bottom_height() const { return overdraw_bottom_height_; }
191
192  void SetPageScaleFactorAndLimits(float page_scale_factor,
193                                   float min_page_scale_factor,
194                                   float max_page_scale_factor);
195  float page_scale_factor() const { return page_scale_factor_; }
196
197  SkColor background_color() const { return background_color_; }
198  void set_background_color(SkColor color) { background_color_ = color; }
199
200  void set_has_transparent_background(bool transparent) {
201    has_transparent_background_ = transparent;
202  }
203
204  PrioritizedResourceManager* contents_texture_manager() const {
205    return contents_texture_manager_.get();
206  }
207
208  void SetVisible(bool visible);
209  bool visible() const { return visible_; }
210
211  void StartPageScaleAnimation(gfx::Vector2d target_offset,
212                               bool use_anchor,
213                               float scale,
214                               base::TimeDelta duration);
215
216  void ApplyScrollAndScale(const ScrollAndScaleSet& info);
217
218  void SetImplTransform(const gfx::Transform& transform);
219  void SetLatencyInfo(const ui::LatencyInfo& latency_info);
220
221  virtual void StartRateLimiter(WebKit::WebGraphicsContext3D* context3d);
222  virtual void StopRateLimiter(WebKit::WebGraphicsContext3D* context3d);
223
224  // RateLimiterClient implementation.
225  virtual void RateLimit() OVERRIDE;
226
227  bool buffered_updates() const {
228    return settings_.max_partial_texture_updates !=
229        std::numeric_limits<size_t>::max();
230  }
231  bool RequestPartialTextureUpdate();
232
233  void SetDeviceScaleFactor(float device_scale_factor);
234  float device_scale_factor() const { return device_scale_factor_; }
235
236  void UpdateTopControlsState(TopControlsState constraints,
237                              TopControlsState current,
238                              bool animate);
239
240  HeadsUpDisplayLayer* hud_layer() const { return hud_layer_.get(); }
241
242  Proxy* proxy() const { return proxy_.get(); }
243
244  AnimationRegistrar* animation_registrar() const {
245    return animation_registrar_.get();
246  }
247
248  bool BlocksPendingCommit() const;
249
250  // Obtains a thorough dump of the LayerTreeHost as a value.
251  scoped_ptr<base::Value> AsValue() const;
252
253  bool in_paint_layer_contents() const { return in_paint_layer_contents_; }
254
255  bool UsingSharedMemoryResources();
256  int id() const { return tree_id_; }
257
258 protected:
259  LayerTreeHost(LayerTreeHostClient* client, const LayerTreeSettings& settings);
260  bool Initialize(scoped_refptr<base::SingleThreadTaskRunner> impl_task_runner);
261  bool InitializeForTesting(scoped_ptr<Proxy> proxy_for_testing);
262
263 private:
264  bool InitializeProxy(scoped_ptr<Proxy> proxy);
265
266  void PaintLayerContents(
267      const RenderSurfaceLayerList& render_surface_layer_list,
268      ResourceUpdateQueue* queue,
269      bool* did_paint_content,
270      bool* need_more_updates);
271  void PaintMasksForRenderSurface(Layer* render_surface_layer,
272                                  ResourceUpdateQueue* queue,
273                                  bool* did_paint_content,
274                                  bool* need_more_updates);
275  bool UpdateLayers(Layer* root_layer, ResourceUpdateQueue* queue);
276  void UpdateHudLayer();
277  void TriggerPrepaint();
278
279  void ReduceMemoryUsage();
280
281  void PrioritizeTextures(
282      const RenderSurfaceLayerList& render_surface_layer_list,
283      OverdrawMetrics* metrics);
284  void SetPrioritiesForSurfaces(size_t surface_memory_bytes);
285  void SetPrioritiesForLayers(const RenderSurfaceLayerList& update_list);
286  size_t CalculateMemoryForRenderSurfaces(
287      const RenderSurfaceLayerList& update_list);
288
289  bool AnimateLayersRecursive(Layer* current, base::TimeTicks time);
290
291  void CalculateLCDTextMetricsCallback(Layer* layer);
292
293  bool animating_;
294  bool needs_full_tree_sync_;
295  bool needs_filter_context_;
296
297  base::CancelableClosure prepaint_callback_;
298
299  LayerTreeHostClient* client_;
300  scoped_ptr<Proxy> proxy_;
301
302  int source_frame_number_;
303  scoped_ptr<RenderingStatsInstrumentation> rendering_stats_instrumentation_;
304
305  bool output_surface_can_be_initialized_;
306  bool output_surface_lost_;
307  int num_failed_recreate_attempts_;
308
309  scoped_refptr<Layer> root_layer_;
310  scoped_refptr<HeadsUpDisplayLayer> hud_layer_;
311
312  scoped_ptr<PrioritizedResourceManager> contents_texture_manager_;
313  scoped_ptr<PrioritizedResource> surface_memory_placeholder_;
314
315  base::WeakPtr<InputHandler> input_handler_weak_ptr_;
316  base::WeakPtr<TopControlsManager> top_controls_manager_weak_ptr_;
317
318  LayerTreeSettings settings_;
319  LayerTreeDebugState debug_state_;
320
321  gfx::Size device_viewport_size_;
322  float overdraw_bottom_height_;
323  float device_scale_factor_;
324
325  bool visible_;
326
327  typedef base::hash_map<WebKit::WebGraphicsContext3D*,
328                         scoped_refptr<RateLimiter> > RateLimiterMap;
329  RateLimiterMap rate_limiters_;
330
331  float page_scale_factor_;
332  float min_page_scale_factor_;
333  float max_page_scale_factor_;
334  gfx::Transform impl_transform_;
335  bool trigger_idle_updates_;
336
337  SkColor background_color_;
338  bool has_transparent_background_;
339
340  typedef ScopedPtrVector<PrioritizedResource> TextureList;
341  size_t partial_texture_update_requests_;
342
343  scoped_ptr<AnimationRegistrar> animation_registrar_;
344
345  struct PendingPageScaleAnimation {
346    gfx::Vector2d target_offset;
347    bool use_anchor;
348    float scale;
349    base::TimeDelta duration;
350  };
351  scoped_ptr<PendingPageScaleAnimation> pending_page_scale_animation_;
352
353  bool in_paint_layer_contents_;
354
355  ui::LatencyInfo latency_info_;
356
357  static const int kTotalFramesToUseForLCDTextMetrics = 50;
358  int total_frames_used_for_lcd_text_metrics_;
359
360  struct LCDTextMetrics {
361    LCDTextMetrics()
362        : total_num_cc_layers(0),
363          total_num_cc_layers_can_use_lcd_text(0),
364          total_num_cc_layers_will_use_lcd_text(0) {}
365
366    int64 total_num_cc_layers;
367    int64 total_num_cc_layers_can_use_lcd_text;
368    int64 total_num_cc_layers_will_use_lcd_text;
369  };
370  LCDTextMetrics lcd_text_metrics_;
371  int tree_id_;
372
373  DISALLOW_COPY_AND_ASSIGN(LayerTreeHost);
374};
375
376}  // namespace cc
377
378#endif  // CC_TREES_LAYER_TREE_HOST_H_
379