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/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/surfaces/surface_sequence.h"
38 #include "cc/trees/layer_tree_host_client.h"
39 #include "cc/trees/layer_tree_host_common.h"
40 #include "cc/trees/layer_tree_settings.h"
41 #include "cc/trees/proxy.h"
42 #include "third_party/skia/include/core/SkColor.h"
43 #include "ui/gfx/geometry/rect.h"
46 class GpuMemoryBufferManager;
50 class AnimationRegistrar;
51 class HeadsUpDisplayLayer;
53 class LayerTreeHostImpl;
54 class LayerTreeHostImplClient;
55 class LayerTreeHostSingleThreadClient;
56 class PrioritizedResource;
57 class PrioritizedResourceManager;
59 class RenderingStatsInstrumentation;
60 class ResourceProvider;
61 class ResourceUpdateQueue;
62 class SharedBitmapManager;
63 class TopControlsManager;
64 class UIResourceRequest;
65 struct RenderingStats;
66 struct ScrollAndScaleSet;
68 // Provides information on an Impl's rendering capabilities back to the
70 struct CC_EXPORT RendererCapabilities {
71 RendererCapabilities(ResourceFormat best_texture_format,
72 bool allow_partial_texture_updates,
74 bool using_shared_memory_resources);
76 RendererCapabilities();
77 ~RendererCapabilities();
79 // Duplicate any modification to this list to RendererCapabilitiesImpl.
80 ResourceFormat best_texture_format;
81 bool allow_partial_texture_updates;
83 bool using_shared_memory_resources;
86 class CC_EXPORT LayerTreeHost {
88 // The SharedBitmapManager will be used on the compositor thread.
89 static scoped_ptr<LayerTreeHost> CreateThreaded(
90 LayerTreeHostClient* client,
91 SharedBitmapManager* shared_bitmap_manager,
92 gpu::GpuMemoryBufferManager* gpu_memory_buffer_manager,
93 const LayerTreeSettings& settings,
94 scoped_refptr<base::SingleThreadTaskRunner> main_task_runner,
95 scoped_refptr<base::SingleThreadTaskRunner> impl_task_runner);
97 static scoped_ptr<LayerTreeHost> CreateSingleThreaded(
98 LayerTreeHostClient* client,
99 LayerTreeHostSingleThreadClient* single_thread_client,
100 SharedBitmapManager* shared_bitmap_manager,
101 gpu::GpuMemoryBufferManager* gpu_memory_buffer_manager,
102 const LayerTreeSettings& settings,
103 scoped_refptr<base::SingleThreadTaskRunner> main_task_runner);
104 virtual ~LayerTreeHost();
106 void SetLayerTreeHostClientReady();
108 // LayerTreeHost interface to Proxy.
109 void WillBeginMainFrame() {
110 client_->WillBeginMainFrame(source_frame_number_);
112 void DidBeginMainFrame();
113 void BeginMainFrame(const BeginFrameArgs& args);
114 void AnimateLayers(base::TimeTicks monotonic_frame_begin_time);
115 void DidStopFlinging();
117 void BeginCommitOnImplThread(LayerTreeHostImpl* host_impl);
118 void FinishCommitOnImplThread(LayerTreeHostImpl* host_impl);
120 void CommitComplete();
121 void SetOutputSurface(scoped_ptr<OutputSurface> output_surface);
122 void RequestNewOutputSurface();
123 virtual scoped_ptr<LayerTreeHostImpl> CreateLayerTreeHostImpl(
124 LayerTreeHostImplClient* client);
125 void DidLoseOutputSurface();
126 bool output_surface_lost() const { return output_surface_lost_; }
127 virtual void OnCreateAndInitializeOutputSurfaceAttempted(bool success);
128 void DidCommitAndDrawFrame() { client_->DidCommitAndDrawFrame(); }
129 void DidCompleteSwapBuffers() { client_->DidCompleteSwapBuffers(); }
130 void DeleteContentsTexturesOnImplThread(ResourceProvider* resource_provider);
131 bool UpdateLayers(ResourceUpdateQueue* queue);
133 LayerTreeHostClient* client() { return client_; }
134 const base::WeakPtr<InputHandler>& GetInputHandler() {
135 return input_handler_weak_ptr_;
138 void NotifyInputThrottledUntilCommit();
140 void Composite(base::TimeTicks frame_begin_time);
142 void FinishAllRendering();
144 void SetDeferCommits(bool defer_commits);
147 virtual void DidDeferCommit();
149 int source_frame_number() const { return source_frame_number_; }
151 void SetNeedsDisplayOnAllLayers();
153 void CollectRenderingStats(RenderingStats* stats) const;
155 RenderingStatsInstrumentation* rendering_stats_instrumentation() const {
156 return rendering_stats_instrumentation_.get();
159 const RendererCapabilities& GetRendererCapabilities() const;
161 void SetNeedsAnimate();
162 virtual void SetNeedsUpdateLayers();
163 virtual void SetNeedsCommit();
164 virtual void SetNeedsFullTreeSync();
165 void SetNeedsRedraw();
166 void SetNeedsRedrawRect(const gfx::Rect& damage_rect);
167 bool CommitRequested() const;
168 bool BeginMainFrameRequested() const;
170 void SetNextCommitWaitsForActivation();
172 void SetNextCommitForcesRedraw();
174 void SetAnimationEvents(scoped_ptr<AnimationEventsVector> events);
176 void SetRootLayer(scoped_refptr<Layer> root_layer);
177 Layer* root_layer() { return root_layer_.get(); }
178 const Layer* root_layer() const { return root_layer_.get(); }
179 const Layer* page_scale_layer() const { return page_scale_layer_.get(); }
180 void RegisterViewportLayers(
181 scoped_refptr<Layer> page_scale_layer,
182 scoped_refptr<Layer> inner_viewport_scroll_layer,
183 scoped_refptr<Layer> outer_viewport_scroll_layer);
184 Layer* inner_viewport_scroll_layer() const {
185 return inner_viewport_scroll_layer_.get();
187 Layer* outer_viewport_scroll_layer() const {
188 return outer_viewport_scroll_layer_.get();
191 void RegisterSelection(const LayerSelectionBound& start,
192 const LayerSelectionBound& end);
194 const LayerTreeSettings& settings() const { return settings_; }
196 void SetDebugState(const LayerTreeDebugState& debug_state);
197 const LayerTreeDebugState& debug_state() const { return debug_state_; }
199 bool has_gpu_rasterization_trigger() const {
200 return has_gpu_rasterization_trigger_;
202 void SetHasGpuRasterizationTrigger(bool has_trigger);
203 bool UseGpuRasterization() const;
205 void SetViewportSize(const gfx::Size& device_viewport_size);
206 void SetTopControlsLayoutHeight(float height);
207 void SetTopControlsContentOffset(float offset);
209 gfx::Size device_viewport_size() const { return device_viewport_size_; }
211 void ApplyPageScaleDeltaFromImplSide(float page_scale_delta);
212 void SetPageScaleFactorAndLimits(float page_scale_factor,
213 float min_page_scale_factor,
214 float max_page_scale_factor);
215 float page_scale_factor() const { return page_scale_factor_; }
217 SkColor background_color() const { return background_color_; }
218 void set_background_color(SkColor color) { background_color_ = color; }
220 void set_has_transparent_background(bool transparent) {
221 has_transparent_background_ = transparent;
224 void SetOverhangBitmap(const SkBitmap& bitmap);
226 PrioritizedResourceManager* contents_texture_manager() const {
227 return contents_texture_manager_.get();
230 void SetVisible(bool visible);
231 bool visible() const { return visible_; }
233 void StartPageScaleAnimation(const gfx::Vector2d& target_offset,
236 base::TimeDelta duration);
238 void ApplyScrollAndScale(ScrollAndScaleSet* info);
239 void SetImplTransform(const gfx::Transform& transform);
241 // Virtual for tests.
242 virtual void StartRateLimiter();
243 virtual void StopRateLimiter();
247 bool AlwaysUsePartialTextureUpdates();
248 size_t MaxPartialTextureUpdates() const;
249 bool RequestPartialTextureUpdate();
251 void SetDeviceScaleFactor(float device_scale_factor);
252 float device_scale_factor() const { return device_scale_factor_; }
254 void UpdateTopControlsState(TopControlsState constraints,
255 TopControlsState current,
258 HeadsUpDisplayLayer* hud_layer() const { return hud_layer_.get(); }
260 Proxy* proxy() const { return proxy_.get(); }
262 AnimationRegistrar* animation_registrar() const {
263 return animation_registrar_.get();
266 // Obtains a thorough dump of the LayerTreeHost as a value.
267 void AsValueInto(base::debug::TracedValue* value) const;
269 bool in_paint_layer_contents() const { return in_paint_layer_contents_; }
271 // CreateUIResource creates a resource given a bitmap. The bitmap is
272 // generated via an interface function, which is called when initializing the
273 // resource and when the resource has been lost (due to lost context). The
274 // parameter of the interface is a single boolean, which indicates whether the
275 // resource has been lost or not. CreateUIResource returns an Id of the
276 // resource, which is always positive.
277 virtual UIResourceId CreateUIResource(UIResourceClient* client);
278 // Deletes a UI resource. May safely be called more than once.
279 virtual void DeleteUIResource(UIResourceId id);
280 // Put the recreation of all UI resources into the resource queue after they
281 // were evicted on the impl thread.
282 void RecreateUIResources();
284 virtual gfx::Size GetUIResourceSize(UIResourceId id) const;
286 bool UsingSharedMemoryResources();
287 int id() const { return id_; }
289 // Returns the id of the benchmark on success, 0 otherwise.
290 int ScheduleMicroBenchmark(const std::string& benchmark_name,
291 scoped_ptr<base::Value> value,
292 const MicroBenchmark::DoneCallback& callback);
293 // Returns true if the message was successfully delivered and handled.
294 bool SendMessageToMicroBenchmark(int id, scoped_ptr<base::Value> value);
296 // When a SwapPromiseMonitor is created on the main thread, it calls
297 // InsertSwapPromiseMonitor() to register itself with LayerTreeHost.
298 // When the monitor is destroyed, it calls RemoveSwapPromiseMonitor()
299 // to unregister itself.
300 void InsertSwapPromiseMonitor(SwapPromiseMonitor* monitor);
301 void RemoveSwapPromiseMonitor(SwapPromiseMonitor* monitor);
303 // Call this function when you expect there to be a swap buffer.
304 // See swap_promise.h for how to use SwapPromise.
305 void QueueSwapPromise(scoped_ptr<SwapPromise> swap_promise);
307 void BreakSwapPromises(SwapPromise::DidNotSwapReason reason);
309 size_t num_queued_swap_promises() const { return swap_promise_list_.size(); }
311 void set_surface_id_namespace(uint32_t id_namespace);
312 SurfaceSequence CreateSurfaceSequence();
315 LayerTreeHost(LayerTreeHostClient* client,
316 SharedBitmapManager* shared_bitmap_manager,
317 gpu::GpuMemoryBufferManager* gpu_memory_buffer_manager,
318 const LayerTreeSettings& settings);
319 void InitializeThreaded(
320 scoped_refptr<base::SingleThreadTaskRunner> main_task_runner,
321 scoped_refptr<base::SingleThreadTaskRunner> impl_task_runner);
322 void InitializeSingleThreaded(
323 LayerTreeHostSingleThreadClient* single_thread_client,
324 scoped_refptr<base::SingleThreadTaskRunner> main_task_runner);
325 void InitializeForTesting(scoped_ptr<Proxy> proxy_for_testing);
326 void SetOutputSurfaceLostForTesting(bool is_lost) {
327 output_surface_lost_ = is_lost;
330 MicroBenchmarkController micro_benchmark_controller_;
333 void InitializeProxy(scoped_ptr<Proxy> proxy);
335 void PaintLayerContents(
336 const RenderSurfaceLayerList& render_surface_layer_list,
337 ResourceUpdateQueue* queue,
338 bool* did_paint_content,
339 bool* need_more_updates);
340 void PaintMasksForRenderSurface(Layer* render_surface_layer,
341 ResourceUpdateQueue* queue,
342 bool* did_paint_content,
343 bool* need_more_updates);
344 bool UpdateLayers(Layer* root_layer, ResourceUpdateQueue* queue);
345 void UpdateHudLayer();
346 void TriggerPrepaint();
348 void ReduceMemoryUsage();
350 void PrioritizeTextures(
351 const RenderSurfaceLayerList& render_surface_layer_list);
352 void SetPrioritiesForSurfaces(size_t surface_memory_bytes);
353 void SetPrioritiesForLayers(const RenderSurfaceLayerList& update_list);
354 size_t CalculateMemoryForRenderSurfaces(
355 const RenderSurfaceLayerList& update_list);
357 bool AnimateLayersRecursive(Layer* current, base::TimeTicks time);
359 struct UIResourceClientData {
360 UIResourceClient* client;
364 typedef base::hash_map<UIResourceId, UIResourceClientData>
366 UIResourceClientMap ui_resource_client_map_;
367 int next_ui_resource_id_;
369 typedef std::list<UIResourceRequest> UIResourceRequestQueue;
370 UIResourceRequestQueue ui_resource_request_queue_;
372 void RecordGpuRasterizationHistogram();
373 void CalculateLCDTextMetricsCallback(Layer* layer);
375 void NotifySwapPromiseMonitorsOfSetNeedsCommit();
377 bool inside_begin_main_frame_;
378 bool needs_full_tree_sync_;
380 base::CancelableClosure prepaint_callback_;
382 LayerTreeHostClient* client_;
383 scoped_ptr<Proxy> proxy_;
385 int source_frame_number_;
386 scoped_ptr<RenderingStatsInstrumentation> rendering_stats_instrumentation_;
388 bool output_surface_lost_;
389 int num_failed_recreate_attempts_;
391 scoped_refptr<Layer> root_layer_;
392 scoped_refptr<HeadsUpDisplayLayer> hud_layer_;
394 scoped_ptr<PrioritizedResourceManager> contents_texture_manager_;
395 scoped_ptr<PrioritizedResource> surface_memory_placeholder_;
397 base::WeakPtr<InputHandler> input_handler_weak_ptr_;
398 base::WeakPtr<TopControlsManager> top_controls_manager_weak_ptr_;
400 const LayerTreeSettings settings_;
401 LayerTreeDebugState debug_state_;
403 gfx::Size device_viewport_size_;
404 float top_controls_layout_height_;
405 float top_controls_content_offset_;
406 float device_scale_factor_;
410 base::OneShotTimer<LayerTreeHost> rate_limit_timer_;
412 float page_scale_factor_;
413 float min_page_scale_factor_;
414 float max_page_scale_factor_;
415 bool has_gpu_rasterization_trigger_;
416 bool content_is_suitable_for_gpu_rasterization_;
417 bool gpu_rasterization_histogram_recorded_;
419 SkColor background_color_;
420 bool has_transparent_background_;
422 // If set, this texture is used to fill in the parts of the screen not
423 // covered by layers.
424 scoped_ptr<ScopedUIResource> overhang_ui_resource_;
426 typedef ScopedPtrVector<PrioritizedResource> TextureList;
427 size_t partial_texture_update_requests_;
429 scoped_ptr<AnimationRegistrar> animation_registrar_;
431 struct PendingPageScaleAnimation {
432 gfx::Vector2d target_offset;
435 base::TimeDelta duration;
437 scoped_ptr<PendingPageScaleAnimation> pending_page_scale_animation_;
439 bool in_paint_layer_contents_;
441 static const int kTotalFramesToUseForLCDTextMetrics = 50;
442 int total_frames_used_for_lcd_text_metrics_;
444 struct LCDTextMetrics {
446 : total_num_cc_layers(0),
447 total_num_cc_layers_can_use_lcd_text(0),
448 total_num_cc_layers_will_use_lcd_text(0) {}
450 int64 total_num_cc_layers;
451 int64 total_num_cc_layers_can_use_lcd_text;
452 int64 total_num_cc_layers_will_use_lcd_text;
454 LCDTextMetrics lcd_text_metrics_;
456 bool next_commit_forces_redraw_;
458 scoped_refptr<Layer> page_scale_layer_;
459 scoped_refptr<Layer> inner_viewport_scroll_layer_;
460 scoped_refptr<Layer> outer_viewport_scroll_layer_;
462 LayerSelectionBound selection_start_;
463 LayerSelectionBound selection_end_;
465 SharedBitmapManager* shared_bitmap_manager_;
466 gpu::GpuMemoryBufferManager* gpu_memory_buffer_manager_;
468 ScopedPtrVector<SwapPromise> swap_promise_list_;
469 std::set<SwapPromiseMonitor*> swap_promise_monitor_;
471 uint32_t surface_id_namespace_;
472 uint32_t next_surface_sequence_;
474 DISALLOW_COPY_AND_ASSIGN(LayerTreeHost);
479 #endif // CC_TREES_LAYER_TREE_HOST_H_