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/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" 43 44 namespace cc { 45 46 class AnimationRegistrar; 47 class HeadsUpDisplayLayer; 48 class Layer; 49 class LayerTreeHostImpl; 50 class LayerTreeHostImplClient; 51 class LayerTreeHostSingleThreadClient; 52 class PrioritizedResource; 53 class PrioritizedResourceManager; 54 class Region; 55 class RenderingStatsInstrumentation; 56 class ResourceProvider; 57 class ResourceUpdateQueue; 58 class SharedBitmapManager; 59 class TopControlsManager; 60 class UIResourceRequest; 61 struct RenderingStats; 62 struct ScrollAndScaleSet; 63 64 // Provides information on an Impl's rendering capabilities back to the 65 // LayerTreeHost. 66 struct CC_EXPORT RendererCapabilities { 67 RendererCapabilities(ResourceFormat best_texture_format, 68 bool allow_partial_texture_updates, 69 bool using_offscreen_context3d, 70 int max_texture_size, 71 bool using_shared_memory_resources); 72 73 RendererCapabilities(); 74 ~RendererCapabilities(); 75 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; 80 int max_texture_size; 81 bool using_shared_memory_resources; 82 }; 83 84 class CC_EXPORT LayerTreeHost { 85 public: 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); 92 93 static scoped_ptr<LayerTreeHost> CreateSingleThreaded( 94 LayerTreeHostClient* client, 95 LayerTreeHostSingleThreadClient* single_thread_client, 96 SharedBitmapManager* manager, 97 const LayerTreeSettings& settings); 98 virtual ~LayerTreeHost(); 99 100 void SetLayerTreeHostClientReady(); 101 102 void set_needs_filter_context() { needs_filter_context_ = true; } 103 bool needs_offscreen_context() const { 104 return needs_filter_context_; 105 } 106 107 // LayerTreeHost interface to Proxy. 108 void WillBeginMainFrame() { 109 client_->WillBeginMainFrame(source_frame_number_); 110 } 111 void DidBeginMainFrame(); 112 void UpdateClientAnimations(base::TimeTicks monotonic_frame_begin_time); 113 void AnimateLayers(base::TimeTicks monotonic_frame_begin_time); 114 void DidStopFlinging(); 115 void Layout(); 116 void BeginCommitOnImplThread(LayerTreeHostImpl* host_impl); 117 void FinishCommitOnImplThread(LayerTreeHostImpl* host_impl); 118 void WillCommit(); 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_; } 125 enum CreateResult { 126 CreateSucceeded, 127 CreateFailedButTryAgain, 128 CreateFailedAndGaveUp, 129 }; 130 CreateResult OnCreateAndInitializeOutputSurfaceAttempted(bool success); 131 void DidCommitAndDrawFrame() { client_->DidCommitAndDrawFrame(); } 132 void DidCompleteSwapBuffers() { client_->DidCompleteSwapBuffers(); } 133 void DeleteContentsTexturesOnImplThread(ResourceProvider* resource_provider); 134 virtual void AcquireLayerTextures(); 135 // Returns false if we should abort this frame due to initialization failure. 136 bool InitializeOutputSurfaceIfNeeded(); 137 bool UpdateLayers(ResourceUpdateQueue* queue); 138 139 LayerTreeHostClient* client() { return client_; } 140 const base::WeakPtr<InputHandler>& GetInputHandler() { 141 return input_handler_weak_ptr_; 142 } 143 144 void NotifyInputThrottledUntilCommit(); 145 146 void Composite(base::TimeTicks frame_begin_time); 147 148 // Composites and attempts to read back the result into the provided 149 // buffer. If it wasn't possible, e.g. due to context lost, will return 150 // false. 151 bool CompositeAndReadback(void* pixels, gfx::Rect rect_in_device_viewport); 152 153 void FinishAllRendering(); 154 155 void SetDeferCommits(bool defer_commits); 156 157 // Test only hook 158 virtual void DidDeferCommit(); 159 160 int source_frame_number() const { return source_frame_number_; } 161 162 void SetNeedsDisplayOnAllLayers(); 163 164 void CollectRenderingStats(RenderingStats* stats) const; 165 166 RenderingStatsInstrumentation* rendering_stats_instrumentation() const { 167 return rendering_stats_instrumentation_.get(); 168 } 169 170 const RendererCapabilities& GetRendererCapabilities() const; 171 172 void SetNeedsAnimate(); 173 virtual void SetNeedsUpdateLayers(); 174 virtual void SetNeedsCommit(); 175 virtual void SetNeedsFullTreeSync(); 176 void SetNeedsRedraw(); 177 void SetNeedsRedrawRect(gfx::Rect damage_rect); 178 bool CommitRequested() const; 179 bool BeginMainFrameRequested() const; 180 181 void SetNextCommitWaitsForActivation(); 182 183 void SetNextCommitForcesRedraw(); 184 185 void SetAnimationEvents(scoped_ptr<AnimationEventsVector> events, 186 base::Time wall_clock_time); 187 188 void SetRootLayer(scoped_refptr<Layer> root_layer); 189 Layer* root_layer() { return root_layer_.get(); } 190 const Layer* root_layer() const { return root_layer_.get(); } 191 const Layer* page_scale_layer() const { return page_scale_layer_.get(); } 192 void RegisterViewportLayers( 193 scoped_refptr<Layer> page_scale_layer, 194 scoped_refptr<Layer> inner_viewport_scroll_layer, 195 scoped_refptr<Layer> outer_viewport_scroll_layer); 196 197 const LayerTreeSettings& settings() const { return settings_; } 198 199 void SetDebugState(const LayerTreeDebugState& debug_state); 200 const LayerTreeDebugState& debug_state() const { return debug_state_; } 201 202 void SetViewportSize(gfx::Size device_viewport_size); 203 void SetOverdrawBottomHeight(float overdraw_bottom_height); 204 205 gfx::Size device_viewport_size() const { return device_viewport_size_; } 206 float overdraw_bottom_height() const { return overdraw_bottom_height_; } 207 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_; } 213 214 SkColor background_color() const { return background_color_; } 215 void set_background_color(SkColor color) { background_color_ = color; } 216 217 void set_has_transparent_background(bool transparent) { 218 has_transparent_background_ = transparent; 219 } 220 221 void SetOverhangBitmap(const SkBitmap& bitmap); 222 223 PrioritizedResourceManager* contents_texture_manager() const { 224 return contents_texture_manager_.get(); 225 } 226 227 void SetVisible(bool visible); 228 bool visible() const { return visible_; } 229 230 void StartPageScaleAnimation(gfx::Vector2d target_offset, 231 bool use_anchor, 232 float scale, 233 base::TimeDelta duration); 234 235 void ApplyScrollAndScale(const ScrollAndScaleSet& info); 236 237 void SetImplTransform(const gfx::Transform& transform); 238 239 // Virtual for tests. 240 virtual void StartRateLimiter(); 241 virtual void StopRateLimiter(); 242 243 void RateLimit(); 244 245 bool AlwaysUsePartialTextureUpdates(); 246 size_t MaxPartialTextureUpdates() const; 247 bool RequestPartialTextureUpdate(); 248 249 void SetDeviceScaleFactor(float device_scale_factor); 250 float device_scale_factor() const { return device_scale_factor_; } 251 252 void UpdateTopControlsState(TopControlsState constraints, 253 TopControlsState current, 254 bool animate); 255 256 HeadsUpDisplayLayer* hud_layer() const { return hud_layer_.get(); } 257 258 Proxy* proxy() const { return proxy_.get(); } 259 260 AnimationRegistrar* animation_registrar() const { 261 return animation_registrar_.get(); 262 } 263 264 // Obtains a thorough dump of the LayerTreeHost as a value. 265 scoped_ptr<base::Value> AsValue() const; 266 267 bool in_paint_layer_contents() const { return in_paint_layer_contents_; } 268 269 // CreateUIResource creates a resource given a bitmap. The bitmap is 270 // generated via an interface function, which is called when initializing the 271 // resource and when the resource has been lost (due to lost context). The 272 // parameter of the interface is a single boolean, which indicates whether the 273 // resource has been lost or not. CreateUIResource returns an Id of the 274 // resource, which is always positive. 275 virtual UIResourceId CreateUIResource(UIResourceClient* client); 276 // Deletes a UI resource. May safely be called more than once. 277 virtual void DeleteUIResource(UIResourceId id); 278 // Put the recreation of all UI resources into the resource queue after they 279 // were evicted on the impl thread. 280 void RecreateUIResources(); 281 282 virtual gfx::Size GetUIResourceSize(UIResourceId id) const; 283 284 bool UsingSharedMemoryResources(); 285 int id() const { return id_; } 286 287 bool ScheduleMicroBenchmark(const std::string& benchmark_name, 288 scoped_ptr<base::Value> value, 289 const MicroBenchmark::DoneCallback& callback); 290 291 // When a SwapPromiseMonitor is created on the main thread, it calls 292 // InsertSwapPromiseMonitor() to register itself with LayerTreeHost. 293 // When the monitor is destroyed, it calls RemoveSwapPromiseMonitor() 294 // to unregister itself. 295 void InsertSwapPromiseMonitor(SwapPromiseMonitor* monitor); 296 void RemoveSwapPromiseMonitor(SwapPromiseMonitor* monitor); 297 298 // Call this function when you expect there to be a swap buffer. 299 // See swap_promise.h for how to use SwapPromise. 300 void QueueSwapPromise(scoped_ptr<SwapPromise> swap_promise); 301 302 void BreakSwapPromises(SwapPromise::DidNotSwapReason reason); 303 304 protected: 305 LayerTreeHost(LayerTreeHostClient* client, 306 SharedBitmapManager* manager, 307 const LayerTreeSettings& settings); 308 bool InitializeThreaded( 309 scoped_refptr<base::SingleThreadTaskRunner> impl_task_runner); 310 bool InitializeSingleThreaded( 311 LayerTreeHostSingleThreadClient* single_thread_client); 312 bool InitializeForTesting(scoped_ptr<Proxy> proxy_for_testing); 313 void SetOutputSurfaceLostForTesting(bool is_lost) { 314 output_surface_lost_ = is_lost; 315 } 316 317 MicroBenchmarkController micro_benchmark_controller_; 318 319 private: 320 bool InitializeProxy(scoped_ptr<Proxy> proxy); 321 322 void PaintLayerContents( 323 const RenderSurfaceLayerList& render_surface_layer_list, 324 ResourceUpdateQueue* queue, 325 bool* did_paint_content, 326 bool* need_more_updates); 327 void PaintMasksForRenderSurface(Layer* render_surface_layer, 328 ResourceUpdateQueue* queue, 329 bool* did_paint_content, 330 bool* need_more_updates); 331 bool UpdateLayers(Layer* root_layer, ResourceUpdateQueue* queue); 332 void UpdateHudLayer(); 333 void TriggerPrepaint(); 334 335 void ReduceMemoryUsage(); 336 337 void PrioritizeTextures( 338 const RenderSurfaceLayerList& render_surface_layer_list, 339 OverdrawMetrics* metrics); 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 CalculateLCDTextMetricsCallback(Layer* layer); 361 362 void NotifySwapPromiseMonitorsOfSetNeedsCommit(); 363 364 bool animating_; 365 bool needs_full_tree_sync_; 366 bool needs_filter_context_; 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_can_be_initialized_; 377 bool output_surface_lost_; 378 int num_failed_recreate_attempts_; 379 380 scoped_refptr<Layer> root_layer_; 381 scoped_refptr<HeadsUpDisplayLayer> hud_layer_; 382 383 scoped_ptr<PrioritizedResourceManager> contents_texture_manager_; 384 scoped_ptr<PrioritizedResource> surface_memory_placeholder_; 385 386 base::WeakPtr<InputHandler> input_handler_weak_ptr_; 387 base::WeakPtr<TopControlsManager> top_controls_manager_weak_ptr_; 388 389 const LayerTreeSettings settings_; 390 LayerTreeDebugState debug_state_; 391 392 gfx::Size device_viewport_size_; 393 float overdraw_bottom_height_; 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 trigger_idle_updates_; 405 406 SkColor background_color_; 407 bool has_transparent_background_; 408 409 // If set, this texture is used to fill in the parts of the screen not 410 // covered by layers. 411 scoped_ptr<ScopedUIResource> overhang_ui_resource_; 412 413 typedef ScopedPtrVector<PrioritizedResource> TextureList; 414 size_t partial_texture_update_requests_; 415 416 scoped_ptr<AnimationRegistrar> animation_registrar_; 417 418 struct PendingPageScaleAnimation { 419 gfx::Vector2d target_offset; 420 bool use_anchor; 421 float scale; 422 base::TimeDelta duration; 423 }; 424 scoped_ptr<PendingPageScaleAnimation> pending_page_scale_animation_; 425 426 bool in_paint_layer_contents_; 427 428 static const int kTotalFramesToUseForLCDTextMetrics = 50; 429 int total_frames_used_for_lcd_text_metrics_; 430 431 struct LCDTextMetrics { 432 LCDTextMetrics() 433 : total_num_cc_layers(0), 434 total_num_cc_layers_can_use_lcd_text(0), 435 total_num_cc_layers_will_use_lcd_text(0) {} 436 437 int64 total_num_cc_layers; 438 int64 total_num_cc_layers_can_use_lcd_text; 439 int64 total_num_cc_layers_will_use_lcd_text; 440 }; 441 LCDTextMetrics lcd_text_metrics_; 442 int id_; 443 bool next_commit_forces_redraw_; 444 445 scoped_refptr<Layer> page_scale_layer_; 446 scoped_refptr<Layer> inner_viewport_scroll_layer_; 447 scoped_refptr<Layer> outer_viewport_scroll_layer_; 448 449 SharedBitmapManager* shared_bitmap_manager_; 450 451 ScopedPtrVector<SwapPromise> swap_promise_list_; 452 std::set<SwapPromiseMonitor*> swap_promise_monitor_; 453 454 DISALLOW_COPY_AND_ASSIGN(LayerTreeHost); 455 }; 456 457 } // namespace cc 458 459 #endif // CC_TREES_LAYER_TREE_HOST_H_ 460