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.
5 #ifndef CC_TREES_LAYER_TREE_HOST_H_
6 #define CC_TREES_LAYER_TREE_HOST_H_
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/scrollbar.h"
31 #include "cc/input/top_controls_state.h"
32 #include "cc/layers/layer_lists.h"
33 #include "cc/output/output_surface.h"
34 #include "cc/resources/resource_format.h"
35 #include "cc/resources/scoped_ui_resource.h"
36 #include "cc/trees/layer_tree_host_client.h"
37 #include "cc/trees/layer_tree_host_common.h"
38 #include "cc/trees/layer_tree_settings.h"
39 #include "cc/trees/occlusion_tracker.h"
40 #include "cc/trees/proxy.h"
41 #include "third_party/skia/include/core/SkColor.h"
42 #include "ui/gfx/rect.h"
46 class AnimationRegistrar;
47 class HeadsUpDisplayLayer;
49 class LayerTreeHostImpl;
50 class LayerTreeHostImplClient;
51 class LayerTreeHostSingleThreadClient;
52 class PrioritizedResource;
53 class PrioritizedResourceManager;
55 class RenderingStatsInstrumentation;
56 class ResourceProvider;
57 class ResourceUpdateQueue;
58 class SharedBitmapManager;
59 class TopControlsManager;
60 class UIResourceRequest;
61 struct RenderingStats;
62 struct ScrollAndScaleSet;
64 // Provides information on an Impl's rendering capabilities back to the
66 struct CC_EXPORT RendererCapabilities {
67 RendererCapabilities(ResourceFormat best_texture_format,
68 bool allow_partial_texture_updates,
69 bool using_offscreen_context3d,
71 bool using_shared_memory_resources);
73 RendererCapabilities();
74 ~RendererCapabilities();
76 // Duplicate any modification to this list to RendererCapabilitiesImpl.
77 ResourceFormat best_texture_format;
78 bool allow_partial_texture_updates;
79 bool using_offscreen_context3d;
81 bool using_shared_memory_resources;
84 class CC_EXPORT LayerTreeHost {
86 // The SharedBitmapManager will be used on the compositor thread.
87 static scoped_ptr<LayerTreeHost> CreateThreaded(
88 LayerTreeHostClient* client,
89 SharedBitmapManager* manager,
90 const LayerTreeSettings& settings,
91 scoped_refptr<base::SingleThreadTaskRunner> impl_task_runner);
93 static scoped_ptr<LayerTreeHost> CreateSingleThreaded(
94 LayerTreeHostClient* client,
95 LayerTreeHostSingleThreadClient* single_thread_client,
96 SharedBitmapManager* manager,
97 const LayerTreeSettings& settings);
98 virtual ~LayerTreeHost();
100 void SetLayerTreeHostClientReady();
102 void set_needs_filter_context() { needs_filter_context_ = true; }
103 bool needs_offscreen_context() const {
104 return needs_filter_context_;
107 // LayerTreeHost interface to Proxy.
108 void WillBeginMainFrame() {
109 client_->WillBeginMainFrame(source_frame_number_);
111 void DidBeginMainFrame();
112 void UpdateClientAnimations(base::TimeTicks monotonic_frame_begin_time);
113 void AnimateLayers(base::TimeTicks monotonic_frame_begin_time);
114 void DidStopFlinging();
116 void BeginCommitOnImplThread(LayerTreeHostImpl* host_impl);
117 void FinishCommitOnImplThread(LayerTreeHostImpl* host_impl);
119 void CommitComplete();
120 scoped_ptr<OutputSurface> CreateOutputSurface();
121 virtual scoped_ptr<LayerTreeHostImpl> CreateLayerTreeHostImpl(
122 LayerTreeHostImplClient* client);
123 void DidLoseOutputSurface();
124 bool output_surface_lost() const { return output_surface_lost_; }
127 CreateFailedButTryAgain,
128 CreateFailedAndGaveUp,
130 virtual CreateResult OnCreateAndInitializeOutputSurfaceAttempted(
132 void DidCommitAndDrawFrame() { client_->DidCommitAndDrawFrame(); }
133 void DidCompleteSwapBuffers() { client_->DidCompleteSwapBuffers(); }
134 void DeleteContentsTexturesOnImplThread(ResourceProvider* resource_provider);
135 virtual void AcquireLayerTextures();
136 // Returns false if we should abort this frame due to initialization failure.
137 bool InitializeOutputSurfaceIfNeeded();
138 bool UpdateLayers(ResourceUpdateQueue* queue);
140 LayerTreeHostClient* client() { return client_; }
141 const base::WeakPtr<InputHandler>& GetInputHandler() {
142 return input_handler_weak_ptr_;
145 void NotifyInputThrottledUntilCommit();
147 void Composite(base::TimeTicks frame_begin_time);
149 // Composites and attempts to read back the result into the provided
150 // buffer. If it wasn't possible, e.g. due to context lost, will return
152 bool CompositeAndReadback(void* pixels,
153 const gfx::Rect& rect_in_device_viewport);
155 void FinishAllRendering();
157 void SetDeferCommits(bool defer_commits);
160 virtual void DidDeferCommit();
162 int source_frame_number() const { return source_frame_number_; }
164 void SetNeedsDisplayOnAllLayers();
166 void CollectRenderingStats(RenderingStats* stats) const;
168 RenderingStatsInstrumentation* rendering_stats_instrumentation() const {
169 return rendering_stats_instrumentation_.get();
172 const RendererCapabilities& GetRendererCapabilities() const;
174 void SetNeedsAnimate();
175 virtual void SetNeedsUpdateLayers();
176 virtual void SetNeedsCommit();
177 virtual void SetNeedsFullTreeSync();
178 void SetNeedsRedraw();
179 void SetNeedsRedrawRect(const gfx::Rect& damage_rect);
180 bool CommitRequested() const;
181 bool BeginMainFrameRequested() const;
183 void SetNextCommitWaitsForActivation();
185 void SetNextCommitForcesRedraw();
187 void SetAnimationEvents(scoped_ptr<AnimationEventsVector> events,
188 base::Time wall_clock_time);
190 void SetRootLayer(scoped_refptr<Layer> root_layer);
191 Layer* root_layer() { return root_layer_.get(); }
192 const Layer* root_layer() const { return root_layer_.get(); }
193 const Layer* page_scale_layer() const { return page_scale_layer_.get(); }
194 void RegisterViewportLayers(
195 scoped_refptr<Layer> page_scale_layer,
196 scoped_refptr<Layer> inner_viewport_scroll_layer,
197 scoped_refptr<Layer> outer_viewport_scroll_layer);
198 Layer* inner_viewport_scroll_layer() const {
199 return inner_viewport_scroll_layer_.get();
201 Layer* outer_viewport_scroll_layer() const {
202 return outer_viewport_scroll_layer_.get();
205 const LayerTreeSettings& settings() const { return settings_; }
207 void SetDebugState(const LayerTreeDebugState& debug_state);
208 const LayerTreeDebugState& debug_state() const { return debug_state_; }
210 void SetViewportSize(const gfx::Size& device_viewport_size);
211 void SetOverdrawBottomHeight(float overdraw_bottom_height);
213 gfx::Size device_viewport_size() const { return device_viewport_size_; }
214 float overdraw_bottom_height() const { return overdraw_bottom_height_; }
216 void ApplyPageScaleDeltaFromImplSide(float page_scale_delta);
217 void SetPageScaleFactorAndLimits(float page_scale_factor,
218 float min_page_scale_factor,
219 float max_page_scale_factor);
220 float page_scale_factor() const { return page_scale_factor_; }
222 SkColor background_color() const { return background_color_; }
223 void set_background_color(SkColor color) { background_color_ = color; }
225 void set_has_transparent_background(bool transparent) {
226 has_transparent_background_ = transparent;
229 void SetOverhangBitmap(const SkBitmap& bitmap);
231 PrioritizedResourceManager* contents_texture_manager() const {
232 return contents_texture_manager_.get();
235 void SetVisible(bool visible);
236 bool visible() const { return visible_; }
238 void StartPageScaleAnimation(const gfx::Vector2d& target_offset,
241 base::TimeDelta duration);
243 void ApplyScrollAndScale(const ScrollAndScaleSet& info);
244 gfx::Vector2d DistributeScrollOffsetToViewports(const gfx::Vector2d offset,
247 void SetImplTransform(const gfx::Transform& transform);
249 // Virtual for tests.
250 virtual void StartRateLimiter();
251 virtual void StopRateLimiter();
255 bool AlwaysUsePartialTextureUpdates();
256 size_t MaxPartialTextureUpdates() const;
257 bool RequestPartialTextureUpdate();
259 void SetDeviceScaleFactor(float device_scale_factor);
260 float device_scale_factor() const { return device_scale_factor_; }
262 void UpdateTopControlsState(TopControlsState constraints,
263 TopControlsState current,
266 HeadsUpDisplayLayer* hud_layer() const { return hud_layer_.get(); }
268 Proxy* proxy() const { return proxy_.get(); }
270 AnimationRegistrar* animation_registrar() const {
271 return animation_registrar_.get();
274 // Obtains a thorough dump of the LayerTreeHost as a value.
275 scoped_ptr<base::Value> AsValue() const;
277 bool in_paint_layer_contents() const { return in_paint_layer_contents_; }
279 // CreateUIResource creates a resource given a bitmap. The bitmap is
280 // generated via an interface function, which is called when initializing the
281 // resource and when the resource has been lost (due to lost context). The
282 // parameter of the interface is a single boolean, which indicates whether the
283 // resource has been lost or not. CreateUIResource returns an Id of the
284 // resource, which is always positive.
285 virtual UIResourceId CreateUIResource(UIResourceClient* client);
286 // Deletes a UI resource. May safely be called more than once.
287 virtual void DeleteUIResource(UIResourceId id);
288 // Put the recreation of all UI resources into the resource queue after they
289 // were evicted on the impl thread.
290 void RecreateUIResources();
292 virtual gfx::Size GetUIResourceSize(UIResourceId id) const;
294 bool UsingSharedMemoryResources();
295 int id() const { return id_; }
297 bool ScheduleMicroBenchmark(const std::string& benchmark_name,
298 scoped_ptr<base::Value> value,
299 const MicroBenchmark::DoneCallback& callback);
301 // When a SwapPromiseMonitor is created on the main thread, it calls
302 // InsertSwapPromiseMonitor() to register itself with LayerTreeHost.
303 // When the monitor is destroyed, it calls RemoveSwapPromiseMonitor()
304 // to unregister itself.
305 void InsertSwapPromiseMonitor(SwapPromiseMonitor* monitor);
306 void RemoveSwapPromiseMonitor(SwapPromiseMonitor* monitor);
308 // Call this function when you expect there to be a swap buffer.
309 // See swap_promise.h for how to use SwapPromise.
310 void QueueSwapPromise(scoped_ptr<SwapPromise> swap_promise);
312 void BreakSwapPromises(SwapPromise::DidNotSwapReason reason);
315 LayerTreeHost(LayerTreeHostClient* client,
316 SharedBitmapManager* manager,
317 const LayerTreeSettings& settings);
318 void InitializeThreaded(
319 scoped_refptr<base::SingleThreadTaskRunner> impl_task_runner);
320 void InitializeSingleThreaded(
321 LayerTreeHostSingleThreadClient* single_thread_client);
322 void InitializeForTesting(scoped_ptr<Proxy> proxy_for_testing);
323 void SetOutputSurfaceLostForTesting(bool is_lost) {
324 output_surface_lost_ = is_lost;
327 MicroBenchmarkController micro_benchmark_controller_;
330 void InitializeProxy(scoped_ptr<Proxy> proxy);
332 void PaintLayerContents(
333 const RenderSurfaceLayerList& render_surface_layer_list,
334 ResourceUpdateQueue* queue,
335 bool* did_paint_content,
336 bool* need_more_updates);
337 void PaintMasksForRenderSurface(Layer* render_surface_layer,
338 ResourceUpdateQueue* queue,
339 bool* did_paint_content,
340 bool* need_more_updates);
341 bool UpdateLayers(Layer* root_layer, ResourceUpdateQueue* queue);
342 void UpdateHudLayer();
343 void TriggerPrepaint();
345 void ReduceMemoryUsage();
347 void PrioritizeTextures(
348 const RenderSurfaceLayerList& render_surface_layer_list,
349 OverdrawMetrics* metrics);
350 void SetPrioritiesForSurfaces(size_t surface_memory_bytes);
351 void SetPrioritiesForLayers(const RenderSurfaceLayerList& update_list);
352 size_t CalculateMemoryForRenderSurfaces(
353 const RenderSurfaceLayerList& update_list);
355 bool AnimateLayersRecursive(Layer* current, base::TimeTicks time);
357 struct UIResourceClientData {
358 UIResourceClient* client;
362 typedef base::hash_map<UIResourceId, UIResourceClientData>
364 UIResourceClientMap ui_resource_client_map_;
365 int next_ui_resource_id_;
367 typedef std::list<UIResourceRequest> UIResourceRequestQueue;
368 UIResourceRequestQueue ui_resource_request_queue_;
370 void CalculateLCDTextMetricsCallback(Layer* layer);
372 void NotifySwapPromiseMonitorsOfSetNeedsCommit();
375 bool needs_full_tree_sync_;
376 bool needs_filter_context_;
378 base::CancelableClosure prepaint_callback_;
380 LayerTreeHostClient* client_;
381 scoped_ptr<Proxy> proxy_;
383 int source_frame_number_;
384 scoped_ptr<RenderingStatsInstrumentation> rendering_stats_instrumentation_;
386 bool output_surface_can_be_initialized_;
387 bool output_surface_lost_;
388 int num_failed_recreate_attempts_;
390 scoped_refptr<Layer> root_layer_;
391 scoped_refptr<HeadsUpDisplayLayer> hud_layer_;
393 scoped_ptr<PrioritizedResourceManager> contents_texture_manager_;
394 scoped_ptr<PrioritizedResource> surface_memory_placeholder_;
396 base::WeakPtr<InputHandler> input_handler_weak_ptr_;
397 base::WeakPtr<TopControlsManager> top_controls_manager_weak_ptr_;
399 const LayerTreeSettings settings_;
400 LayerTreeDebugState debug_state_;
402 gfx::Size device_viewport_size_;
403 float overdraw_bottom_height_;
404 float device_scale_factor_;
408 base::OneShotTimer<LayerTreeHost> rate_limit_timer_;
410 float page_scale_factor_;
411 float min_page_scale_factor_;
412 float max_page_scale_factor_;
413 gfx::Transform impl_transform_;
414 bool trigger_idle_updates_;
416 SkColor background_color_;
417 bool has_transparent_background_;
419 // If set, this texture is used to fill in the parts of the screen not
420 // covered by layers.
421 scoped_ptr<ScopedUIResource> overhang_ui_resource_;
423 typedef ScopedPtrVector<PrioritizedResource> TextureList;
424 size_t partial_texture_update_requests_;
426 scoped_ptr<AnimationRegistrar> animation_registrar_;
428 struct PendingPageScaleAnimation {
429 gfx::Vector2d target_offset;
432 base::TimeDelta duration;
434 scoped_ptr<PendingPageScaleAnimation> pending_page_scale_animation_;
436 bool in_paint_layer_contents_;
438 static const int kTotalFramesToUseForLCDTextMetrics = 50;
439 int total_frames_used_for_lcd_text_metrics_;
441 struct LCDTextMetrics {
443 : total_num_cc_layers(0),
444 total_num_cc_layers_can_use_lcd_text(0),
445 total_num_cc_layers_will_use_lcd_text(0) {}
447 int64 total_num_cc_layers;
448 int64 total_num_cc_layers_can_use_lcd_text;
449 int64 total_num_cc_layers_will_use_lcd_text;
451 LCDTextMetrics lcd_text_metrics_;
453 bool next_commit_forces_redraw_;
455 scoped_refptr<Layer> page_scale_layer_;
456 scoped_refptr<Layer> inner_viewport_scroll_layer_;
457 scoped_refptr<Layer> outer_viewport_scroll_layer_;
459 SharedBitmapManager* shared_bitmap_manager_;
461 ScopedPtrVector<SwapPromise> swap_promise_list_;
462 std::set<SwapPromiseMonitor*> swap_promise_monitor_;
464 DISALLOW_COPY_AND_ASSIGN(LayerTreeHost);
469 #endif // CC_TREES_LAYER_TREE_HOST_H_