IndexedDB: fsync after transactions.
[chromium-blink-merge.git] / cc / trees / layer_tree_host.h
blob867bb197caf29fcea3537656c958fc85f615ad14
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 <list>
10 #include <set>
11 #include <string>
12 #include <vector>
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"
44 namespace cc {
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;
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);
73 RendererCapabilities();
74 ~RendererCapabilities();
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;
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);
93 static scoped_ptr<LayerTreeHost> CreateSingleThreaded(
94 LayerTreeHostClient* client,
95 LayerTreeHostSingleThreadClient* single_thread_client,
96 SharedBitmapManager* manager,
97 const LayerTreeSettings& settings);
98 virtual ~LayerTreeHost();
100 void SetLayerTreeHostClientReady();
102 void set_needs_filter_context() { needs_filter_context_ = true; }
103 bool needs_offscreen_context() const {
104 return needs_filter_context_;
107 // LayerTreeHost interface to Proxy.
108 void WillBeginMainFrame() {
109 client_->WillBeginMainFrame(source_frame_number_);
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,
130 virtual CreateResult OnCreateAndInitializeOutputSurfaceAttempted(
131 bool success);
132 void DidCommitAndDrawFrame() { client_->DidCommitAndDrawFrame(); }
133 void DidCompleteSwapBuffers() { client_->DidCompleteSwapBuffers(); }
134 void DeleteContentsTexturesOnImplThread(ResourceProvider* resource_provider);
135 virtual void AcquireLayerTextures();
136 // Returns false if we should abort this frame due to initialization failure.
137 bool InitializeOutputSurfaceIfNeeded();
138 bool UpdateLayers(ResourceUpdateQueue* queue);
140 LayerTreeHostClient* client() { return client_; }
141 const base::WeakPtr<InputHandler>& GetInputHandler() {
142 return input_handler_weak_ptr_;
145 void NotifyInputThrottledUntilCommit();
147 void Composite(base::TimeTicks frame_begin_time);
149 // Composites and attempts to read back the result into the provided
150 // buffer. If it wasn't possible, e.g. due to context lost, will return
151 // false.
152 bool CompositeAndReadback(void* pixels,
153 const gfx::Rect& rect_in_device_viewport);
155 void FinishAllRendering();
157 void SetDeferCommits(bool defer_commits);
159 // Test only hook
160 virtual void DidDeferCommit();
162 int source_frame_number() const { return source_frame_number_; }
164 void SetNeedsDisplayOnAllLayers();
166 void CollectRenderingStats(RenderingStats* stats) const;
168 RenderingStatsInstrumentation* rendering_stats_instrumentation() const {
169 return rendering_stats_instrumentation_.get();
172 const RendererCapabilities& GetRendererCapabilities() const;
174 void SetNeedsAnimate();
175 virtual void SetNeedsUpdateLayers();
176 virtual void SetNeedsCommit();
177 virtual void SetNeedsFullTreeSync();
178 void SetNeedsRedraw();
179 void SetNeedsRedrawRect(const gfx::Rect& damage_rect);
180 bool CommitRequested() const;
181 bool BeginMainFrameRequested() const;
183 void SetNextCommitWaitsForActivation();
185 void SetNextCommitForcesRedraw();
187 void SetAnimationEvents(scoped_ptr<AnimationEventsVector> events,
188 base::Time wall_clock_time);
190 void SetRootLayer(scoped_refptr<Layer> root_layer);
191 Layer* root_layer() { return root_layer_.get(); }
192 const Layer* root_layer() const { return root_layer_.get(); }
193 const Layer* page_scale_layer() const { return page_scale_layer_.get(); }
194 void RegisterViewportLayers(
195 scoped_refptr<Layer> page_scale_layer,
196 scoped_refptr<Layer> inner_viewport_scroll_layer,
197 scoped_refptr<Layer> outer_viewport_scroll_layer);
199 const LayerTreeSettings& settings() const { return settings_; }
201 void SetDebugState(const LayerTreeDebugState& debug_state);
202 const LayerTreeDebugState& debug_state() const { return debug_state_; }
204 void SetViewportSize(gfx::Size device_viewport_size);
205 void SetOverdrawBottomHeight(float overdraw_bottom_height);
207 gfx::Size device_viewport_size() const { return device_viewport_size_; }
208 float overdraw_bottom_height() const { return overdraw_bottom_height_; }
210 void ApplyPageScaleDeltaFromImplSide(float page_scale_delta);
211 void SetPageScaleFactorAndLimits(float page_scale_factor,
212 float min_page_scale_factor,
213 float max_page_scale_factor);
214 float page_scale_factor() const { return page_scale_factor_; }
216 SkColor background_color() const { return background_color_; }
217 void set_background_color(SkColor color) { background_color_ = color; }
219 void set_has_transparent_background(bool transparent) {
220 has_transparent_background_ = transparent;
223 void SetOverhangBitmap(const SkBitmap& bitmap);
225 PrioritizedResourceManager* contents_texture_manager() const {
226 return contents_texture_manager_.get();
229 void SetVisible(bool visible);
230 bool visible() const { return visible_; }
232 void StartPageScaleAnimation(gfx::Vector2d target_offset,
233 bool use_anchor,
234 float scale,
235 base::TimeDelta duration);
237 void ApplyScrollAndScale(const ScrollAndScaleSet& info);
239 void SetImplTransform(const gfx::Transform& transform);
241 // Virtual for tests.
242 virtual void StartRateLimiter();
243 virtual void StopRateLimiter();
245 void RateLimit();
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,
256 bool animate);
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 scoped_ptr<base::Value> AsValue() 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 bool ScheduleMicroBenchmark(const std::string& benchmark_name,
290 scoped_ptr<base::Value> value,
291 const MicroBenchmark::DoneCallback& callback);
293 // When a SwapPromiseMonitor is created on the main thread, it calls
294 // InsertSwapPromiseMonitor() to register itself with LayerTreeHost.
295 // When the monitor is destroyed, it calls RemoveSwapPromiseMonitor()
296 // to unregister itself.
297 void InsertSwapPromiseMonitor(SwapPromiseMonitor* monitor);
298 void RemoveSwapPromiseMonitor(SwapPromiseMonitor* monitor);
300 // Call this function when you expect there to be a swap buffer.
301 // See swap_promise.h for how to use SwapPromise.
302 void QueueSwapPromise(scoped_ptr<SwapPromise> swap_promise);
304 void BreakSwapPromises(SwapPromise::DidNotSwapReason reason);
306 protected:
307 LayerTreeHost(LayerTreeHostClient* client,
308 SharedBitmapManager* manager,
309 const LayerTreeSettings& settings);
310 void InitializeThreaded(
311 scoped_refptr<base::SingleThreadTaskRunner> impl_task_runner);
312 void InitializeSingleThreaded(
313 LayerTreeHostSingleThreadClient* single_thread_client);
314 void InitializeForTesting(scoped_ptr<Proxy> proxy_for_testing);
315 void SetOutputSurfaceLostForTesting(bool is_lost) {
316 output_surface_lost_ = is_lost;
319 MicroBenchmarkController micro_benchmark_controller_;
321 private:
322 void InitializeProxy(scoped_ptr<Proxy> proxy);
324 void PaintLayerContents(
325 const RenderSurfaceLayerList& render_surface_layer_list,
326 ResourceUpdateQueue* queue,
327 bool* did_paint_content,
328 bool* need_more_updates);
329 void PaintMasksForRenderSurface(Layer* render_surface_layer,
330 ResourceUpdateQueue* queue,
331 bool* did_paint_content,
332 bool* need_more_updates);
333 bool UpdateLayers(Layer* root_layer, ResourceUpdateQueue* queue);
334 void UpdateHudLayer();
335 void TriggerPrepaint();
337 void ReduceMemoryUsage();
339 void PrioritizeTextures(
340 const RenderSurfaceLayerList& render_surface_layer_list,
341 OverdrawMetrics* metrics);
342 void SetPrioritiesForSurfaces(size_t surface_memory_bytes);
343 void SetPrioritiesForLayers(const RenderSurfaceLayerList& update_list);
344 size_t CalculateMemoryForRenderSurfaces(
345 const RenderSurfaceLayerList& update_list);
347 bool AnimateLayersRecursive(Layer* current, base::TimeTicks time);
349 struct UIResourceClientData {
350 UIResourceClient* client;
351 gfx::Size size;
354 typedef base::hash_map<UIResourceId, UIResourceClientData>
355 UIResourceClientMap;
356 UIResourceClientMap ui_resource_client_map_;
357 int next_ui_resource_id_;
359 typedef std::list<UIResourceRequest> UIResourceRequestQueue;
360 UIResourceRequestQueue ui_resource_request_queue_;
362 void CalculateLCDTextMetricsCallback(Layer* layer);
364 void NotifySwapPromiseMonitorsOfSetNeedsCommit();
366 bool animating_;
367 bool needs_full_tree_sync_;
368 bool needs_filter_context_;
370 base::CancelableClosure prepaint_callback_;
372 LayerTreeHostClient* client_;
373 scoped_ptr<Proxy> proxy_;
375 int source_frame_number_;
376 scoped_ptr<RenderingStatsInstrumentation> rendering_stats_instrumentation_;
378 bool output_surface_can_be_initialized_;
379 bool output_surface_lost_;
380 int num_failed_recreate_attempts_;
382 scoped_refptr<Layer> root_layer_;
383 scoped_refptr<HeadsUpDisplayLayer> hud_layer_;
385 scoped_ptr<PrioritizedResourceManager> contents_texture_manager_;
386 scoped_ptr<PrioritizedResource> surface_memory_placeholder_;
388 base::WeakPtr<InputHandler> input_handler_weak_ptr_;
389 base::WeakPtr<TopControlsManager> top_controls_manager_weak_ptr_;
391 const LayerTreeSettings settings_;
392 LayerTreeDebugState debug_state_;
394 gfx::Size device_viewport_size_;
395 float overdraw_bottom_height_;
396 float device_scale_factor_;
398 bool visible_;
400 base::OneShotTimer<LayerTreeHost> rate_limit_timer_;
402 float page_scale_factor_;
403 float min_page_scale_factor_;
404 float max_page_scale_factor_;
405 gfx::Transform impl_transform_;
406 bool trigger_idle_updates_;
408 SkColor background_color_;
409 bool has_transparent_background_;
411 // If set, this texture is used to fill in the parts of the screen not
412 // covered by layers.
413 scoped_ptr<ScopedUIResource> overhang_ui_resource_;
415 typedef ScopedPtrVector<PrioritizedResource> TextureList;
416 size_t partial_texture_update_requests_;
418 scoped_ptr<AnimationRegistrar> animation_registrar_;
420 struct PendingPageScaleAnimation {
421 gfx::Vector2d target_offset;
422 bool use_anchor;
423 float scale;
424 base::TimeDelta duration;
426 scoped_ptr<PendingPageScaleAnimation> pending_page_scale_animation_;
428 bool in_paint_layer_contents_;
430 static const int kTotalFramesToUseForLCDTextMetrics = 50;
431 int total_frames_used_for_lcd_text_metrics_;
433 struct LCDTextMetrics {
434 LCDTextMetrics()
435 : total_num_cc_layers(0),
436 total_num_cc_layers_can_use_lcd_text(0),
437 total_num_cc_layers_will_use_lcd_text(0) {}
439 int64 total_num_cc_layers;
440 int64 total_num_cc_layers_can_use_lcd_text;
441 int64 total_num_cc_layers_will_use_lcd_text;
443 LCDTextMetrics lcd_text_metrics_;
444 int id_;
445 bool next_commit_forces_redraw_;
447 scoped_refptr<Layer> page_scale_layer_;
448 scoped_refptr<Layer> inner_viewport_scroll_layer_;
449 scoped_refptr<Layer> outer_viewport_scroll_layer_;
451 SharedBitmapManager* shared_bitmap_manager_;
453 ScopedPtrVector<SwapPromise> swap_promise_list_;
454 std::set<SwapPromiseMonitor*> swap_promise_monitor_;
456 DISALLOW_COPY_AND_ASSIGN(LayerTreeHost);
459 } // namespace cc
461 #endif // CC_TREES_LAYER_TREE_HOST_H_