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 <stddef.h> 9 #include <stdint.h> 10 11 #include <limits> 12 #include <memory> 13 #include <set> 14 #include <string> 15 #include <unordered_map> 16 #include <vector> 17 18 #include "base/callback_forward.h" 19 #include "base/cancelable_callback.h" 20 #include "base/containers/flat_map.h" 21 #include "base/containers/flat_set.h" 22 #include "base/memory/ref_counted.h" 23 #include "base/memory/weak_ptr.h" 24 #include "base/single_thread_task_runner.h" 25 #include "base/time/time.h" 26 #include "cc/benchmarks/micro_benchmark.h" 27 #include "cc/benchmarks/micro_benchmark_controller.h" 28 #include "cc/cc_export.h" 29 #include "cc/input/browser_controls_state.h" 30 #include "cc/input/event_listener_properties.h" 31 #include "cc/input/input_handler.h" 32 #include "cc/input/layer_selection_bound.h" 33 #include "cc/input/scrollbar.h" 34 #include "cc/layers/layer_collections.h" 35 #include "cc/layers/layer_list_iterator.h" 36 #include "cc/metrics/begin_main_frame_metrics.h" 37 #include "cc/metrics/event_metrics.h" 38 #include "cc/metrics/events_metrics_manager.h" 39 #include "cc/metrics/frame_sequence_tracker.h" 40 #include "cc/paint/node_id.h" 41 #include "cc/trees/browser_controls_params.h" 42 #include "cc/trees/compositor_mode.h" 43 #include "cc/trees/layer_tree_frame_sink.h" 44 #include "cc/trees/layer_tree_host_client.h" 45 #include "cc/trees/layer_tree_settings.h" 46 #include "cc/trees/mutator_host.h" 47 #include "cc/trees/proxy.h" 48 #include "cc/trees/swap_promise.h" 49 #include "cc/trees/swap_promise_manager.h" 50 #include "cc/trees/target_property.h" 51 #include "cc/trees/viewport_layers.h" 52 #include "components/viz/common/resources/resource_format.h" 53 #include "components/viz/common/surfaces/local_surface_id_allocation.h" 54 #include "services/metrics/public/cpp/ukm_source_id.h" 55 #include "ui/gfx/geometry/rect.h" 56 #include "ui/gfx/overlay_transform.h" 57 58 namespace gfx { 59 struct PresentationFeedback; 60 } 61 62 namespace cc { 63 64 class HeadsUpDisplayLayer; 65 class Layer; 66 class LayerTreeHostImpl; 67 class LayerTreeHostImplClient; 68 class LayerTreeHostSingleThreadClient; 69 class LayerTreeMutator; 70 class PaintWorkletLayerPainter; 71 class MutatorEvents; 72 class MutatorHost; 73 struct PendingPageScaleAnimation; 74 class RenderFrameMetadataObserver; 75 class RenderingStatsInstrumentation; 76 struct OverscrollBehavior; 77 class TaskGraphRunner; 78 class UIResourceManager; 79 class UkmRecorderFactory; 80 struct RenderingStats; 81 struct ScrollAndScaleSet; 82 83 // Returned from LayerTreeHost::DeferMainFrameUpdate. Automatically un-defers on 84 // destruction. 85 class CC_EXPORT ScopedDeferMainFrameUpdate { 86 public: 87 explicit ScopedDeferMainFrameUpdate(LayerTreeHost* host); 88 ~ScopedDeferMainFrameUpdate(); 89 90 private: 91 base::WeakPtr<LayerTreeHost> host_; 92 }; 93 94 class CC_EXPORT LayerTreeHost : public MutatorHostClient { 95 public: 96 struct CC_EXPORT InitParams { 97 InitParams(); 98 ~InitParams(); 99 100 InitParams(InitParams&&); 101 InitParams& operator=(InitParams&&); 102 103 LayerTreeHostClient* client = nullptr; 104 LayerTreeHostSchedulingClient* scheduling_client = nullptr; 105 TaskGraphRunner* task_graph_runner = nullptr; 106 LayerTreeSettings const* settings = nullptr; 107 scoped_refptr<base::SingleThreadTaskRunner> main_task_runner; 108 MutatorHost* mutator_host = nullptr; 109 110 // The image worker task runner is used to schedule image decodes. The 111 // compositor thread may make sync calls to this thread, analogous to the 112 // raster worker threads. 113 scoped_refptr<base::SequencedTaskRunner> image_worker_task_runner; 114 115 std::unique_ptr<UkmRecorderFactory> ukm_recorder_factory; 116 }; 117 118 // Constructs a LayerTreeHost with a compositor thread where scrolling and 119 // animation take place. This is used for the web compositor in the renderer 120 // process to move work off the main thread which javascript can dominate. 121 static std::unique_ptr<LayerTreeHost> CreateThreaded( 122 scoped_refptr<base::SingleThreadTaskRunner> impl_task_runner, 123 InitParams params); 124 125 // Constructs a LayerTreeHost without a separate compositor thread, but which 126 // behaves and looks the same as a threaded compositor externally, with the 127 // exception of the additional client interface. This is used in other cases 128 // where the main thread creating this instance can be expected to not become 129 // blocked, so moving work to another thread and the overhead it adds are not 130 // required. 131 static std::unique_ptr<LayerTreeHost> CreateSingleThreaded( 132 LayerTreeHostSingleThreadClient* single_thread_client, 133 InitParams params); 134 135 LayerTreeHost(const LayerTreeHost&) = delete; 136 virtual ~LayerTreeHost(); 137 138 LayerTreeHost& operator=(const LayerTreeHost&) = delete; 139 140 // Returns the process global unique identifier for this LayerTreeHost. 141 int GetId() const; 142 143 // The current source frame number. This is incremented for each main frame 144 // update(commit) pushed to the compositor thread. The initial frame number 145 // is 0, and it is incremented once commit is completed (which is before the 146 // compositor-thread-side submits its frame for the commit). 147 int SourceFrameNumber() const; 148 149 // Returns the UIResourceManager used to create UIResources for 150 // UIResourceLayers pushed to the LayerTree. 151 UIResourceManager* GetUIResourceManager() const; 152 153 // Returns the TaskRunnerProvider used to access the main and compositor 154 // thread task runners. 155 TaskRunnerProvider* GetTaskRunnerProvider() const; 156 157 // Returns the settings used by this host. These settings are constants given 158 // at startup. 159 const LayerTreeSettings& GetSettings() const; 160 161 // Sets the LayerTreeMutator interface used to directly mutate the compositor 162 // state on the compositor thread. (Compositor-Worker) 163 void SetLayerTreeMutator(std::unique_ptr<LayerTreeMutator> mutator); 164 165 // Sets the LayerTreePainter interface used to dispatch the JS paint callback 166 // to a worklet thread. 167 void SetPaintWorkletLayerPainter( 168 std::unique_ptr<PaintWorkletLayerPainter> painter); 169 170 // Attachs a SwapPromise to the Layer tree, that passes through the 171 // LayerTreeHost and LayerTreeHostImpl with the next commit and frame 172 // submission, which can be used to observe that progress. This also 173 // causes a main frame to be requested. 174 // See swap_promise.h for how to use SwapPromise. 175 void QueueSwapPromise(std::unique_ptr<SwapPromise> swap_promise); 176 177 // Returns the SwapPromiseManager, used to insert SwapPromises dynamically 178 // when a main frame is requested. 179 SwapPromiseManager* GetSwapPromiseManager(); 180 181 std::unique_ptr<EventsMetricsManager::ScopedMonitor> 182 GetScopedEventMetricsMonitor(const EventMetrics& event_metrics); 183 void ClearEventsMetrics(); 184 185 // Visibility and LayerTreeFrameSink ------------------------------- 186 187 // Sets or gets if the LayerTreeHost is visible. When not visible it will: 188 // - Not request a new LayerTreeFrameSink from the client. 189 // - Stop submitting frames to the display compositor. 190 // - Stop producing main frames and committing them. 191 // The LayerTreeHost is not visible when first created, so this must be called 192 // to make it visible before it will attempt to start producing output. 193 void SetVisible(bool visible); 194 bool IsVisible() const; 195 196 // Called in response to a LayerTreeFrameSink request made to the client 197 // using LayerTreeHostClient::RequestNewLayerTreeFrameSink. The client will 198 // be informed of the LayerTreeFrameSink initialization status using 199 // DidInitializaLayerTreeFrameSink or DidFailToInitializeLayerTreeFrameSink. 200 // The request is completed when the host successfully initializes an 201 // LayerTreeFrameSink. 202 void SetLayerTreeFrameSink( 203 std::unique_ptr<LayerTreeFrameSink> layer_tree_frame_sink); 204 205 // Forces the host to immediately release all references to the 206 // LayerTreeFrameSink, if any. Can be safely called any time, but the 207 // compositor should not be visible. 208 std::unique_ptr<LayerTreeFrameSink> ReleaseLayerTreeFrameSink(); 209 210 // Frame Scheduling (main and compositor frames) requests ------- 211 212 // Requests a main frame update even if no content has changed. This is used, 213 // for instance in the case of RequestAnimationFrame from blink to ensure the 214 // main frame update is run on the next tick without pre-emptively forcing a 215 // full commit synchronization or layer updates. 216 void SetNeedsAnimate(); 217 218 // Requests a main frame update and also ensure that the host pulls layer 219 // updates from the client, even if no content might have changed, without 220 // forcing a full commit synchronization. 221 virtual void SetNeedsUpdateLayers(); 222 223 // Requests that the next main frame update performs a full commit 224 // synchronization. 225 virtual void SetNeedsCommit(); 226 227 // Returns true after SetNeedsAnimate(), SetNeedsUpdateLayers() or 228 // SetNeedsCommit(), until it is satisfied. 229 bool RequestedMainFramePendingForTesting() const; 230 231 // Requests that the next frame re-chooses crisp raster scales for all layers. 232 void SetNeedsRecalculateRasterScales(); 233 234 // Returns true if a main frame with commit synchronization has been 235 // requested. 236 bool CommitRequested() const; 237 238 // Prevents the compositor from requesting main frame updates from the client 239 // until the ScopedDeferMainFrameUpdate object is destroyed, or 240 // StopDeferringCommits is called. 241 std::unique_ptr<ScopedDeferMainFrameUpdate> DeferMainFrameUpdate(); 242 243 // Notification that the proxy started or stopped deferring main frame updates 244 void OnDeferMainFrameUpdatesChanged(bool); 245 246 // Prevents the proxy from committing the layer tree to the compositor, 247 // while still allowing main frame lifecycle updates. |timeout| 248 // is the interval after which commits will restart if nothing stops 249 // deferring sooner. If multiple calls are made to StartDeferringCommits 250 // while deferal is active, the first timeout continues to apply. 251 void StartDeferringCommits(base::TimeDelta timeout); 252 253 // Stop deferring commits immediately. 254 void StopDeferringCommits(PaintHoldingCommitTrigger); 255 256 // Notification that the proxy started or stopped deferring commits. 257 void OnDeferCommitsChanged(bool); 258 259 // Returns whether there are any outstanding ScopedDeferMainFrameUpdate, 260 // though commits may be deferred also when the local_surface_id_from_parent() 261 // is not valid. defer_main_frame_update()262 bool defer_main_frame_update() const { 263 return defer_main_frame_update_count_; 264 } 265 266 // Synchronously performs a main frame update and layer updates. Used only in 267 // single threaded mode when the compositor's internal scheduling is disabled. 268 void LayoutAndUpdateLayers(); 269 270 // Synchronously performs a complete main frame update, commit and compositor 271 // frame. Used only in single threaded mode when the compositor's internal 272 // scheduling is disabled. 273 void Composite(base::TimeTicks frame_begin_time, bool raster); 274 275 // Requests a redraw (compositor frame) for the given rect. 276 void SetNeedsRedrawRect(const gfx::Rect& damage_rect); 277 278 // Requests a main frame (including layer updates) and ensures that this main 279 // frame results in a redraw for the complete viewport when producing the 280 // CompositorFrame. 281 void SetNeedsCommitWithForcedRedraw(); 282 283 // Input Handling --------------------------------------------- 284 285 // Sets the state of the browser controls. (Used for URL bar animations). 286 void UpdateBrowserControlsState(BrowserControlsState constraints, 287 BrowserControlsState current, 288 bool animate); 289 290 // Returns a reference to the InputHandler used to respond to input events on 291 // the compositor thread. 292 const base::WeakPtr<InputHandler>& GetInputHandler() const; 293 294 // Debugging and benchmarks --------------------------------- 295 void SetDebugState(const LayerTreeDebugState& debug_state); 296 const LayerTreeDebugState& GetDebugState() const; 297 298 // Returns the id of the benchmark on success, 0 otherwise. 299 int ScheduleMicroBenchmark(const std::string& benchmark_name, 300 std::unique_ptr<base::Value> value, 301 MicroBenchmark::DoneCallback callback); 302 303 // Returns true if the message was successfully delivered and handled. 304 bool SendMessageToMicroBenchmark(int id, std::unique_ptr<base::Value> value); 305 306 // When the main thread informs the compositor thread that it is ready to 307 // commit, generally it would remain blocked until the main thread state is 308 // copied to the pending tree. Calling this would ensure that the main thread 309 // remains blocked until the pending tree is activated. 310 void SetNextCommitWaitsForActivation(); 311 312 // Registers a callback that is run when the next frame successfully makes it 313 // to the screen (it's entirely possible some frames may be dropped between 314 // the time this is called and the callback is run). 315 using PresentationTimeCallback = 316 base::OnceCallback<void(const gfx::PresentationFeedback&)>; 317 void RequestPresentationTimeForNextFrame(PresentationTimeCallback callback); 318 319 // Layer tree accessors and modifiers ------------------------ 320 321 // Sets or gets the root of the Layer tree. Children of the root Layer are 322 // attached to it and will be added/removed along with the root Layer. The 323 // LayerTreeHost retains ownership of a reference to the root Layer. 324 void SetRootLayer(scoped_refptr<Layer> root_layer); root_layer()325 Layer* root_layer() { return root_layer_.get(); } root_layer()326 const Layer* root_layer() const { return root_layer_.get(); } 327 328 // Sets the root layer which is not managed by blink, and we will initialize 329 // its paint properties using PropertyTreeBuilder. For ui::Compositor, because 330 // for now we always use PropertyTreeBulder, this function is equivalent to 331 // SetRootLayer(). 332 // TODO(crbug.com/925855): This is temporary. Eventually we should let the 333 // caller inform blink about the layer and remove the function. 334 void SetNonBlinkManagedRootLayer(scoped_refptr<Layer> root_layer); 335 336 struct ViewportPropertyIds { 337 int overscroll_elasticity_transform = TransformTree::kInvalidNodeId; 338 int page_scale_transform = TransformTree::kInvalidNodeId; 339 int inner_scroll = ScrollTree::kInvalidNodeId; 340 int outer_clip = ClipTree::kInvalidNodeId; 341 int outer_scroll = ScrollTree::kInvalidNodeId; 342 }; 343 344 // Sets the collection of viewport property ids, defined to allow viewport 345 // pinch-zoom etc. on the compositor thread. This is set only on the 346 // main-frame's compositor, i.e., will be unset in OOPIF and UI compositors. 347 void RegisterViewportPropertyIds(const ViewportPropertyIds&); 348 ViewportPropertyIdsForTesting()349 LayerTreeHost::ViewportPropertyIds ViewportPropertyIdsForTesting() const { 350 return viewport_property_ids_; 351 } 352 Layer* InnerViewportScrollLayerForTesting() const; 353 Layer* OuterViewportScrollLayerForTesting() const; 354 355 // Sets or gets the position of touch handles for a text selection. These are 356 // submitted to the display compositor along with the Layer tree's contents 357 // allowing it to present the selection handles. This is done because the 358 // handles are a UI widget above, and not clipped to, the viewport of this 359 // LayerTreeHost. 360 void RegisterSelection(const LayerSelection& selection); selection()361 const LayerSelection& selection() const { return selection_; } 362 363 // Sets or gets if the client has any scroll event handlers registered. This 364 // allows the threaded compositor to prioritize main frames even when 365 // servicing a touch scroll on the compositor thread, in order to give the 366 // event handler a chance to be part of each frame. 367 void SetHaveScrollEventHandlers(bool have_event_handlers); have_scroll_event_handlers()368 bool have_scroll_event_handlers() const { 369 return have_scroll_event_handlers_; 370 } 371 372 // Set or get what event handlers exist on the layer tree in order to inform 373 // the compositor thread if it is able to handle an input event, or it needs 374 // to pass it to the main thread to be handled. The class is the type of input 375 // event, and for each class there is a properties defining if the compositor 376 // thread can handle the event. 377 void SetEventListenerProperties(EventListenerClass event_class, 378 EventListenerProperties event_properties); event_listener_properties(EventListenerClass event_class)379 EventListenerProperties event_listener_properties( 380 EventListenerClass event_class) const { 381 return event_listener_properties_[static_cast<size_t>(event_class)]; 382 } 383 384 void SetViewportRectAndScale(const gfx::Rect& device_viewport_rect, 385 float device_scale_factor, 386 const viz::LocalSurfaceIdAllocation& 387 local_surface_id_allocation_from_parent); 388 389 void SetViewportVisibleRect(const gfx::Rect& visible_rect); 390 viewport_visible_rect()391 gfx::Rect viewport_visible_rect() const { return viewport_visible_rect_; } 392 device_viewport_rect()393 gfx::Rect device_viewport_rect() const { return device_viewport_rect_; } 394 395 void SetBrowserControlsParams(const BrowserControlsParams& params); 396 void SetBrowserControlsShownRatio(float top_ratio, float bottom_ratio); 397 398 void SetOverscrollBehavior(const OverscrollBehavior& overscroll_behavior); overscroll_behavior()399 const OverscrollBehavior& overscroll_behavior() const { 400 return overscroll_behavior_; 401 } 402 403 void SetPageScaleFactorAndLimits(float page_scale_factor, 404 float min_page_scale_factor, 405 float max_page_scale_factor); page_scale_factor()406 float page_scale_factor() const { return page_scale_factor_; } min_page_scale_factor()407 float min_page_scale_factor() const { return min_page_scale_factor_; } max_page_scale_factor()408 float max_page_scale_factor() const { return max_page_scale_factor_; } 409 set_background_color(SkColor color)410 void set_background_color(SkColor color) { background_color_ = color; } background_color()411 SkColor background_color() const { return background_color_; } 412 set_display_transform_hint(gfx::OverlayTransform hint)413 void set_display_transform_hint(gfx::OverlayTransform hint) { 414 display_transform_hint_ = hint; 415 } display_transform_hint()416 gfx::OverlayTransform display_transform_hint() const { 417 return display_transform_hint_; 418 } 419 420 void StartPageScaleAnimation(const gfx::Vector2d& target_offset, 421 bool use_anchor, 422 float scale, 423 base::TimeDelta duration); 424 bool HasPendingPageScaleAnimation() const; 425 device_scale_factor()426 float device_scale_factor() const { return device_scale_factor_; } 427 428 void SetRecordingScaleFactor(float recording_scale_factor); 429 painted_device_scale_factor()430 float painted_device_scale_factor() const { 431 return painted_device_scale_factor_; 432 } 433 434 // If this LayerTreeHost needs a valid viz::LocalSurfaceId then commits will 435 // be deferred until a valid viz::LocalSurfaceId is provided. 436 void SetLocalSurfaceIdAllocationFromParent( 437 const viz::LocalSurfaceIdAllocation& 438 local_surface_id_allocation_from_parent); 439 local_surface_id_allocation_from_parent()440 const viz::LocalSurfaceIdAllocation& local_surface_id_allocation_from_parent() 441 const { 442 return local_surface_id_allocation_from_parent_; 443 } 444 445 // Requests the allocation of a new LocalSurfaceId on the compositor thread. 446 void RequestNewLocalSurfaceId(); 447 448 // Returns the current state of the new LocalSurfaceId request and resets 449 // the state. 450 bool TakeNewLocalSurfaceIdRequest(); new_local_surface_id_request_for_testing()451 bool new_local_surface_id_request_for_testing() const { 452 return new_local_surface_id_request_; 453 } 454 455 void SetRasterColorSpace(const gfx::ColorSpace& raster_color_space); raster_color_space()456 const gfx::ColorSpace& raster_color_space() const { 457 return raster_color_space_; 458 } 459 460 // This layer tree may be embedded in a hierarchy that has page scale 461 // factor controlled at the top level. We represent that scale here as 462 // 'external_page_scale_factor', a value that affects raster scale in the 463 // same way that page_scale_factor does, but doesn't affect any geometry 464 // calculations. 465 void SetExternalPageScaleFactor(float page_scale_factor, 466 bool is_external_pinch_gesture_active); is_external_pinch_gesture_active_for_testing()467 bool is_external_pinch_gesture_active_for_testing() { 468 return is_external_pinch_gesture_active_; 469 } 470 471 // Requests that we force send RenderFrameMetadata with the next frame. RequestForceSendMetadata()472 void RequestForceSendMetadata() { force_send_metadata_request_ = true; } 473 474 // Returns the state of |force_send_metadata_request_| and resets the 475 // variable to false. 476 bool TakeForceSendMetadataRequest(); 477 478 // Used externally by blink for setting the PropertyTrees when 479 // UseLayerLists() is true, which also implies that Slimming Paint 480 // v2 is enabled. property_trees()481 PropertyTrees* property_trees() { return &property_trees_; } property_trees()482 const PropertyTrees* property_trees() const { return &property_trees_; } 483 484 void SetPropertyTreesForTesting(const PropertyTrees* property_trees); 485 486 void SetNeedsDisplayOnAllLayers(); 487 488 void RegisterLayer(Layer* layer); 489 void UnregisterLayer(Layer* layer); 490 Layer* LayerById(int id) const; 491 492 bool PaintContent(const LayerList& update_layer_list); in_paint_layer_contents()493 bool in_paint_layer_contents() const { return in_paint_layer_contents_; } 494 495 void SetHasCopyRequest(bool has_copy_request); has_copy_request()496 bool has_copy_request() const { return has_copy_request_; } 497 498 void AddSurfaceRange(const viz::SurfaceRange& surface_range); 499 void RemoveSurfaceRange(const viz::SurfaceRange& surface_range); 500 base::flat_set<viz::SurfaceRange> SurfaceRanges() const; 501 502 // Marks or unmarks a layer are needing PushPropertiesTo in the next commit. 503 // These are internal methods, called from the Layer itself when changing a 504 // property or completing a PushPropertiesTo. 505 void AddLayerShouldPushProperties(Layer* layer); 506 void RemoveLayerShouldPushProperties(Layer* layer); 507 void ClearLayersThatShouldPushProperties(); 508 // The current set of all Layers attached to the LayerTreeHost's tree that 509 // have been marked as needing PushPropertiesTo in the next commit. LayersThatShouldPushProperties()510 const base::flat_set<Layer*>& LayersThatShouldPushProperties() { 511 return layers_that_should_push_properties_; 512 } 513 514 void SetPageScaleFromImplSide(float page_scale); 515 void SetElasticOverscrollFromImplSide(gfx::Vector2dF elastic_overscroll); elastic_overscroll()516 gfx::Vector2dF elastic_overscroll() const { return elastic_overscroll_; } 517 518 // Ensures a HUD layer exists if it is needed, and updates the HUD bounds and 519 // position. If a HUD layer exists but is no longer needed, it is destroyed. 520 void UpdateHudLayer(bool show_hud_info); hud_layer()521 HeadsUpDisplayLayer* hud_layer() const { return hud_layer_.get(); } 522 bool is_hud_layer(const Layer*) const; 523 524 virtual void SetNeedsFullTreeSync(); needs_full_tree_sync()525 bool needs_full_tree_sync() const { return needs_full_tree_sync_; } 526 needs_surface_ranges_sync()527 bool needs_surface_ranges_sync() const { return needs_surface_ranges_sync_; } set_needs_surface_ranges_sync(bool needs_surface_ranges_sync)528 void set_needs_surface_ranges_sync(bool needs_surface_ranges_sync) { 529 needs_surface_ranges_sync_ = needs_surface_ranges_sync; 530 } 531 532 void SetPropertyTreesNeedRebuild(); 533 534 void PushPropertyTreesTo(LayerTreeImpl* tree_impl); 535 void PushLayerTreePropertiesTo(LayerTreeImpl* tree_impl); 536 void PushSurfaceRangesTo(LayerTreeImpl* tree_impl); 537 void PushLayerTreeHostPropertiesTo(LayerTreeHostImpl* host_impl); 538 void MoveChangeTrackingToLayers(LayerTreeImpl* tree_impl); 539 mutator_host()540 MutatorHost* mutator_host() const { return mutator_host_; } 541 542 // Returns the layer with the given |element_id|. In layer-list mode, only 543 // scrollable layers are registered in this map. 544 Layer* LayerByElementId(ElementId element_id) const; 545 void RegisterElement(ElementId element_id, 546 Layer* layer); 547 void UnregisterElement(ElementId element_id); 548 549 // For layer list mode only. 550 void UpdateActiveElements(); 551 552 void SetElementIdsForTesting(); 553 554 void BuildPropertyTreesForTesting(); 555 556 // Layer iterators. 557 LayerListIterator begin() const; 558 LayerListIterator end() const; 559 LayerListReverseIterator rbegin(); 560 LayerListReverseIterator rend(); 561 562 // LayerTreeHost interface to Proxy. 563 void WillBeginMainFrame(); 564 void DidBeginMainFrame(); 565 void BeginMainFrame(const viz::BeginFrameArgs& args); 566 void BeginMainFrameNotExpectedSoon(); 567 void BeginMainFrameNotExpectedUntil(base::TimeTicks time); 568 void AnimateLayers(base::TimeTicks monotonic_frame_begin_time); 569 void RequestMainFrameUpdate(bool report_cc_metrics); 570 void FinishCommitOnImplThread(LayerTreeHostImpl* host_impl); 571 void WillCommit(); 572 void CommitComplete(); 573 void RequestNewLayerTreeFrameSink(); 574 void DidInitializeLayerTreeFrameSink(); 575 void DidFailToInitializeLayerTreeFrameSink(); 576 virtual std::unique_ptr<LayerTreeHostImpl> CreateLayerTreeHostImpl( 577 LayerTreeHostImplClient* client); 578 void DidLoseLayerTreeFrameSink(); DidCommitAndDrawFrame()579 void DidCommitAndDrawFrame() { client_->DidCommitAndDrawFrame(); } DidReceiveCompositorFrameAck()580 void DidReceiveCompositorFrameAck() { 581 client_->DidReceiveCompositorFrameAck(); 582 } 583 bool UpdateLayers(); 584 void DidPresentCompositorFrame( 585 uint32_t frame_token, 586 std::vector<LayerTreeHost::PresentationTimeCallback> callbacks, 587 const gfx::PresentationFeedback& feedback); 588 // Called when the compositor completed page scale animation. 589 void DidCompletePageScaleAnimation(); 590 void ApplyScrollAndScale(ScrollAndScaleSet* info); 591 void ApplyMutatorEvents(std::unique_ptr<MutatorEvents> events); 592 void RecordStartOfFrameMetrics(); 593 void RecordEndOfFrameMetrics(base::TimeTicks frame_begin_time, 594 ActiveFrameSequenceTrackers trackers); 595 client()596 LayerTreeHostClient* client() { return client_; } scheduling_client()597 LayerTreeHostSchedulingClient* scheduling_client() { 598 return scheduling_client_; 599 } 600 gpu_rasterization_histogram_recorded()601 bool gpu_rasterization_histogram_recorded() const { 602 return gpu_rasterization_histogram_recorded_; 603 } 604 605 void CollectRenderingStats(RenderingStats* stats) const; 606 rendering_stats_instrumentation()607 RenderingStatsInstrumentation* rendering_stats_instrumentation() const { 608 return rendering_stats_instrumentation_.get(); 609 } 610 proxy()611 Proxy* proxy() const { return proxy_.get(); } 612 613 bool IsSingleThreaded() const; 614 bool IsThreaded() const; 615 616 // Indicates whether this host is configured to use layer lists 617 // rather than layer trees. This also implies that property trees 618 // are always already built and so cc doesn't have to build them. 619 bool IsUsingLayerLists() const; 620 621 // MutatorHostClient implementation. 622 bool IsElementInPropertyTrees(ElementId element_id, 623 ElementListType list_type) const override; 624 void SetMutatorsNeedCommit() override; 625 void SetMutatorsNeedRebuildPropertyTrees() override; 626 void SetElementFilterMutated(ElementId element_id, 627 ElementListType list_type, 628 const FilterOperations& filters) override; 629 void SetElementBackdropFilterMutated( 630 ElementId element_id, 631 ElementListType list_type, 632 const FilterOperations& backdrop_filters) override; 633 void SetElementOpacityMutated(ElementId element_id, 634 ElementListType list_type, 635 float opacity) override; 636 void SetElementTransformMutated(ElementId element_id, 637 ElementListType list_type, 638 const gfx::Transform& transform) override; 639 void SetElementScrollOffsetMutated( 640 ElementId element_id, 641 ElementListType list_type, 642 const gfx::ScrollOffset& scroll_offset) override; 643 644 void ElementIsAnimatingChanged(const PropertyToElementIdMap& element_id_map, 645 ElementListType list_type, 646 const PropertyAnimationState& mask, 647 const PropertyAnimationState& state) override; 648 void AnimationScalesChanged(ElementId element_id, 649 ElementListType list_type, 650 float maximum_scale, 651 float starting_scale) override; 652 OnCustomPropertyMutated(ElementId element_id,const std::string & custom_property_name,PaintWorkletInput::PropertyValue custom_property_value)653 void OnCustomPropertyMutated( 654 ElementId element_id, 655 const std::string& custom_property_name, 656 PaintWorkletInput::PropertyValue custom_property_value) override {} 657 ScrollOffsetAnimationFinished()658 void ScrollOffsetAnimationFinished() override {} 659 gfx::ScrollOffset GetScrollOffsetForAnimation( 660 ElementId element_id) const override; 661 NotifyAnimationWorkletStateChange(AnimationWorkletMutationState state,ElementListType tree_type)662 void NotifyAnimationWorkletStateChange(AnimationWorkletMutationState state, 663 ElementListType tree_type) override {} 664 665 void QueueImageDecode(const PaintImage& image, 666 base::OnceCallback<void(bool)> callback); 667 void ImageDecodesFinished(const std::vector<std::pair<int, bool>>& results); 668 669 void RequestBeginMainFrameNotExpected(bool new_state); 670 recording_scale_factor()671 float recording_scale_factor() const { return recording_scale_factor_; } 672 673 void SetSourceURL(ukm::SourceId source_id, const GURL& url); 674 675 void SetRenderFrameObserver( 676 std::unique_ptr<RenderFrameMetadataObserver> observer); 677 678 std::string LayersAsString() const; 679 680 // Captures the on-screen text content, if success, fills the associated 681 // NodeId in |content| and return true, otherwise return false. 682 bool CaptureContent(std::vector<NodeId>* content); 683 begin_main_frame_metrics()684 std::unique_ptr<BeginMainFrameMetrics> begin_main_frame_metrics() { 685 return std::move(begin_main_frame_metrics_); 686 } 687 688 // Set the the impl proxy when a commit from the main thread begins 689 // processing. Used in metrics to determine the time spent waiting on thread 690 // synchronization. SetImplCommitStartTime(base::TimeTicks commit_start_time)691 void SetImplCommitStartTime(base::TimeTicks commit_start_time) { 692 impl_commit_start_time_ = commit_start_time; 693 } 694 695 protected: 696 LayerTreeHost(InitParams params, CompositorMode mode); 697 698 void InitializeThreaded( 699 scoped_refptr<base::SingleThreadTaskRunner> main_task_runner, 700 scoped_refptr<base::SingleThreadTaskRunner> impl_task_runner); 701 void InitializeSingleThreaded( 702 LayerTreeHostSingleThreadClient* single_thread_client, 703 scoped_refptr<base::SingleThreadTaskRunner> main_task_runner); 704 void InitializeForTesting( 705 std::unique_ptr<TaskRunnerProvider> task_runner_provider, 706 std::unique_ptr<Proxy> proxy_for_testing); 707 void SetTaskRunnerProviderForTesting( 708 std::unique_ptr<TaskRunnerProvider> task_runner_provider); 709 void SetUIResourceManagerForTesting( 710 std::unique_ptr<UIResourceManager> ui_resource_manager); 711 712 // task_graph_runner() returns a valid value only until the LayerTreeHostImpl 713 // is created in CreateLayerTreeHostImpl(). task_graph_runner()714 TaskGraphRunner* task_graph_runner() const { return task_graph_runner_; } 715 716 void OnCommitForSwapPromises(); 717 718 void RecordGpuRasterizationHistogram(const LayerTreeHostImpl* host_impl); 719 720 MicroBenchmarkController micro_benchmark_controller_; 721 722 base::WeakPtr<InputHandler> input_handler_weak_ptr_; 723 724 scoped_refptr<base::SequencedTaskRunner> image_worker_task_runner_; 725 std::unique_ptr<UkmRecorderFactory> ukm_recorder_factory_; 726 727 private: 728 friend class LayerTreeHostSerializationTest; 729 friend class ScopedDeferMainFrameUpdate; 730 731 // This is the number of consecutive frames in which we want the content to be 732 // free of slow-paths before toggling the flag. 733 enum { kNumFramesToConsiderBeforeRemovingSlowPathFlag = 60 }; 734 735 void ApplyViewportChanges(const ScrollAndScaleSet& info); 736 void RecordManipulationTypeCounts(const ScrollAndScaleSet& scroll_info); 737 void SendOverscrollAndScrollEndEventsFromImplSide( 738 const ScrollAndScaleSet& info); 739 void ApplyPageScaleDeltaFromImplSide(float page_scale_delta); 740 void InitializeProxy(std::unique_ptr<Proxy> proxy); 741 742 bool DoUpdateLayers(); 743 744 void UpdateDeferMainFrameUpdateInternal(); 745 746 const CompositorMode compositor_mode_; 747 748 std::unique_ptr<UIResourceManager> ui_resource_manager_; 749 750 LayerTreeHostClient* client_; 751 LayerTreeHostSchedulingClient* scheduling_client_; 752 std::unique_ptr<Proxy> proxy_; 753 std::unique_ptr<TaskRunnerProvider> task_runner_provider_; 754 755 int source_frame_number_ = 0U; 756 std::unique_ptr<RenderingStatsInstrumentation> 757 rendering_stats_instrumentation_; 758 759 SwapPromiseManager swap_promise_manager_; 760 761 // |current_layer_tree_frame_sink_| can't be updated until we've successfully 762 // initialized a new LayerTreeFrameSink. |new_layer_tree_frame_sink_| 763 // contains the new LayerTreeFrameSink that is currently being initialized. 764 // If initialization is successful then |new_layer_tree_frame_sink_| replaces 765 // |current_layer_tree_frame_sink_|. 766 std::unique_ptr<LayerTreeFrameSink> new_layer_tree_frame_sink_; 767 std::unique_ptr<LayerTreeFrameSink> current_layer_tree_frame_sink_; 768 769 const LayerTreeSettings settings_; 770 LayerTreeDebugState debug_state_; 771 772 bool visible_ = false; 773 774 bool gpu_rasterization_histogram_recorded_ = false; 775 776 // If set, then page scale animation has completed, but the client hasn't been 777 // notified about it yet. 778 bool did_complete_scale_animation_ = false; 779 780 int id_; 781 bool next_commit_forces_redraw_ = false; 782 bool next_commit_forces_recalculate_raster_scales_ = false; 783 // Track when we're inside a main frame to see if compositor is being 784 // destroyed midway which causes a crash. crbug.com/654672 785 bool inside_main_frame_ = false; 786 787 TaskGraphRunner* task_graph_runner_; 788 789 uint32_t num_consecutive_frames_without_slow_paths_ = 0; 790 791 scoped_refptr<Layer> root_layer_; 792 793 ViewportPropertyIds viewport_property_ids_; 794 795 OverscrollBehavior overscroll_behavior_; 796 797 BrowserControlsParams browser_controls_params_; 798 float top_controls_shown_ratio_ = 0.f; 799 float bottom_controls_shown_ratio_ = 0.f; 800 801 float device_scale_factor_ = 1.f; 802 float painted_device_scale_factor_ = 1.f; 803 float recording_scale_factor_ = 1.f; 804 float page_scale_factor_ = 1.f; 805 float min_page_scale_factor_ = 1.f; 806 float max_page_scale_factor_ = 1.f; 807 float external_page_scale_factor_ = 1.f; 808 bool is_external_pinch_gesture_active_ = false; 809 // Used to track the out-bound state for ApplyViewportChanges. 810 bool is_pinch_gesture_active_from_impl_ = false; 811 812 gfx::ColorSpace raster_color_space_; 813 814 bool clear_caches_on_next_commit_ = false; 815 viz::LocalSurfaceIdAllocation local_surface_id_allocation_from_parent_; 816 bool new_local_surface_id_request_ = false; 817 uint32_t defer_main_frame_update_count_ = 0; 818 819 SkColor background_color_ = SK_ColorWHITE; 820 821 // Display transform hint to tag generated compositor frames. 822 gfx::OverlayTransform display_transform_hint_ = gfx::OVERLAY_TRANSFORM_NONE; 823 824 LayerSelection selection_; 825 826 gfx::Rect device_viewport_rect_; 827 828 gfx::Rect viewport_visible_rect_; 829 830 bool have_scroll_event_handlers_ = false; 831 EventListenerProperties event_listener_properties_ 832 [static_cast<size_t>(EventListenerClass::kLast) + 1]; 833 834 std::unique_ptr<PendingPageScaleAnimation> pending_page_scale_animation_; 835 836 // Whether we have a pending request to force send RenderFrameMetadata with 837 // the next frame. 838 bool force_send_metadata_request_ = false; 839 840 PropertyTrees property_trees_; 841 842 bool needs_full_tree_sync_ = true; 843 844 bool needs_surface_ranges_sync_ = false; 845 846 gfx::Vector2dF elastic_overscroll_; 847 848 scoped_refptr<HeadsUpDisplayLayer> hud_layer_; 849 850 // The number of SurfaceLayers that have (fallback,primary) set to 851 // viz::SurfaceRange. 852 base::flat_map<viz::SurfaceRange, int> surface_ranges_; 853 854 // Set of layers that need to push properties. 855 base::flat_set<Layer*> layers_that_should_push_properties_; 856 857 // Layer id to Layer map. 858 std::unordered_map<int, Layer*> layer_id_map_; 859 860 // This is for layer tree mode only. 861 std::unordered_map<ElementId, Layer*, ElementIdHash> element_layers_map_; 862 863 bool in_paint_layer_contents_ = false; 864 865 // This is true if atleast one layer in the layer tree has a copy request. We 866 // use this bool to decide whether we need to compute subtree has copy request 867 // for every layer during property tree building. 868 bool has_copy_request_ = false; 869 870 // When settings_.use_layer_lists is true, paint properties are generated by 871 // blink and we don't use PropertyTreeBuilder, except that the root layer 872 // is set by SetNonBlinkManagedRootLayer(). 873 // TODO(crbug.com/925855): Remove this field when removing 874 // SetNonBlinkManagedRootLayer(). 875 bool force_use_property_tree_builder_ = false; 876 877 MutatorHost* mutator_host_; 878 879 std::vector<std::pair<PaintImage, base::OnceCallback<void(bool)>>> 880 queued_image_decodes_; 881 std::unordered_map<int, base::OnceCallback<void(bool)>> 882 pending_image_decodes_; 883 884 // Presentation time callbacks requested for the next frame are initially 885 // added here. 886 std::vector<PresentationTimeCallback> pending_presentation_time_callbacks_; 887 888 // Latency information for work done in ProxyMain::BeginMainFrame. The 889 // unique_ptr is allocated in RequestMainFrameUpdate, and passed to Blink's 890 // LocalFrameView that fills in the fields. This object adds the timing for 891 // UpdateLayers. CC reads the data during commit, and clears the unique_ptr. 892 std::unique_ptr<BeginMainFrameMetrics> begin_main_frame_metrics_; 893 894 // The time that the impl thread started processing the most recent commit 895 // sent from the main thread. Zero if the most recent BeginMainFrame did not 896 // result in a commit (due to no change in content). 897 base::TimeTicks impl_commit_start_time_; 898 899 EventsMetricsManager events_metrics_manager_; 900 901 // Used to vend weak pointers to LayerTreeHost to ScopedDeferMainFrameUpdate 902 // objects. 903 base::WeakPtrFactory<LayerTreeHost> defer_main_frame_update_weak_ptr_factory_{ 904 this}; 905 }; 906 907 } // namespace cc 908 909 #endif // CC_TREES_LAYER_TREE_HOST_H_ 910