cc: Implement shared worker contexts.
[chromium-blink-merge.git] / cc / trees / layer_tree_host.h
blob29990f930c3725aabb473c96b0d1309caa7bf61f
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_
8 #include <limits>
9 #include <set>
10 #include <string>
11 #include <vector>
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 "base/timer/timer.h"
21 #include "cc/animation/animation_events.h"
22 #include "cc/base/cc_export.h"
23 #include "cc/base/scoped_ptr_vector.h"
24 #include "cc/debug/frame_timing_tracker.h"
25 #include "cc/debug/micro_benchmark.h"
26 #include "cc/debug/micro_benchmark_controller.h"
27 #include "cc/input/input_handler.h"
28 #include "cc/input/layer_selection_bound.h"
29 #include "cc/input/scrollbar.h"
30 #include "cc/input/top_controls_state.h"
31 #include "cc/layers/layer_lists.h"
32 #include "cc/output/output_surface.h"
33 #include "cc/output/renderer_capabilities.h"
34 #include "cc/output/swap_promise.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/mutator_host_client.h"
42 #include "cc/trees/proxy.h"
43 #include "cc/trees/swap_promise_monitor.h"
44 #include "third_party/skia/include/core/SkColor.h"
45 #include "ui/gfx/geometry/rect.h"
47 namespace gpu {
48 class GpuMemoryBufferManager;
51 namespace cc {
52 class AnimationRegistrar;
53 class AnimationHost;
54 class BeginFrameSource;
55 class HeadsUpDisplayLayer;
56 class Layer;
57 class LayerTreeHostImpl;
58 class LayerTreeHostImplClient;
59 class LayerTreeHostSingleThreadClient;
60 class PropertyTrees;
61 class Region;
62 class RenderingStatsInstrumentation;
63 class ResourceProvider;
64 class ResourceUpdateQueue;
65 class SharedBitmapManager;
66 class TaskGraphRunner;
67 class TopControlsManager;
68 class UIResourceRequest;
69 struct PendingPageScaleAnimation;
70 struct RenderingStats;
71 struct ScrollAndScaleSet;
73 class CC_EXPORT LayerTreeHost : public MutatorHostClient {
74 public:
75 // TODO(sad): InitParams should be a movable type so that it can be
76 // std::move()d to the Create* functions.
77 struct CC_EXPORT InitParams {
78 LayerTreeHostClient* client = nullptr;
79 SharedBitmapManager* shared_bitmap_manager = nullptr;
80 gpu::GpuMemoryBufferManager* gpu_memory_buffer_manager = nullptr;
81 TaskGraphRunner* task_graph_runner = nullptr;
82 LayerTreeSettings const* settings = nullptr;
83 scoped_refptr<base::SingleThreadTaskRunner> main_task_runner;
84 scoped_ptr<BeginFrameSource> external_begin_frame_source;
86 InitParams();
87 ~InitParams();
90 // The SharedBitmapManager will be used on the compositor thread.
91 static scoped_ptr<LayerTreeHost> CreateThreaded(
92 scoped_refptr<base::SingleThreadTaskRunner> impl_task_runner,
93 InitParams* params);
95 static scoped_ptr<LayerTreeHost> CreateSingleThreaded(
96 LayerTreeHostSingleThreadClient* single_thread_client,
97 InitParams* params);
98 virtual ~LayerTreeHost();
100 void SetLayerTreeHostClientReady();
102 // LayerTreeHost interface to Proxy.
103 void WillBeginMainFrame();
104 void DidBeginMainFrame();
105 void BeginMainFrame(const BeginFrameArgs& args);
106 void BeginMainFrameNotExpectedSoon();
107 void AnimateLayers(base::TimeTicks monotonic_frame_begin_time);
108 void DidStopFlinging();
109 void Layout();
110 void FinishCommitOnImplThread(LayerTreeHostImpl* host_impl);
111 void WillCommit();
112 void CommitComplete();
113 void SetOutputSurface(scoped_ptr<OutputSurface> output_surface);
114 void RequestNewOutputSurface();
115 void DidInitializeOutputSurface();
116 void DidFailToInitializeOutputSurface();
117 virtual scoped_ptr<LayerTreeHostImpl> CreateLayerTreeHostImpl(
118 LayerTreeHostImplClient* client);
119 void DidLoseOutputSurface();
120 bool output_surface_lost() const { return output_surface_lost_; }
121 void DidCommitAndDrawFrame() { client_->DidCommitAndDrawFrame(); }
122 void DidCompleteSwapBuffers() { client_->DidCompleteSwapBuffers(); }
123 bool UpdateLayers();
125 // Called when the compositor completed page scale animation.
126 void DidCompletePageScaleAnimation();
128 LayerTreeHostClient* client() { return client_; }
129 const base::WeakPtr<InputHandler>& GetInputHandler() {
130 return input_handler_weak_ptr_;
133 void NotifyInputThrottledUntilCommit();
135 void LayoutAndUpdateLayers();
136 void Composite(base::TimeTicks frame_begin_time);
138 void FinishAllRendering();
140 void SetDeferCommits(bool defer_commits);
142 int source_frame_number() const { return source_frame_number_; }
144 int meta_information_sequence_number() {
145 return meta_information_sequence_number_;
148 void IncrementMetaInformationSequenceNumber() {
149 meta_information_sequence_number_++;
152 void SetNeedsDisplayOnAllLayers();
154 void CollectRenderingStats(RenderingStats* stats) const;
156 RenderingStatsInstrumentation* rendering_stats_instrumentation() const {
157 return rendering_stats_instrumentation_.get();
160 const RendererCapabilities& GetRendererCapabilities() const;
162 void SetNeedsAnimate();
163 virtual void SetNeedsUpdateLayers();
164 virtual void SetNeedsCommit();
165 virtual void SetNeedsFullTreeSync();
166 virtual void SetNeedsMetaInfoRecomputation(
167 bool needs_meta_info_recomputation);
168 void SetNeedsRedraw();
169 void SetNeedsRedrawRect(const gfx::Rect& damage_rect);
170 bool CommitRequested() const;
171 bool BeginMainFrameRequested() const;
173 void SetNextCommitWaitsForActivation();
175 void SetNextCommitForcesRedraw();
177 void SetAnimationEvents(scoped_ptr<AnimationEventsVector> events);
179 void SetRootLayer(scoped_refptr<Layer> root_layer);
180 Layer* root_layer() { return root_layer_.get(); }
181 const Layer* root_layer() const { return root_layer_.get(); }
182 const Layer* overscroll_elasticity_layer() const {
183 return overscroll_elasticity_layer_.get();
185 const Layer* page_scale_layer() const { return page_scale_layer_.get(); }
186 void RegisterViewportLayers(scoped_refptr<Layer> overscroll_elasticity_layer,
187 scoped_refptr<Layer> page_scale_layer,
188 scoped_refptr<Layer> inner_viewport_scroll_layer,
189 scoped_refptr<Layer> outer_viewport_scroll_layer);
190 Layer* inner_viewport_scroll_layer() const {
191 return inner_viewport_scroll_layer_.get();
193 Layer* outer_viewport_scroll_layer() const {
194 return outer_viewport_scroll_layer_.get();
197 void RegisterSelection(const LayerSelection& selection);
199 const LayerTreeSettings& settings() const { return settings_; }
201 void SetDebugState(const LayerTreeDebugState& debug_state);
202 const LayerTreeDebugState& debug_state() const { return debug_state_; }
204 bool has_gpu_rasterization_trigger() const {
205 return has_gpu_rasterization_trigger_;
207 void SetHasGpuRasterizationTrigger(bool has_trigger);
209 void SetViewportSize(const gfx::Size& device_viewport_size);
210 void SetTopControlsHeight(float height, bool shrink);
211 void SetTopControlsShownRatio(float ratio);
213 void set_hide_pinch_scrollbars_near_min_scale(bool hide) {
214 hide_pinch_scrollbars_near_min_scale_ = hide;
217 gfx::Size device_viewport_size() const { return device_viewport_size_; }
219 void ApplyPageScaleDeltaFromImplSide(float page_scale_delta);
220 void SetPageScaleFactorAndLimits(float page_scale_factor,
221 float min_page_scale_factor,
222 float max_page_scale_factor);
223 float page_scale_factor() const { return page_scale_factor_; }
224 gfx::Vector2dF elastic_overscroll() const { return elastic_overscroll_; }
226 SkColor background_color() const { return background_color_; }
227 void set_background_color(SkColor color) { background_color_ = color; }
229 void set_has_transparent_background(bool transparent) {
230 has_transparent_background_ = transparent;
233 void SetVisible(bool visible);
234 bool visible() const { return visible_; }
236 void SetThrottleFrameProduction(bool throttle);
238 void StartPageScaleAnimation(const gfx::Vector2d& target_offset,
239 bool use_anchor,
240 float scale,
241 base::TimeDelta duration);
243 void ApplyScrollAndScale(ScrollAndScaleSet* info);
244 void SetImplTransform(const gfx::Transform& transform);
246 // Virtual for tests.
247 virtual void StartRateLimiter();
248 virtual void StopRateLimiter();
250 void RateLimit();
252 void SetDeviceScaleFactor(float device_scale_factor);
253 float device_scale_factor() const { return device_scale_factor_; }
255 void UpdateTopControlsState(TopControlsState constraints,
256 TopControlsState current,
257 bool animate);
259 HeadsUpDisplayLayer* hud_layer() const { return hud_layer_.get(); }
261 Proxy* proxy() const { return proxy_.get(); }
262 AnimationRegistrar* animation_registrar() const {
263 return animation_registrar_.get();
265 AnimationHost* animation_host() const { return animation_host_.get(); }
267 bool in_paint_layer_contents() const { return in_paint_layer_contents_; }
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();
282 virtual gfx::Size GetUIResourceSize(UIResourceId id) const;
284 bool UsingSharedMemoryResources();
285 int id() const { return id_; }
287 // Returns the id of the benchmark on success, 0 otherwise.
288 int ScheduleMicroBenchmark(const std::string& benchmark_name,
289 scoped_ptr<base::Value> value,
290 const MicroBenchmark::DoneCallback& callback);
291 // Returns true if the message was successfully delivered and handled.
292 bool SendMessageToMicroBenchmark(int id, scoped_ptr<base::Value> value);
294 // When a SwapPromiseMonitor is created on the main thread, it calls
295 // InsertSwapPromiseMonitor() to register itself with LayerTreeHost.
296 // When the monitor is destroyed, it calls RemoveSwapPromiseMonitor()
297 // to unregister itself.
298 void InsertSwapPromiseMonitor(SwapPromiseMonitor* monitor);
299 void RemoveSwapPromiseMonitor(SwapPromiseMonitor* monitor);
301 // Call this function when you expect there to be a swap buffer.
302 // See swap_promise.h for how to use SwapPromise.
303 void QueueSwapPromise(scoped_ptr<SwapPromise> swap_promise);
305 void BreakSwapPromises(SwapPromise::DidNotSwapReason reason);
307 size_t num_queued_swap_promises() const { return swap_promise_list_.size(); }
309 void set_surface_id_namespace(uint32_t id_namespace);
310 SurfaceSequence CreateSurfaceSequence();
312 void SetChildrenNeedBeginFrames(bool children_need_begin_frames) const;
313 void SendBeginFramesToChildren(const BeginFrameArgs& args) const;
315 void SetAuthoritativeVSyncInterval(const base::TimeDelta& interval);
317 PropertyTrees* property_trees() { return &property_trees_; }
318 bool needs_meta_info_recomputation() {
319 return needs_meta_info_recomputation_;
322 void RecordFrameTimingEvents(
323 scoped_ptr<FrameTimingTracker::CompositeTimingSet> composite_events,
324 scoped_ptr<FrameTimingTracker::MainFrameTimingSet> main_frame_events);
326 Layer* LayerById(int id) const;
327 void RegisterLayer(Layer* layer);
328 void UnregisterLayer(Layer* layer);
329 // LayerTreeMutatorsClient implementation.
330 bool IsLayerInTree(int layer_id, LayerTreeType tree_type) const override;
331 void SetMutatorsNeedCommit() override;
332 void SetLayerFilterMutated(int layer_id,
333 LayerTreeType tree_type,
334 const FilterOperations& filters) override;
335 void SetLayerOpacityMutated(int layer_id,
336 LayerTreeType tree_type,
337 float opacity) override;
338 void SetLayerTransformMutated(int layer_id,
339 LayerTreeType tree_type,
340 const gfx::Transform& transform) override;
341 void SetLayerScrollOffsetMutated(
342 int layer_id,
343 LayerTreeType tree_type,
344 const gfx::ScrollOffset& scroll_offset) override;
345 void LayerTransformIsPotentiallyAnimatingChanged(int layer_id,
346 LayerTreeType tree_type,
347 bool is_animating) override;
348 void ScrollOffsetAnimationFinished() override {}
349 gfx::ScrollOffset GetScrollOffsetForAnimation(int layer_id) const override;
351 bool ScrollOffsetAnimationWasInterrupted(const Layer* layer) const;
352 bool IsAnimatingFilterProperty(const Layer* layer) const;
353 bool IsAnimatingOpacityProperty(const Layer* layer) const;
354 bool IsAnimatingTransformProperty(const Layer* layer) const;
355 bool HasPotentiallyRunningFilterAnimation(const Layer* layer) const;
356 bool HasPotentiallyRunningOpacityAnimation(const Layer* layer) const;
357 bool HasPotentiallyRunningTransformAnimation(const Layer* layer) const;
358 bool HasOnlyTranslationTransforms(const Layer* layer) const;
359 bool MaximumTargetScale(const Layer* layer, float* max_scale) const;
360 bool AnimationStartScale(const Layer* layer, float* start_scale) const;
361 bool HasAnyAnimationTargetingProperty(
362 const Layer* layer,
363 Animation::TargetProperty property) const;
364 bool AnimationsPreserveAxisAlignment(const Layer* layer) const;
365 bool HasAnyAnimation(const Layer* layer) const;
366 bool HasActiveAnimation(const Layer* layer) const;
368 protected:
369 explicit LayerTreeHost(InitParams* params);
370 void InitializeThreaded(
371 scoped_refptr<base::SingleThreadTaskRunner> main_task_runner,
372 scoped_refptr<base::SingleThreadTaskRunner> impl_task_runner,
373 scoped_ptr<BeginFrameSource> external_begin_frame_source);
374 void InitializeSingleThreaded(
375 LayerTreeHostSingleThreadClient* single_thread_client,
376 scoped_refptr<base::SingleThreadTaskRunner> main_task_runner,
377 scoped_ptr<BeginFrameSource> external_begin_frame_source);
378 void InitializeForTesting(scoped_ptr<Proxy> proxy_for_testing);
379 void SetOutputSurfaceLostForTesting(bool is_lost) {
380 output_surface_lost_ = is_lost;
383 // shared_bitmap_manager(), gpu_memory_buffer_manager(), and
384 // task_graph_runner() return valid values only until the LayerTreeHostImpl is
385 // created in CreateLayerTreeHostImpl().
386 SharedBitmapManager* shared_bitmap_manager() const {
387 return shared_bitmap_manager_;
389 gpu::GpuMemoryBufferManager* gpu_memory_buffer_manager() const {
390 return gpu_memory_buffer_manager_;
392 TaskGraphRunner* task_graph_runner() const { return task_graph_runner_; }
394 MicroBenchmarkController micro_benchmark_controller_;
396 void OnCommitForSwapPromises();
398 private:
399 void InitializeProxy(scoped_ptr<Proxy> proxy);
401 bool DoUpdateLayers(Layer* root_layer);
402 void UpdateHudLayer();
404 bool AnimateLayersRecursive(Layer* current, base::TimeTicks time);
406 struct UIResourceClientData {
407 UIResourceClient* client;
408 gfx::Size size;
411 typedef base::hash_map<UIResourceId, UIResourceClientData>
412 UIResourceClientMap;
413 UIResourceClientMap ui_resource_client_map_;
414 int next_ui_resource_id_;
416 typedef std::vector<UIResourceRequest> UIResourceRequestQueue;
417 UIResourceRequestQueue ui_resource_request_queue_;
419 void RecordGpuRasterizationHistogram();
420 void CalculateLCDTextMetricsCallback(Layer* layer);
422 void NotifySwapPromiseMonitorsOfSetNeedsCommit();
424 void SetPropertyTreesNeedRebuild();
426 bool inside_begin_main_frame_;
427 bool needs_full_tree_sync_;
428 bool needs_meta_info_recomputation_;
430 LayerTreeHostClient* client_;
431 scoped_ptr<Proxy> proxy_;
433 int source_frame_number_;
434 int meta_information_sequence_number_;
435 scoped_ptr<RenderingStatsInstrumentation> rendering_stats_instrumentation_;
437 // |current_output_surface_| can't be updated until we've successfully
438 // initialized a new output surface. |new_output_surface_| contains the
439 // new output surface that is currently being initialized. If initialization
440 // is successful then |new_output_surface_| replaces
441 // |current_output_surface_|.
442 scoped_ptr<OutputSurface> new_output_surface_;
443 scoped_ptr<OutputSurface> current_output_surface_;
444 bool output_surface_lost_;
446 scoped_refptr<Layer> root_layer_;
447 scoped_refptr<HeadsUpDisplayLayer> hud_layer_;
449 base::WeakPtr<InputHandler> input_handler_weak_ptr_;
450 base::WeakPtr<TopControlsManager> top_controls_manager_weak_ptr_;
452 const LayerTreeSettings settings_;
453 LayerTreeDebugState debug_state_;
455 gfx::Size device_viewport_size_;
456 bool top_controls_shrink_blink_size_;
457 float top_controls_height_;
458 float top_controls_shown_ratio_;
459 bool hide_pinch_scrollbars_near_min_scale_;
460 float device_scale_factor_;
462 bool visible_;
464 base::OneShotTimer<LayerTreeHost> rate_limit_timer_;
466 float page_scale_factor_;
467 float min_page_scale_factor_;
468 float max_page_scale_factor_;
469 gfx::Vector2dF elastic_overscroll_;
470 bool has_gpu_rasterization_trigger_;
471 bool content_is_suitable_for_gpu_rasterization_;
472 bool gpu_rasterization_histogram_recorded_;
474 SkColor background_color_;
475 bool has_transparent_background_;
477 scoped_ptr<AnimationRegistrar> animation_registrar_;
478 scoped_ptr<AnimationHost> animation_host_;
480 scoped_ptr<PendingPageScaleAnimation> pending_page_scale_animation_;
482 // If set, then page scale animation has completed, but the client hasn't been
483 // notified about it yet.
484 bool did_complete_scale_animation_;
486 bool in_paint_layer_contents_;
488 int id_;
489 bool next_commit_forces_redraw_;
491 scoped_refptr<Layer> overscroll_elasticity_layer_;
492 scoped_refptr<Layer> page_scale_layer_;
493 scoped_refptr<Layer> inner_viewport_scroll_layer_;
494 scoped_refptr<Layer> outer_viewport_scroll_layer_;
496 LayerSelection selection_;
498 SharedBitmapManager* shared_bitmap_manager_;
499 gpu::GpuMemoryBufferManager* gpu_memory_buffer_manager_;
500 TaskGraphRunner* task_graph_runner_;
502 ScopedPtrVector<SwapPromise> swap_promise_list_;
503 std::set<SwapPromiseMonitor*> swap_promise_monitor_;
505 PropertyTrees property_trees_;
507 typedef base::hash_map<int, Layer*> LayerIdMap;
508 LayerIdMap layer_id_map_;
510 uint32_t surface_id_namespace_;
511 uint32_t next_surface_sequence_;
513 DISALLOW_COPY_AND_ASSIGN(LayerTreeHost);
516 } // namespace cc
518 #endif // CC_TREES_LAYER_TREE_HOST_H_