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