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/proxy.h"
40 #include "third_party/skia/include/core/SkColor.h"
41 #include "ui/gfx/rect.h"
45 class AnimationRegistrar;
46 class HeadsUpDisplayLayer;
48 class LayerTreeHostImpl;
49 class LayerTreeHostImplClient;
50 class LayerTreeHostSingleThreadClient;
51 class PrioritizedResource;
52 class PrioritizedResourceManager;
54 class RenderingStatsInstrumentation;
55 class ResourceProvider;
56 class ResourceUpdateQueue;
57 class SharedBitmapManager;
58 class TopControlsManager;
59 class UIResourceRequest;
60 struct RenderingStats;
61 struct ScrollAndScaleSet;
63 // Provides information on an Impl's rendering capabilities back to the
65 struct CC_EXPORT RendererCapabilities {
66 RendererCapabilities(ResourceFormat best_texture_format,
67 bool allow_partial_texture_updates,
69 bool using_shared_memory_resources);
71 RendererCapabilities();
72 ~RendererCapabilities();
74 // Duplicate any modification to this list to RendererCapabilitiesImpl.
75 ResourceFormat best_texture_format;
76 bool allow_partial_texture_updates;
78 bool using_shared_memory_resources;
81 class CC_EXPORT LayerTreeHost {
83 // The SharedBitmapManager will be used on the compositor thread.
84 static scoped_ptr<LayerTreeHost> CreateThreaded(
85 LayerTreeHostClient* client,
86 SharedBitmapManager* manager,
87 const LayerTreeSettings& settings,
88 scoped_refptr<base::SingleThreadTaskRunner> impl_task_runner);
90 static scoped_ptr<LayerTreeHost> CreateSingleThreaded(
91 LayerTreeHostClient* client,
92 LayerTreeHostSingleThreadClient* single_thread_client,
93 SharedBitmapManager* manager,
94 const LayerTreeSettings& settings);
95 virtual ~LayerTreeHost();
97 void SetLayerTreeHostClientReady();
99 // LayerTreeHost interface to Proxy.
100 void WillBeginMainFrame() {
101 client_->WillBeginMainFrame(source_frame_number_);
103 void DidBeginMainFrame();
104 void UpdateClientAnimations(base::TimeTicks monotonic_frame_begin_time);
105 void AnimateLayers(base::TimeTicks monotonic_frame_begin_time);
106 void DidStopFlinging();
108 void BeginCommitOnImplThread(LayerTreeHostImpl* host_impl);
109 void FinishCommitOnImplThread(LayerTreeHostImpl* host_impl);
111 void CommitComplete();
112 scoped_ptr<OutputSurface> CreateOutputSurface();
113 virtual scoped_ptr<LayerTreeHostImpl> CreateLayerTreeHostImpl(
114 LayerTreeHostImplClient* client);
115 void DidLoseOutputSurface();
116 bool output_surface_lost() const { return output_surface_lost_; }
117 virtual void OnCreateAndInitializeOutputSurfaceAttempted(bool success);
118 void DidCommitAndDrawFrame() { client_->DidCommitAndDrawFrame(); }
119 void DidCompleteSwapBuffers() { client_->DidCompleteSwapBuffers(); }
120 void DeleteContentsTexturesOnImplThread(ResourceProvider* resource_provider);
121 // Returns false if we should abort this frame due to initialization failure.
122 bool InitializeOutputSurfaceIfNeeded();
123 bool UpdateLayers(ResourceUpdateQueue* queue);
125 LayerTreeHostClient* client() { return client_; }
126 const base::WeakPtr<InputHandler>& GetInputHandler() {
127 return input_handler_weak_ptr_;
130 void NotifyInputThrottledUntilCommit();
132 void Composite(base::TimeTicks frame_begin_time);
134 // Composites and attempts to read back the result into the provided
135 // buffer. If it wasn't possible, e.g. due to context lost, will return
137 bool CompositeAndReadback(void* pixels,
138 const gfx::Rect& rect_in_device_viewport);
140 void FinishAllRendering();
142 void SetDeferCommits(bool defer_commits);
145 virtual void DidDeferCommit();
147 int source_frame_number() const { return source_frame_number_; }
149 void SetNeedsDisplayOnAllLayers();
151 void CollectRenderingStats(RenderingStats* stats) const;
153 RenderingStatsInstrumentation* rendering_stats_instrumentation() const {
154 return rendering_stats_instrumentation_.get();
157 const RendererCapabilities& GetRendererCapabilities() const;
159 void SetNeedsAnimate();
160 virtual void SetNeedsUpdateLayers();
161 virtual void SetNeedsCommit();
162 virtual void SetNeedsFullTreeSync();
163 void SetNeedsRedraw();
164 void SetNeedsRedrawRect(const gfx::Rect& damage_rect);
165 bool CommitRequested() const;
166 bool BeginMainFrameRequested() const;
168 void SetNextCommitWaitsForActivation();
170 void SetNextCommitForcesRedraw();
172 void SetAnimationEvents(scoped_ptr<AnimationEventsVector> events);
174 void SetRootLayer(scoped_refptr<Layer> root_layer);
175 Layer* root_layer() { return root_layer_.get(); }
176 const Layer* root_layer() const { return root_layer_.get(); }
177 const Layer* page_scale_layer() const { return page_scale_layer_.get(); }
178 void RegisterViewportLayers(
179 scoped_refptr<Layer> page_scale_layer,
180 scoped_refptr<Layer> inner_viewport_scroll_layer,
181 scoped_refptr<Layer> outer_viewport_scroll_layer);
182 Layer* inner_viewport_scroll_layer() const {
183 return inner_viewport_scroll_layer_.get();
185 Layer* outer_viewport_scroll_layer() const {
186 return outer_viewport_scroll_layer_.get();
189 const LayerTreeSettings& settings() const { return settings_; }
191 void SetDebugState(const LayerTreeDebugState& debug_state);
192 const LayerTreeDebugState& debug_state() const { return debug_state_; }
194 bool has_gpu_rasterization_trigger() const {
195 return has_gpu_rasterization_trigger_;
197 void set_has_gpu_rasterization_trigger(bool has_trigger) {
198 has_gpu_rasterization_trigger_ = has_trigger;
200 bool UseGpuRasterization() const;
202 void SetViewportSize(const gfx::Size& device_viewport_size);
203 void SetOverdrawBottomHeight(float overdraw_bottom_height);
205 gfx::Size device_viewport_size() const { return device_viewport_size_; }
206 float overdraw_bottom_height() const { return overdraw_bottom_height_; }
208 void ApplyPageScaleDeltaFromImplSide(float page_scale_delta);
209 void SetPageScaleFactorAndLimits(float page_scale_factor,
210 float min_page_scale_factor,
211 float max_page_scale_factor);
212 float page_scale_factor() const { return page_scale_factor_; }
214 SkColor background_color() const { return background_color_; }
215 void set_background_color(SkColor color) { background_color_ = color; }
217 void set_has_transparent_background(bool transparent) {
218 has_transparent_background_ = transparent;
221 void SetOverhangBitmap(const SkBitmap& bitmap);
223 PrioritizedResourceManager* contents_texture_manager() const {
224 return contents_texture_manager_.get();
227 void SetVisible(bool visible);
228 bool visible() const { return visible_; }
230 void StartPageScaleAnimation(const gfx::Vector2d& target_offset,
233 base::TimeDelta duration);
235 void ApplyScrollAndScale(const ScrollAndScaleSet& info);
236 void SetImplTransform(const gfx::Transform& transform);
238 // Virtual for tests.
239 virtual void StartRateLimiter();
240 virtual void StopRateLimiter();
244 bool AlwaysUsePartialTextureUpdates();
245 size_t MaxPartialTextureUpdates() const;
246 bool RequestPartialTextureUpdate();
248 void SetDeviceScaleFactor(float device_scale_factor);
249 float device_scale_factor() const { return device_scale_factor_; }
251 void UpdateTopControlsState(TopControlsState constraints,
252 TopControlsState current,
255 HeadsUpDisplayLayer* hud_layer() const { return hud_layer_.get(); }
257 Proxy* proxy() const { return proxy_.get(); }
259 AnimationRegistrar* animation_registrar() const {
260 return animation_registrar_.get();
263 // Obtains a thorough dump of the LayerTreeHost as a value.
264 scoped_ptr<base::Value> AsValue() const;
266 bool in_paint_layer_contents() const { return in_paint_layer_contents_; }
268 // CreateUIResource creates a resource given a bitmap. The bitmap is
269 // generated via an interface function, which is called when initializing the
270 // resource and when the resource has been lost (due to lost context). The
271 // parameter of the interface is a single boolean, which indicates whether the
272 // resource has been lost or not. CreateUIResource returns an Id of the
273 // resource, which is always positive.
274 virtual UIResourceId CreateUIResource(UIResourceClient* client);
275 // Deletes a UI resource. May safely be called more than once.
276 virtual void DeleteUIResource(UIResourceId id);
277 // Put the recreation of all UI resources into the resource queue after they
278 // were evicted on the impl thread.
279 void RecreateUIResources();
281 virtual gfx::Size GetUIResourceSize(UIResourceId id) const;
283 bool UsingSharedMemoryResources();
284 int id() const { return id_; }
286 bool ScheduleMicroBenchmark(const std::string& benchmark_name,
287 scoped_ptr<base::Value> value,
288 const MicroBenchmark::DoneCallback& callback);
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);
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);
301 void BreakSwapPromises(SwapPromise::DidNotSwapReason reason);
304 LayerTreeHost(LayerTreeHostClient* client,
305 SharedBitmapManager* manager,
306 const LayerTreeSettings& settings);
307 void InitializeThreaded(
308 scoped_refptr<base::SingleThreadTaskRunner> impl_task_runner);
309 void InitializeSingleThreaded(
310 LayerTreeHostSingleThreadClient* single_thread_client);
311 void InitializeForTesting(scoped_ptr<Proxy> proxy_for_testing);
312 void SetOutputSurfaceLostForTesting(bool is_lost) {
313 output_surface_lost_ = is_lost;
316 MicroBenchmarkController micro_benchmark_controller_;
319 void InitializeProxy(scoped_ptr<Proxy> proxy);
321 void PaintLayerContents(
322 const RenderSurfaceLayerList& render_surface_layer_list,
323 ResourceUpdateQueue* queue,
324 bool* did_paint_content,
325 bool* need_more_updates);
326 void PaintMasksForRenderSurface(Layer* render_surface_layer,
327 ResourceUpdateQueue* queue,
328 bool* did_paint_content,
329 bool* need_more_updates);
330 bool UpdateLayers(Layer* root_layer, ResourceUpdateQueue* queue);
331 void UpdateHudLayer();
332 void TriggerPrepaint();
334 void ReduceMemoryUsage();
336 void PrioritizeTextures(
337 const RenderSurfaceLayerList& render_surface_layer_list);
338 void SetPrioritiesForSurfaces(size_t surface_memory_bytes);
339 void SetPrioritiesForLayers(const RenderSurfaceLayerList& update_list);
340 size_t CalculateMemoryForRenderSurfaces(
341 const RenderSurfaceLayerList& update_list);
343 bool AnimateLayersRecursive(Layer* current, base::TimeTicks time);
345 struct UIResourceClientData {
346 UIResourceClient* client;
350 typedef base::hash_map<UIResourceId, UIResourceClientData>
352 UIResourceClientMap ui_resource_client_map_;
353 int next_ui_resource_id_;
355 typedef std::list<UIResourceRequest> UIResourceRequestQueue;
356 UIResourceRequestQueue ui_resource_request_queue_;
358 void CalculateLCDTextMetricsCallback(Layer* layer);
360 void NotifySwapPromiseMonitorsOfSetNeedsCommit();
363 bool needs_full_tree_sync_;
365 base::CancelableClosure prepaint_callback_;
367 LayerTreeHostClient* client_;
368 scoped_ptr<Proxy> proxy_;
370 int source_frame_number_;
371 scoped_ptr<RenderingStatsInstrumentation> rendering_stats_instrumentation_;
373 bool output_surface_can_be_initialized_;
374 bool output_surface_lost_;
375 int num_failed_recreate_attempts_;
377 scoped_refptr<Layer> root_layer_;
378 scoped_refptr<HeadsUpDisplayLayer> hud_layer_;
380 scoped_ptr<PrioritizedResourceManager> contents_texture_manager_;
381 scoped_ptr<PrioritizedResource> surface_memory_placeholder_;
383 base::WeakPtr<InputHandler> input_handler_weak_ptr_;
384 base::WeakPtr<TopControlsManager> top_controls_manager_weak_ptr_;
386 const LayerTreeSettings settings_;
387 LayerTreeDebugState debug_state_;
389 gfx::Size device_viewport_size_;
390 float overdraw_bottom_height_;
391 float device_scale_factor_;
395 base::OneShotTimer<LayerTreeHost> rate_limit_timer_;
397 float page_scale_factor_;
398 float min_page_scale_factor_;
399 float max_page_scale_factor_;
400 gfx::Transform impl_transform_;
401 bool trigger_idle_updates_;
402 bool has_gpu_rasterization_trigger_;
403 bool content_is_suitable_for_gpu_rasterization_;
405 SkColor background_color_;
406 bool has_transparent_background_;
408 // If set, this texture is used to fill in the parts of the screen not
409 // covered by layers.
410 scoped_ptr<ScopedUIResource> overhang_ui_resource_;
412 typedef ScopedPtrVector<PrioritizedResource> TextureList;
413 size_t partial_texture_update_requests_;
415 scoped_ptr<AnimationRegistrar> animation_registrar_;
417 struct PendingPageScaleAnimation {
418 gfx::Vector2d target_offset;
421 base::TimeDelta duration;
423 scoped_ptr<PendingPageScaleAnimation> pending_page_scale_animation_;
425 bool in_paint_layer_contents_;
427 static const int kTotalFramesToUseForLCDTextMetrics = 50;
428 int total_frames_used_for_lcd_text_metrics_;
430 struct LCDTextMetrics {
432 : total_num_cc_layers(0),
433 total_num_cc_layers_can_use_lcd_text(0),
434 total_num_cc_layers_will_use_lcd_text(0) {}
436 int64 total_num_cc_layers;
437 int64 total_num_cc_layers_can_use_lcd_text;
438 int64 total_num_cc_layers_will_use_lcd_text;
440 LCDTextMetrics lcd_text_metrics_;
442 bool next_commit_forces_redraw_;
444 scoped_refptr<Layer> page_scale_layer_;
445 scoped_refptr<Layer> inner_viewport_scroll_layer_;
446 scoped_refptr<Layer> outer_viewport_scroll_layer_;
448 SharedBitmapManager* shared_bitmap_manager_;
450 ScopedPtrVector<SwapPromise> swap_promise_list_;
451 std::set<SwapPromiseMonitor*> swap_promise_monitor_;
453 DISALLOW_COPY_AND_ASSIGN(LayerTreeHost);
458 #endif // CC_TREES_LAYER_TREE_HOST_H_