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 <list>
10#include <set>
11#include <string>
12#include <vector>
13
14#include "base/basictypes.h"
15#include "base/cancelable_callback.h"
16#include "base/containers/hash_tables.h"
17#include "base/memory/ref_counted.h"
18#include "base/memory/scoped_ptr.h"
19#include "base/memory/weak_ptr.h"
20#include "base/time/time.h"
21#include "base/timer/timer.h"
22#include "cc/animation/animation_events.h"
23#include "cc/base/cc_export.h"
24#include "cc/base/scoped_ptr_vector.h"
25#include "cc/base/swap_promise.h"
26#include "cc/base/swap_promise_monitor.h"
27#include "cc/debug/micro_benchmark.h"
28#include "cc/debug/micro_benchmark_controller.h"
29#include "cc/input/input_handler.h"
30#include "cc/input/layer_selection_bound.h"
31#include "cc/input/scrollbar.h"
32#include "cc/input/top_controls_state.h"
33#include "cc/layers/layer_lists.h"
34#include "cc/output/output_surface.h"
35#include "cc/resources/resource_format.h"
36#include "cc/resources/scoped_ui_resource.h"
37#include "cc/trees/layer_tree_host_client.h"
38#include "cc/trees/layer_tree_host_common.h"
39#include "cc/trees/layer_tree_settings.h"
40#include "cc/trees/proxy.h"
41#include "third_party/skia/include/core/SkColor.h"
42#include "ui/gfx/rect.h"
43
44namespace cc {
45
46class AnimationRegistrar;
47class HeadsUpDisplayLayer;
48class Layer;
49class LayerTreeHostImpl;
50class LayerTreeHostImplClient;
51class LayerTreeHostSingleThreadClient;
52class PrioritizedResource;
53class PrioritizedResourceManager;
54class Region;
55class RenderingStatsInstrumentation;
56class ResourceProvider;
57class ResourceUpdateQueue;
58class SharedBitmapManager;
59class TopControlsManager;
60class UIResourceRequest;
61struct RenderingStats;
62struct ScrollAndScaleSet;
63
64// Provides information on an Impl's rendering capabilities back to the
65// LayerTreeHost.
66struct CC_EXPORT RendererCapabilities {
67  RendererCapabilities(ResourceFormat best_texture_format,
68                       bool allow_partial_texture_updates,
69                       int max_texture_size,
70                       bool using_shared_memory_resources);
71
72  RendererCapabilities();
73  ~RendererCapabilities();
74
75  // Duplicate any modification to this list to RendererCapabilitiesImpl.
76  ResourceFormat best_texture_format;
77  bool allow_partial_texture_updates;
78  int max_texture_size;
79  bool using_shared_memory_resources;
80};
81
82class CC_EXPORT LayerTreeHost {
83 public:
84  // The SharedBitmapManager will be used on the compositor thread.
85  static scoped_ptr<LayerTreeHost> CreateThreaded(
86      LayerTreeHostClient* client,
87      SharedBitmapManager* manager,
88      const LayerTreeSettings& settings,
89      scoped_refptr<base::SingleThreadTaskRunner> main_task_runner,
90      scoped_refptr<base::SingleThreadTaskRunner> impl_task_runner);
91
92  static scoped_ptr<LayerTreeHost> CreateSingleThreaded(
93      LayerTreeHostClient* client,
94      LayerTreeHostSingleThreadClient* single_thread_client,
95      SharedBitmapManager* manager,
96      const LayerTreeSettings& settings,
97      scoped_refptr<base::SingleThreadTaskRunner> main_task_runner);
98  virtual ~LayerTreeHost();
99
100  void SetLayerTreeHostClientReady();
101
102  // LayerTreeHost interface to Proxy.
103  void WillBeginMainFrame() {
104    client_->WillBeginMainFrame(source_frame_number_);
105  }
106  void DidBeginMainFrame();
107  void BeginMainFrame(const BeginFrameArgs& args);
108  void AnimateLayers(base::TimeTicks monotonic_frame_begin_time);
109  void DidStopFlinging();
110  void Layout();
111  void BeginCommitOnImplThread(LayerTreeHostImpl* host_impl);
112  void FinishCommitOnImplThread(LayerTreeHostImpl* host_impl);
113  void WillCommit();
114  void CommitComplete();
115  void SetOutputSurface(scoped_ptr<OutputSurface> output_surface);
116  void RequestNewOutputSurface();
117  virtual scoped_ptr<LayerTreeHostImpl> CreateLayerTreeHostImpl(
118      LayerTreeHostImplClient* client);
119  void DidLoseOutputSurface();
120  bool output_surface_lost() const { return output_surface_lost_; }
121  virtual void OnCreateAndInitializeOutputSurfaceAttempted(bool success);
122  void DidCommitAndDrawFrame() { client_->DidCommitAndDrawFrame(); }
123  void DidCompleteSwapBuffers() { client_->DidCompleteSwapBuffers(); }
124  void DeleteContentsTexturesOnImplThread(ResourceProvider* resource_provider);
125  bool UpdateLayers(ResourceUpdateQueue* queue);
126
127  LayerTreeHostClient* client() { return client_; }
128  const base::WeakPtr<InputHandler>& GetInputHandler() {
129    return input_handler_weak_ptr_;
130  }
131
132  void NotifyInputThrottledUntilCommit();
133
134  void Composite(base::TimeTicks frame_begin_time);
135
136  void FinishAllRendering();
137
138  void SetDeferCommits(bool defer_commits);
139
140  // Test only hook
141  virtual void DidDeferCommit();
142
143  int source_frame_number() const { return source_frame_number_; }
144
145  void SetNeedsDisplayOnAllLayers();
146
147  void CollectRenderingStats(RenderingStats* stats) const;
148
149  RenderingStatsInstrumentation* rendering_stats_instrumentation() const {
150    return rendering_stats_instrumentation_.get();
151  }
152
153  const RendererCapabilities& GetRendererCapabilities() const;
154
155  void SetNeedsAnimate();
156  virtual void SetNeedsUpdateLayers();
157  virtual void SetNeedsCommit();
158  virtual void SetNeedsFullTreeSync();
159  void SetNeedsRedraw();
160  void SetNeedsRedrawRect(const gfx::Rect& damage_rect);
161  bool CommitRequested() const;
162  bool BeginMainFrameRequested() const;
163
164  void SetNextCommitWaitsForActivation();
165
166  void SetNextCommitForcesRedraw();
167
168  void SetAnimationEvents(scoped_ptr<AnimationEventsVector> events);
169
170  void SetRootLayer(scoped_refptr<Layer> root_layer);
171  Layer* root_layer() { return root_layer_.get(); }
172  const Layer* root_layer() const { return root_layer_.get(); }
173  const Layer* page_scale_layer() const { return page_scale_layer_.get(); }
174  void RegisterViewportLayers(
175      scoped_refptr<Layer> page_scale_layer,
176      scoped_refptr<Layer> inner_viewport_scroll_layer,
177      scoped_refptr<Layer> outer_viewport_scroll_layer);
178  Layer* inner_viewport_scroll_layer() const {
179    return inner_viewport_scroll_layer_.get();
180  }
181  Layer* outer_viewport_scroll_layer() const {
182    return outer_viewport_scroll_layer_.get();
183  }
184
185  void RegisterSelection(const LayerSelectionBound& start,
186                         const LayerSelectionBound& end);
187
188  const LayerTreeSettings& settings() const { return settings_; }
189
190  void SetDebugState(const LayerTreeDebugState& debug_state);
191  const LayerTreeDebugState& debug_state() const { return debug_state_; }
192
193  bool has_gpu_rasterization_trigger() const {
194    return has_gpu_rasterization_trigger_;
195  }
196  void SetHasGpuRasterizationTrigger(bool has_trigger);
197  bool UseGpuRasterization() const;
198
199  void SetViewportSize(const gfx::Size& device_viewport_size);
200  void SetTopControlsLayoutHeight(float height);
201  void SetTopControlsContentOffset(float offset);
202
203  gfx::Size device_viewport_size() const { return device_viewport_size_; }
204
205  void ApplyPageScaleDeltaFromImplSide(float page_scale_delta);
206  void SetPageScaleFactorAndLimits(float page_scale_factor,
207                                   float min_page_scale_factor,
208                                   float max_page_scale_factor);
209  float page_scale_factor() const { return page_scale_factor_; }
210
211  SkColor background_color() const { return background_color_; }
212  void set_background_color(SkColor color) { background_color_ = color; }
213
214  void set_has_transparent_background(bool transparent) {
215    has_transparent_background_ = transparent;
216  }
217
218  void SetOverhangBitmap(const SkBitmap& bitmap);
219
220  PrioritizedResourceManager* contents_texture_manager() const {
221    return contents_texture_manager_.get();
222  }
223
224  void SetVisible(bool visible);
225  bool visible() const { return visible_; }
226
227  void StartPageScaleAnimation(const gfx::Vector2d& target_offset,
228                               bool use_anchor,
229                               float scale,
230                               base::TimeDelta duration);
231
232  void ApplyScrollAndScale(ScrollAndScaleSet* info);
233  void SetImplTransform(const gfx::Transform& transform);
234
235  // Virtual for tests.
236  virtual void StartRateLimiter();
237  virtual void StopRateLimiter();
238
239  void RateLimit();
240
241  bool AlwaysUsePartialTextureUpdates();
242  size_t MaxPartialTextureUpdates() const;
243  bool RequestPartialTextureUpdate();
244
245  void SetDeviceScaleFactor(float device_scale_factor);
246  float device_scale_factor() const { return device_scale_factor_; }
247
248  void UpdateTopControlsState(TopControlsState constraints,
249                              TopControlsState current,
250                              bool animate);
251
252  HeadsUpDisplayLayer* hud_layer() const { return hud_layer_.get(); }
253
254  Proxy* proxy() const { return proxy_.get(); }
255
256  AnimationRegistrar* animation_registrar() const {
257    return animation_registrar_.get();
258  }
259
260  // Obtains a thorough dump of the LayerTreeHost as a value.
261  void AsValueInto(base::debug::TracedValue* value) const;
262
263  bool in_paint_layer_contents() const { return in_paint_layer_contents_; }
264
265  // CreateUIResource creates a resource given a bitmap.  The bitmap is
266  // generated via an interface function, which is called when initializing the
267  // resource and when the resource has been lost (due to lost context).  The
268  // parameter of the interface is a single boolean, which indicates whether the
269  // resource has been lost or not.  CreateUIResource returns an Id of the
270  // resource, which is always positive.
271  virtual UIResourceId CreateUIResource(UIResourceClient* client);
272  // Deletes a UI resource.  May safely be called more than once.
273  virtual void DeleteUIResource(UIResourceId id);
274  // Put the recreation of all UI resources into the resource queue after they
275  // were evicted on the impl thread.
276  void RecreateUIResources();
277
278  virtual gfx::Size GetUIResourceSize(UIResourceId id) const;
279
280  bool UsingSharedMemoryResources();
281  int id() const { return id_; }
282
283  // Returns the id of the benchmark on success, 0 otherwise.
284  int ScheduleMicroBenchmark(const std::string& benchmark_name,
285                             scoped_ptr<base::Value> value,
286                             const MicroBenchmark::DoneCallback& callback);
287  // Returns true if the message was successfully delivered and handled.
288  bool SendMessageToMicroBenchmark(int id, scoped_ptr<base::Value> value);
289
290  // When a SwapPromiseMonitor is created on the main thread, it calls
291  // InsertSwapPromiseMonitor() to register itself with LayerTreeHost.
292  // When the monitor is destroyed, it calls RemoveSwapPromiseMonitor()
293  // to unregister itself.
294  void InsertSwapPromiseMonitor(SwapPromiseMonitor* monitor);
295  void RemoveSwapPromiseMonitor(SwapPromiseMonitor* monitor);
296
297  // Call this function when you expect there to be a swap buffer.
298  // See swap_promise.h for how to use SwapPromise.
299  void QueueSwapPromise(scoped_ptr<SwapPromise> swap_promise);
300
301  void BreakSwapPromises(SwapPromise::DidNotSwapReason reason);
302
303 protected:
304  LayerTreeHost(LayerTreeHostClient* client,
305                SharedBitmapManager* manager,
306                const LayerTreeSettings& settings);
307  void InitializeThreaded(
308      scoped_refptr<base::SingleThreadTaskRunner> main_task_runner,
309      scoped_refptr<base::SingleThreadTaskRunner> impl_task_runner);
310  void InitializeSingleThreaded(
311      LayerTreeHostSingleThreadClient* single_thread_client,
312      scoped_refptr<base::SingleThreadTaskRunner> main_task_runner);
313  void InitializeForTesting(scoped_ptr<Proxy> proxy_for_testing);
314  void SetOutputSurfaceLostForTesting(bool is_lost) {
315    output_surface_lost_ = is_lost;
316  }
317
318  MicroBenchmarkController micro_benchmark_controller_;
319
320 private:
321  void InitializeProxy(scoped_ptr<Proxy> proxy);
322
323  void PaintLayerContents(
324      const RenderSurfaceLayerList& render_surface_layer_list,
325      ResourceUpdateQueue* queue,
326      bool* did_paint_content,
327      bool* need_more_updates);
328  void PaintMasksForRenderSurface(Layer* render_surface_layer,
329                                  ResourceUpdateQueue* queue,
330                                  bool* did_paint_content,
331                                  bool* need_more_updates);
332  bool UpdateLayers(Layer* root_layer, ResourceUpdateQueue* queue);
333  void UpdateHudLayer();
334  void TriggerPrepaint();
335
336  void ReduceMemoryUsage();
337
338  void PrioritizeTextures(
339      const RenderSurfaceLayerList& render_surface_layer_list);
340  void SetPrioritiesForSurfaces(size_t surface_memory_bytes);
341  void SetPrioritiesForLayers(const RenderSurfaceLayerList& update_list);
342  size_t CalculateMemoryForRenderSurfaces(
343      const RenderSurfaceLayerList& update_list);
344
345  bool AnimateLayersRecursive(Layer* current, base::TimeTicks time);
346
347  struct UIResourceClientData {
348    UIResourceClient* client;
349    gfx::Size size;
350  };
351
352  typedef base::hash_map<UIResourceId, UIResourceClientData>
353      UIResourceClientMap;
354  UIResourceClientMap ui_resource_client_map_;
355  int next_ui_resource_id_;
356
357  typedef std::list<UIResourceRequest> UIResourceRequestQueue;
358  UIResourceRequestQueue ui_resource_request_queue_;
359
360  void RecordGpuRasterizationHistogram();
361  void CalculateLCDTextMetricsCallback(Layer* layer);
362
363  void NotifySwapPromiseMonitorsOfSetNeedsCommit();
364
365  bool inside_begin_main_frame_;
366  bool needs_full_tree_sync_;
367
368  base::CancelableClosure prepaint_callback_;
369
370  LayerTreeHostClient* client_;
371  scoped_ptr<Proxy> proxy_;
372
373  int source_frame_number_;
374  scoped_ptr<RenderingStatsInstrumentation> rendering_stats_instrumentation_;
375
376  bool output_surface_lost_;
377  int num_failed_recreate_attempts_;
378
379  scoped_refptr<Layer> root_layer_;
380  scoped_refptr<HeadsUpDisplayLayer> hud_layer_;
381
382  scoped_ptr<PrioritizedResourceManager> contents_texture_manager_;
383  scoped_ptr<PrioritizedResource> surface_memory_placeholder_;
384
385  base::WeakPtr<InputHandler> input_handler_weak_ptr_;
386  base::WeakPtr<TopControlsManager> top_controls_manager_weak_ptr_;
387
388  const LayerTreeSettings settings_;
389  LayerTreeDebugState debug_state_;
390
391  gfx::Size device_viewport_size_;
392  float top_controls_layout_height_;
393  float top_controls_content_offset_;
394  float device_scale_factor_;
395
396  bool visible_;
397
398  base::OneShotTimer<LayerTreeHost> rate_limit_timer_;
399
400  float page_scale_factor_;
401  float min_page_scale_factor_;
402  float max_page_scale_factor_;
403  gfx::Transform impl_transform_;
404  bool has_gpu_rasterization_trigger_;
405  bool content_is_suitable_for_gpu_rasterization_;
406  bool gpu_rasterization_histogram_recorded_;
407
408  SkColor background_color_;
409  bool has_transparent_background_;
410
411  // If set, this texture is used to fill in the parts of the screen not
412  // covered by layers.
413  scoped_ptr<ScopedUIResource> overhang_ui_resource_;
414
415  typedef ScopedPtrVector<PrioritizedResource> TextureList;
416  size_t partial_texture_update_requests_;
417
418  scoped_ptr<AnimationRegistrar> animation_registrar_;
419
420  struct PendingPageScaleAnimation {
421    gfx::Vector2d target_offset;
422    bool use_anchor;
423    float scale;
424    base::TimeDelta duration;
425  };
426  scoped_ptr<PendingPageScaleAnimation> pending_page_scale_animation_;
427
428  bool in_paint_layer_contents_;
429
430  static const int kTotalFramesToUseForLCDTextMetrics = 50;
431  int total_frames_used_for_lcd_text_metrics_;
432
433  struct LCDTextMetrics {
434    LCDTextMetrics()
435        : total_num_cc_layers(0),
436          total_num_cc_layers_can_use_lcd_text(0),
437          total_num_cc_layers_will_use_lcd_text(0) {}
438
439    int64 total_num_cc_layers;
440    int64 total_num_cc_layers_can_use_lcd_text;
441    int64 total_num_cc_layers_will_use_lcd_text;
442  };
443  LCDTextMetrics lcd_text_metrics_;
444  int id_;
445  bool next_commit_forces_redraw_;
446
447  scoped_refptr<Layer> page_scale_layer_;
448  scoped_refptr<Layer> inner_viewport_scroll_layer_;
449  scoped_refptr<Layer> outer_viewport_scroll_layer_;
450
451  LayerSelectionBound selection_start_;
452  LayerSelectionBound selection_end_;
453
454  SharedBitmapManager* shared_bitmap_manager_;
455
456  ScopedPtrVector<SwapPromise> swap_promise_list_;
457  std::set<SwapPromiseMonitor*> swap_promise_monitor_;
458
459  DISALLOW_COPY_AND_ASSIGN(LayerTreeHost);
460};
461
462}  // namespace cc
463
464#endif  // CC_TREES_LAYER_TREE_HOST_H_
465