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_
13 #include "base/basictypes.h"
14 #include "base/cancelable_callback.h"
15 #include "base/containers/hash_tables.h"
16 #include "base/memory/ref_counted.h"
17 #include "base/memory/scoped_ptr.h"
18 #include "base/memory/weak_ptr.h"
19 #include "base/time/time.h"
20 #include "cc/animation/animation_events.h"
21 #include "cc/base/cc_export.h"
22 #include "cc/base/scoped_ptr_vector.h"
23 #include "cc/debug/micro_benchmark.h"
24 #include "cc/debug/micro_benchmark_controller.h"
25 #include "cc/input/input_handler.h"
26 #include "cc/input/scrollbar.h"
27 #include "cc/input/top_controls_state.h"
28 #include "cc/layers/layer_lists.h"
29 #include "cc/output/output_surface.h"
30 #include "cc/resources/resource_format.h"
31 #include "cc/resources/scoped_ui_resource.h"
32 #include "cc/resources/ui_resource_bitmap.h"
33 #include "cc/resources/ui_resource_client.h"
34 #include "cc/scheduler/rate_limiter.h"
35 #include "cc/trees/layer_tree_host_client.h"
36 #include "cc/trees/layer_tree_host_common.h"
37 #include "cc/trees/layer_tree_settings.h"
38 #include "cc/trees/occlusion_tracker.h"
39 #include "cc/trees/proxy.h"
40 #include "third_party/skia/include/core/SkColor.h"
41 #include "ui/events/latency_info.h"
42 #include "ui/gfx/rect.h"
44 namespace WebKit { class WebGraphicsContext3D; }
46 #if defined(COMPILER_GCC)
47 namespace BASE_HASH_NAMESPACE {
49 struct hash<WebKit::WebGraphicsContext3D*> {
50 size_t operator()(WebKit::WebGraphicsContext3D* ptr) const {
51 return hash<size_t>()(reinterpret_cast<size_t>(ptr));
54 } // namespace BASE_HASH_NAMESPACE
59 class AnimationRegistrar;
60 class HeadsUpDisplayLayer;
62 class LayerTreeHostImpl;
63 class LayerTreeHostImplClient;
64 class PrioritizedResourceManager;
65 class PrioritizedResource;
67 class RenderingStatsInstrumentation;
68 class ResourceProvider;
69 class ResourceUpdateQueue;
70 class SharedBitmapManager;
71 class TopControlsManager;
72 struct RenderingStats;
73 struct ScrollAndScaleSet;
75 // Provides information on an Impl's rendering capabilities back to the
77 struct CC_EXPORT RendererCapabilities {
78 RendererCapabilities();
79 ~RendererCapabilities();
81 ResourceFormat best_texture_format;
82 bool using_partial_swap;
83 bool using_set_visibility;
85 bool allow_partial_texture_updates;
86 bool using_offscreen_context3d;
88 bool avoid_pow2_textures;
90 bool using_shared_memory_resources;
91 bool using_discard_framebuffer;
94 class CC_EXPORT UIResourceRequest {
96 enum UIResourceRequestType {
99 UIResourceInvalidRequest
102 UIResourceRequest(UIResourceRequestType type, UIResourceId id);
103 UIResourceRequest(UIResourceRequestType type,
105 const UIResourceBitmap& bitmap);
106 UIResourceRequest(const UIResourceRequest& request);
108 ~UIResourceRequest();
110 UIResourceRequestType GetType() const { return type_; }
111 UIResourceId GetId() const { return id_; }
112 UIResourceBitmap GetBitmap() const {
114 return *bitmap_.get();
117 UIResourceRequest& operator=(const UIResourceRequest& request);
120 UIResourceRequestType type_;
122 scoped_ptr<UIResourceBitmap> bitmap_;
125 class CC_EXPORT LayerTreeHost : NON_EXPORTED_BASE(public RateLimiterClient) {
127 // The SharedBitmapManager will be used on the compositor thread.
128 static scoped_ptr<LayerTreeHost> Create(
129 LayerTreeHostClient* client,
130 SharedBitmapManager* manager,
131 const LayerTreeSettings& settings,
132 scoped_refptr<base::SingleThreadTaskRunner> impl_task_runner);
133 virtual ~LayerTreeHost();
135 void SetLayerTreeHostClientReady();
137 // Returns true if any LayerTreeHost is alive.
138 static bool AnyLayerTreeHostInstanceExists();
140 void set_needs_filter_context() { needs_filter_context_ = true; }
141 bool needs_offscreen_context() const {
142 return needs_filter_context_;
145 // LayerTreeHost interface to Proxy.
146 void WillBeginMainFrame() { client_->WillBeginMainFrame(); }
147 void DidBeginMainFrame();
148 void UpdateClientAnimations(base::TimeTicks monotonic_frame_begin_time);
149 void AnimateLayers(base::TimeTicks monotonic_frame_begin_time);
150 void DidStopFlinging();
152 void BeginCommitOnImplThread(LayerTreeHostImpl* host_impl);
153 void FinishCommitOnImplThread(LayerTreeHostImpl* host_impl);
155 void CommitComplete();
156 scoped_ptr<OutputSurface> CreateOutputSurface();
157 virtual scoped_ptr<LayerTreeHostImpl> CreateLayerTreeHostImpl(
158 LayerTreeHostImplClient* client);
159 void DidLoseOutputSurface();
160 bool output_surface_lost() const { return output_surface_lost_; }
163 CreateFailedButTryAgain,
164 CreateFailedAndGaveUp,
166 CreateResult OnCreateAndInitializeOutputSurfaceAttempted(bool success);
167 void DidCommitAndDrawFrame() { client_->DidCommitAndDrawFrame(); }
168 void DidCompleteSwapBuffers() { client_->DidCompleteSwapBuffers(); }
169 void DeleteContentsTexturesOnImplThread(ResourceProvider* resource_provider);
170 virtual void AcquireLayerTextures();
171 // Returns false if we should abort this frame due to initialization failure.
172 bool InitializeOutputSurfaceIfNeeded();
173 bool UpdateLayers(ResourceUpdateQueue* queue);
175 LayerTreeHostClient* client() { return client_; }
176 const base::WeakPtr<InputHandler>& GetInputHandler() {
177 return input_handler_weak_ptr_;
180 void NotifyInputThrottledUntilCommit();
182 void Composite(base::TimeTicks frame_begin_time);
184 // Only used when compositing on the main thread.
185 void ScheduleComposite();
187 // Composites and attempts to read back the result into the provided
188 // buffer. If it wasn't possible, e.g. due to context lost, will return
190 bool CompositeAndReadback(void* pixels, gfx::Rect rect_in_device_viewport);
192 void FinishAllRendering();
194 void SetDeferCommits(bool defer_commits);
197 virtual void DidDeferCommit();
199 int source_frame_number() const { return source_frame_number_; }
201 void SetNeedsDisplayOnAllLayers();
203 void CollectRenderingStats(RenderingStats* stats) const;
205 RenderingStatsInstrumentation* rendering_stats_instrumentation() const {
206 return rendering_stats_instrumentation_.get();
209 const RendererCapabilities& GetRendererCapabilities() const;
211 void SetNeedsAnimate();
212 virtual void SetNeedsUpdateLayers();
213 virtual void SetNeedsCommit();
214 virtual void SetNeedsFullTreeSync();
215 void SetNeedsRedraw();
216 void SetNeedsRedrawRect(gfx::Rect damage_rect);
217 bool CommitRequested() const;
218 bool BeginMainFrameRequested() const;
220 void SetNextCommitWaitsForActivation();
222 void SetNextCommitForcesRedraw();
224 void SetAnimationEvents(scoped_ptr<AnimationEventsVector> events,
225 base::Time wall_clock_time);
227 void SetRootLayer(scoped_refptr<Layer> root_layer);
228 Layer* root_layer() { return root_layer_.get(); }
229 const Layer* root_layer() const { return root_layer_.get(); }
230 const Layer* page_scale_layer() const { return page_scale_layer_.get(); }
231 void RegisterViewportLayers(
232 scoped_refptr<Layer> page_scale_layer,
233 scoped_refptr<Layer> inner_viewport_scroll_layer,
234 scoped_refptr<Layer> outer_viewport_scroll_layer);
236 const LayerTreeSettings& settings() const { return settings_; }
238 void SetDebugState(const LayerTreeDebugState& debug_state);
239 const LayerTreeDebugState& debug_state() const { return debug_state_; }
241 void SetViewportSize(gfx::Size device_viewport_size);
242 void SetOverdrawBottomHeight(float overdraw_bottom_height);
244 gfx::Size device_viewport_size() const { return device_viewport_size_; }
245 float overdraw_bottom_height() const { return overdraw_bottom_height_; }
247 void ApplyPageScaleDeltaFromImplSide(float page_scale_delta);
248 void SetPageScaleFactorAndLimits(float page_scale_factor,
249 float min_page_scale_factor,
250 float max_page_scale_factor);
251 float page_scale_factor() const { return page_scale_factor_; }
253 SkColor background_color() const { return background_color_; }
254 void set_background_color(SkColor color) { background_color_ = color; }
256 void set_has_transparent_background(bool transparent) {
257 has_transparent_background_ = transparent;
260 void SetOverhangBitmap(const SkBitmap& bitmap);
262 PrioritizedResourceManager* contents_texture_manager() const {
263 return contents_texture_manager_.get();
266 void SetVisible(bool visible);
267 bool visible() const { return visible_; }
269 void StartPageScaleAnimation(gfx::Vector2d target_offset,
272 base::TimeDelta duration);
274 void ApplyScrollAndScale(const ScrollAndScaleSet& info);
276 void SetImplTransform(const gfx::Transform& transform);
277 void SetLatencyInfo(const ui::LatencyInfo& latency_info);
279 virtual void StartRateLimiter(WebKit::WebGraphicsContext3D* context3d);
280 virtual void StopRateLimiter(WebKit::WebGraphicsContext3D* context3d);
282 // RateLimiterClient implementation.
283 virtual void RateLimit() OVERRIDE;
285 bool AlwaysUsePartialTextureUpdates();
286 size_t MaxPartialTextureUpdates() const;
287 bool RequestPartialTextureUpdate();
289 void SetDeviceScaleFactor(float device_scale_factor);
290 float device_scale_factor() const { return device_scale_factor_; }
292 void UpdateTopControlsState(TopControlsState constraints,
293 TopControlsState current,
296 HeadsUpDisplayLayer* hud_layer() const { return hud_layer_.get(); }
298 Proxy* proxy() const { return proxy_.get(); }
300 AnimationRegistrar* animation_registrar() const {
301 return animation_registrar_.get();
304 // Obtains a thorough dump of the LayerTreeHost as a value.
305 scoped_ptr<base::Value> AsValue() const;
307 bool in_paint_layer_contents() const { return in_paint_layer_contents_; }
309 // CreateUIResource creates a resource given a bitmap. The bitmap is
310 // generated via an interface function, which is called when initializing the
311 // resource and when the resource has been lost (due to lost context). The
312 // parameter of the interface is a single boolean, which indicates whether the
313 // resource has been lost or not. CreateUIResource returns an Id of the
314 // resource, which is always positive.
315 virtual UIResourceId CreateUIResource(UIResourceClient* client);
316 // Deletes a UI resource. May safely be called more than once.
317 virtual void DeleteUIResource(UIResourceId id);
318 // Put the recreation of all UI resources into the resource queue after they
319 // were evicted on the impl thread.
320 void RecreateUIResources();
322 virtual gfx::Size GetUIResourceSize(UIResourceId id) const;
324 bool UsingSharedMemoryResources();
325 int id() const { return tree_id_; }
327 bool ScheduleMicroBenchmark(const std::string& benchmark_name,
328 scoped_ptr<base::Value> value,
329 const MicroBenchmark::DoneCallback& callback);
332 LayerTreeHost(LayerTreeHostClient* client,
333 SharedBitmapManager* manager,
334 const LayerTreeSettings& settings);
335 bool Initialize(scoped_refptr<base::SingleThreadTaskRunner> impl_task_runner);
336 bool InitializeForTesting(scoped_ptr<Proxy> proxy_for_testing);
337 void SetOutputSurfaceLostForTesting(bool is_lost) {
338 output_surface_lost_ = is_lost;
342 bool InitializeProxy(scoped_ptr<Proxy> proxy);
344 void PaintLayerContents(
345 const RenderSurfaceLayerList& render_surface_layer_list,
346 ResourceUpdateQueue* queue,
347 bool* did_paint_content,
348 bool* need_more_updates);
349 void PaintMasksForRenderSurface(Layer* render_surface_layer,
350 ResourceUpdateQueue* queue,
351 bool* did_paint_content,
352 bool* need_more_updates);
353 bool UpdateLayers(Layer* root_layer, ResourceUpdateQueue* queue);
354 void UpdateHudLayer();
355 void TriggerPrepaint();
357 void ReduceMemoryUsage();
359 void PrioritizeTextures(
360 const RenderSurfaceLayerList& render_surface_layer_list,
361 OverdrawMetrics* metrics);
362 void SetPrioritiesForSurfaces(size_t surface_memory_bytes);
363 void SetPrioritiesForLayers(const RenderSurfaceLayerList& update_list);
364 size_t CalculateMemoryForRenderSurfaces(
365 const RenderSurfaceLayerList& update_list);
367 bool AnimateLayersRecursive(Layer* current, base::TimeTicks time);
369 struct UIResourceClientData {
370 UIResourceClient* client;
374 typedef base::hash_map<UIResourceId, UIResourceClientData>
376 UIResourceClientMap ui_resource_client_map_;
377 int next_ui_resource_id_;
379 typedef std::list<UIResourceRequest> UIResourceRequestQueue;
380 UIResourceRequestQueue ui_resource_request_queue_;
382 void CalculateLCDTextMetricsCallback(Layer* layer);
385 bool needs_full_tree_sync_;
386 bool needs_filter_context_;
388 base::CancelableClosure prepaint_callback_;
390 LayerTreeHostClient* client_;
391 scoped_ptr<Proxy> proxy_;
393 int source_frame_number_;
394 scoped_ptr<RenderingStatsInstrumentation> rendering_stats_instrumentation_;
395 MicroBenchmarkController micro_benchmark_controller_;
398 bool output_surface_can_be_initialized_;
399 bool output_surface_lost_;
400 int num_failed_recreate_attempts_;
402 scoped_refptr<Layer> root_layer_;
403 scoped_refptr<HeadsUpDisplayLayer> hud_layer_;
405 scoped_ptr<PrioritizedResourceManager> contents_texture_manager_;
406 scoped_ptr<PrioritizedResource> surface_memory_placeholder_;
408 base::WeakPtr<InputHandler> input_handler_weak_ptr_;
409 base::WeakPtr<TopControlsManager> top_controls_manager_weak_ptr_;
411 const LayerTreeSettings settings_;
412 LayerTreeDebugState debug_state_;
414 gfx::Size device_viewport_size_;
415 float overdraw_bottom_height_;
416 float device_scale_factor_;
420 typedef base::hash_map<WebKit::WebGraphicsContext3D*,
421 scoped_refptr<RateLimiter> > RateLimiterMap;
422 RateLimiterMap rate_limiters_;
424 float page_scale_factor_;
425 float min_page_scale_factor_;
426 float max_page_scale_factor_;
427 gfx::Transform impl_transform_;
428 bool trigger_idle_updates_;
430 SkColor background_color_;
431 bool has_transparent_background_;
433 // If set, this texture is used to fill in the parts of the screen not
434 // covered by layers.
435 scoped_ptr<ScopedUIResource> overhang_ui_resource_;
437 typedef ScopedPtrVector<PrioritizedResource> TextureList;
438 size_t partial_texture_update_requests_;
440 scoped_ptr<AnimationRegistrar> animation_registrar_;
442 struct PendingPageScaleAnimation {
443 gfx::Vector2d target_offset;
446 base::TimeDelta duration;
448 scoped_ptr<PendingPageScaleAnimation> pending_page_scale_animation_;
450 bool in_paint_layer_contents_;
452 ui::LatencyInfo latency_info_;
454 static const int kTotalFramesToUseForLCDTextMetrics = 50;
455 int total_frames_used_for_lcd_text_metrics_;
457 struct LCDTextMetrics {
459 : total_num_cc_layers(0),
460 total_num_cc_layers_can_use_lcd_text(0),
461 total_num_cc_layers_will_use_lcd_text(0) {}
463 int64 total_num_cc_layers;
464 int64 total_num_cc_layers_can_use_lcd_text;
465 int64 total_num_cc_layers_will_use_lcd_text;
467 LCDTextMetrics lcd_text_metrics_;
469 bool next_commit_forces_redraw_;
471 scoped_refptr<Layer> page_scale_layer_;
472 scoped_refptr<Layer> inner_viewport_scroll_layer_;
473 scoped_refptr<Layer> outer_viewport_scroll_layer_;
475 SharedBitmapManager* shared_bitmap_manager_;
477 DISALLOW_COPY_AND_ASSIGN(LayerTreeHost);
482 #endif // CC_TREES_LAYER_TREE_HOST_H_