Update To 11.40.268.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/layer_selection_bound.h"
31 #include "cc/input/scrollbar.h"
32 #include "cc/input/top_controls_state.h"
33 #include "cc/layers/layer_lists.h"
34 #include "cc/output/output_surface.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/proxy.h"
42 #include "third_party/skia/include/core/SkColor.h"
43 #include "ui/gfx/geometry/rect.h"
44
45 namespace gpu {
46 class GpuMemoryBufferManager;
47 }
48
49 namespace cc {
50 class AnimationRegistrar;
51 class HeadsUpDisplayLayer;
52 class Layer;
53 class LayerTreeHostImpl;
54 class LayerTreeHostImplClient;
55 class LayerTreeHostSingleThreadClient;
56 class PrioritizedResource;
57 class PrioritizedResourceManager;
58 class Region;
59 class RenderingStatsInstrumentation;
60 class ResourceProvider;
61 class ResourceUpdateQueue;
62 class SharedBitmapManager;
63 class TopControlsManager;
64 class UIResourceRequest;
65 struct RenderingStats;
66 struct ScrollAndScaleSet;
67
68 // Provides information on an Impl's rendering capabilities back to the
69 // LayerTreeHost.
70 struct CC_EXPORT RendererCapabilities {
71   RendererCapabilities(ResourceFormat best_texture_format,
72                        bool allow_partial_texture_updates,
73                        int max_texture_size,
74                        bool using_shared_memory_resources);
75
76   RendererCapabilities();
77   ~RendererCapabilities();
78
79   // Duplicate any modification to this list to RendererCapabilitiesImpl.
80   ResourceFormat best_texture_format;
81   bool allow_partial_texture_updates;
82   int max_texture_size;
83   bool using_shared_memory_resources;
84 };
85
86 class CC_EXPORT LayerTreeHost {
87  public:
88   // The SharedBitmapManager will be used on the compositor thread.
89   static scoped_ptr<LayerTreeHost> CreateThreaded(
90       LayerTreeHostClient* client,
91       SharedBitmapManager* shared_bitmap_manager,
92       gpu::GpuMemoryBufferManager* gpu_memory_buffer_manager,
93       const LayerTreeSettings& settings,
94       scoped_refptr<base::SingleThreadTaskRunner> main_task_runner,
95       scoped_refptr<base::SingleThreadTaskRunner> impl_task_runner);
96
97   static scoped_ptr<LayerTreeHost> CreateSingleThreaded(
98       LayerTreeHostClient* client,
99       LayerTreeHostSingleThreadClient* single_thread_client,
100       SharedBitmapManager* shared_bitmap_manager,
101       gpu::GpuMemoryBufferManager* gpu_memory_buffer_manager,
102       const LayerTreeSettings& settings,
103       scoped_refptr<base::SingleThreadTaskRunner> main_task_runner);
104   virtual ~LayerTreeHost();
105
106   void SetLayerTreeHostClientReady();
107
108   // LayerTreeHost interface to Proxy.
109   void WillBeginMainFrame() {
110     client_->WillBeginMainFrame(source_frame_number_);
111   }
112   void DidBeginMainFrame();
113   void BeginMainFrame(const BeginFrameArgs& args);
114   void AnimateLayers(base::TimeTicks monotonic_frame_begin_time);
115   void DidStopFlinging();
116   void Layout();
117   void BeginCommitOnImplThread(LayerTreeHostImpl* host_impl);
118   void FinishCommitOnImplThread(LayerTreeHostImpl* host_impl);
119   void WillCommit();
120   void CommitComplete();
121   void SetOutputSurface(scoped_ptr<OutputSurface> output_surface);
122   void RequestNewOutputSurface();
123   virtual scoped_ptr<LayerTreeHostImpl> CreateLayerTreeHostImpl(
124       LayerTreeHostImplClient* client);
125   void DidLoseOutputSurface();
126   bool output_surface_lost() const { return output_surface_lost_; }
127   virtual void OnCreateAndInitializeOutputSurfaceAttempted(bool success);
128   void DidCommitAndDrawFrame() { client_->DidCommitAndDrawFrame(); }
129   void DidCompleteSwapBuffers() { client_->DidCompleteSwapBuffers(); }
130   void DeleteContentsTexturesOnImplThread(ResourceProvider* resource_provider);
131   bool UpdateLayers(ResourceUpdateQueue* queue);
132
133   LayerTreeHostClient* client() { return client_; }
134   const base::WeakPtr<InputHandler>& GetInputHandler() {
135     return input_handler_weak_ptr_;
136   }
137
138   void NotifyInputThrottledUntilCommit();
139
140   void Composite(base::TimeTicks frame_begin_time);
141
142   void FinishAllRendering();
143
144   void SetDeferCommits(bool defer_commits);
145
146   // Test only hook
147   virtual void DidDeferCommit();
148
149   int source_frame_number() const { return source_frame_number_; }
150
151   void SetNeedsDisplayOnAllLayers();
152
153   void CollectRenderingStats(RenderingStats* stats) const;
154
155   RenderingStatsInstrumentation* rendering_stats_instrumentation() const {
156     return rendering_stats_instrumentation_.get();
157   }
158
159   const RendererCapabilities& GetRendererCapabilities() const;
160
161   void SetNeedsAnimate();
162   virtual void SetNeedsUpdateLayers();
163   virtual void SetNeedsCommit();
164   virtual void SetNeedsFullTreeSync();
165   void SetNeedsRedraw();
166   void SetNeedsRedrawRect(const gfx::Rect& damage_rect);
167   bool CommitRequested() const;
168   bool BeginMainFrameRequested() const;
169
170   void SetNextCommitWaitsForActivation();
171
172   void SetNextCommitForcesRedraw();
173
174   void SetAnimationEvents(scoped_ptr<AnimationEventsVector> events);
175
176   void SetRootLayer(scoped_refptr<Layer> root_layer);
177   Layer* root_layer() { return root_layer_.get(); }
178   const Layer* root_layer() const { return root_layer_.get(); }
179   const Layer* page_scale_layer() const { return page_scale_layer_.get(); }
180   void RegisterViewportLayers(
181       scoped_refptr<Layer> page_scale_layer,
182       scoped_refptr<Layer> inner_viewport_scroll_layer,
183       scoped_refptr<Layer> outer_viewport_scroll_layer);
184   Layer* inner_viewport_scroll_layer() const {
185     return inner_viewport_scroll_layer_.get();
186   }
187   Layer* outer_viewport_scroll_layer() const {
188     return outer_viewport_scroll_layer_.get();
189   }
190
191   void RegisterSelection(const LayerSelectionBound& start,
192                          const LayerSelectionBound& end);
193
194   const LayerTreeSettings& settings() const { return settings_; }
195
196   void SetDebugState(const LayerTreeDebugState& debug_state);
197   const LayerTreeDebugState& debug_state() const { return debug_state_; }
198
199   bool has_gpu_rasterization_trigger() const {
200     return has_gpu_rasterization_trigger_;
201   }
202   void SetHasGpuRasterizationTrigger(bool has_trigger);
203   bool UseGpuRasterization() const;
204
205   void SetViewportSize(const gfx::Size& device_viewport_size);
206   void SetTopControlsLayoutHeight(float height);
207   void SetTopControlsContentOffset(float offset);
208
209   gfx::Size device_viewport_size() const { return device_viewport_size_; }
210
211   void ApplyPageScaleDeltaFromImplSide(float page_scale_delta);
212   void SetPageScaleFactorAndLimits(float page_scale_factor,
213                                    float min_page_scale_factor,
214                                    float max_page_scale_factor);
215   float page_scale_factor() const { return page_scale_factor_; }
216
217   SkColor background_color() const { return background_color_; }
218   void set_background_color(SkColor color) { background_color_ = color; }
219
220   void set_has_transparent_background(bool transparent) {
221     has_transparent_background_ = transparent;
222   }
223
224   void SetOverhangBitmap(const SkBitmap& bitmap);
225
226   PrioritizedResourceManager* contents_texture_manager() const {
227     return contents_texture_manager_.get();
228   }
229
230   void SetVisible(bool visible);
231   bool visible() const { return visible_; }
232
233   void StartPageScaleAnimation(const gfx::Vector2d& target_offset,
234                                bool use_anchor,
235                                float scale,
236                                base::TimeDelta duration);
237
238   void ApplyScrollAndScale(ScrollAndScaleSet* info);
239   void SetImplTransform(const gfx::Transform& transform);
240
241   // Virtual for tests.
242   virtual void StartRateLimiter();
243   virtual void StopRateLimiter();
244
245   void RateLimit();
246
247   bool AlwaysUsePartialTextureUpdates();
248   size_t MaxPartialTextureUpdates() const;
249   bool RequestPartialTextureUpdate();
250
251   void SetDeviceScaleFactor(float device_scale_factor);
252   float device_scale_factor() const { return device_scale_factor_; }
253
254   void UpdateTopControlsState(TopControlsState constraints,
255                               TopControlsState current,
256                               bool animate);
257
258   HeadsUpDisplayLayer* hud_layer() const { return hud_layer_.get(); }
259
260   Proxy* proxy() const { return proxy_.get(); }
261
262   AnimationRegistrar* animation_registrar() const {
263     return animation_registrar_.get();
264   }
265
266   // Obtains a thorough dump of the LayerTreeHost as a value.
267   void AsValueInto(base::debug::TracedValue* value) const;
268
269   bool in_paint_layer_contents() const { return in_paint_layer_contents_; }
270
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();
283
284   virtual gfx::Size GetUIResourceSize(UIResourceId id) const;
285
286   bool UsingSharedMemoryResources();
287   int id() const { return id_; }
288
289   // Returns the id of the benchmark on success, 0 otherwise.
290   int ScheduleMicroBenchmark(const std::string& benchmark_name,
291                              scoped_ptr<base::Value> value,
292                              const MicroBenchmark::DoneCallback& callback);
293   // Returns true if the message was successfully delivered and handled.
294   bool SendMessageToMicroBenchmark(int id, scoped_ptr<base::Value> value);
295
296   // When a SwapPromiseMonitor is created on the main thread, it calls
297   // InsertSwapPromiseMonitor() to register itself with LayerTreeHost.
298   // When the monitor is destroyed, it calls RemoveSwapPromiseMonitor()
299   // to unregister itself.
300   void InsertSwapPromiseMonitor(SwapPromiseMonitor* monitor);
301   void RemoveSwapPromiseMonitor(SwapPromiseMonitor* monitor);
302
303   // Call this function when you expect there to be a swap buffer.
304   // See swap_promise.h for how to use SwapPromise.
305   void QueueSwapPromise(scoped_ptr<SwapPromise> swap_promise);
306
307   void BreakSwapPromises(SwapPromise::DidNotSwapReason reason);
308
309   size_t num_queued_swap_promises() const { return swap_promise_list_.size(); }
310
311   void set_surface_id_namespace(uint32_t id_namespace);
312   SurfaceSequence CreateSurfaceSequence();
313
314  protected:
315   LayerTreeHost(LayerTreeHostClient* client,
316                 SharedBitmapManager* shared_bitmap_manager,
317                 gpu::GpuMemoryBufferManager* gpu_memory_buffer_manager,
318                 const LayerTreeSettings& settings);
319   void InitializeThreaded(
320       scoped_refptr<base::SingleThreadTaskRunner> main_task_runner,
321       scoped_refptr<base::SingleThreadTaskRunner> impl_task_runner);
322   void InitializeSingleThreaded(
323       LayerTreeHostSingleThreadClient* single_thread_client,
324       scoped_refptr<base::SingleThreadTaskRunner> main_task_runner);
325   void InitializeForTesting(scoped_ptr<Proxy> proxy_for_testing);
326   void SetOutputSurfaceLostForTesting(bool is_lost) {
327     output_surface_lost_ = is_lost;
328   }
329
330   MicroBenchmarkController micro_benchmark_controller_;
331
332  private:
333   void InitializeProxy(scoped_ptr<Proxy> proxy);
334
335   void PaintLayerContents(
336       const RenderSurfaceLayerList& render_surface_layer_list,
337       ResourceUpdateQueue* queue,
338       bool* did_paint_content,
339       bool* need_more_updates);
340   void PaintMasksForRenderSurface(Layer* render_surface_layer,
341                                   ResourceUpdateQueue* queue,
342                                   bool* did_paint_content,
343                                   bool* need_more_updates);
344   bool UpdateLayers(Layer* root_layer, ResourceUpdateQueue* queue);
345   void UpdateHudLayer();
346   void TriggerPrepaint();
347
348   void ReduceMemoryUsage();
349
350   void PrioritizeTextures(
351       const RenderSurfaceLayerList& render_surface_layer_list);
352   void SetPrioritiesForSurfaces(size_t surface_memory_bytes);
353   void SetPrioritiesForLayers(const RenderSurfaceLayerList& update_list);
354   size_t CalculateMemoryForRenderSurfaces(
355       const RenderSurfaceLayerList& update_list);
356
357   bool AnimateLayersRecursive(Layer* current, base::TimeTicks time);
358
359   struct UIResourceClientData {
360     UIResourceClient* client;
361     gfx::Size size;
362   };
363
364   typedef base::hash_map<UIResourceId, UIResourceClientData>
365       UIResourceClientMap;
366   UIResourceClientMap ui_resource_client_map_;
367   int next_ui_resource_id_;
368
369   typedef std::list<UIResourceRequest> UIResourceRequestQueue;
370   UIResourceRequestQueue ui_resource_request_queue_;
371
372   void RecordGpuRasterizationHistogram();
373   void CalculateLCDTextMetricsCallback(Layer* layer);
374
375   void NotifySwapPromiseMonitorsOfSetNeedsCommit();
376
377   bool inside_begin_main_frame_;
378   bool needs_full_tree_sync_;
379
380   base::CancelableClosure prepaint_callback_;
381
382   LayerTreeHostClient* client_;
383   scoped_ptr<Proxy> proxy_;
384
385   int source_frame_number_;
386   scoped_ptr<RenderingStatsInstrumentation> rendering_stats_instrumentation_;
387
388   bool output_surface_lost_;
389   int num_failed_recreate_attempts_;
390
391   scoped_refptr<Layer> root_layer_;
392   scoped_refptr<HeadsUpDisplayLayer> hud_layer_;
393
394   scoped_ptr<PrioritizedResourceManager> contents_texture_manager_;
395   scoped_ptr<PrioritizedResource> surface_memory_placeholder_;
396
397   base::WeakPtr<InputHandler> input_handler_weak_ptr_;
398   base::WeakPtr<TopControlsManager> top_controls_manager_weak_ptr_;
399
400   const LayerTreeSettings settings_;
401   LayerTreeDebugState debug_state_;
402
403   gfx::Size device_viewport_size_;
404   float top_controls_layout_height_;
405   float top_controls_content_offset_;
406   float device_scale_factor_;
407
408   bool visible_;
409
410   base::OneShotTimer<LayerTreeHost> rate_limit_timer_;
411
412   float page_scale_factor_;
413   float min_page_scale_factor_;
414   float max_page_scale_factor_;
415   bool has_gpu_rasterization_trigger_;
416   bool content_is_suitable_for_gpu_rasterization_;
417   bool gpu_rasterization_histogram_recorded_;
418
419   SkColor background_color_;
420   bool has_transparent_background_;
421
422   // If set, this texture is used to fill in the parts of the screen not
423   // covered by layers.
424   scoped_ptr<ScopedUIResource> overhang_ui_resource_;
425
426   typedef ScopedPtrVector<PrioritizedResource> TextureList;
427   size_t partial_texture_update_requests_;
428
429   scoped_ptr<AnimationRegistrar> animation_registrar_;
430
431   struct PendingPageScaleAnimation {
432     gfx::Vector2d target_offset;
433     bool use_anchor;
434     float scale;
435     base::TimeDelta duration;
436   };
437   scoped_ptr<PendingPageScaleAnimation> pending_page_scale_animation_;
438
439   bool in_paint_layer_contents_;
440
441   static const int kTotalFramesToUseForLCDTextMetrics = 50;
442   int total_frames_used_for_lcd_text_metrics_;
443
444   struct LCDTextMetrics {
445     LCDTextMetrics()
446         : total_num_cc_layers(0),
447           total_num_cc_layers_can_use_lcd_text(0),
448           total_num_cc_layers_will_use_lcd_text(0) {}
449
450     int64 total_num_cc_layers;
451     int64 total_num_cc_layers_can_use_lcd_text;
452     int64 total_num_cc_layers_will_use_lcd_text;
453   };
454   LCDTextMetrics lcd_text_metrics_;
455   int id_;
456   bool next_commit_forces_redraw_;
457
458   scoped_refptr<Layer> page_scale_layer_;
459   scoped_refptr<Layer> inner_viewport_scroll_layer_;
460   scoped_refptr<Layer> outer_viewport_scroll_layer_;
461
462   LayerSelectionBound selection_start_;
463   LayerSelectionBound selection_end_;
464
465   SharedBitmapManager* shared_bitmap_manager_;
466   gpu::GpuMemoryBufferManager* gpu_memory_buffer_manager_;
467
468   ScopedPtrVector<SwapPromise> swap_promise_list_;
469   std::set<SwapPromiseMonitor*> swap_promise_monitor_;
470
471   uint32_t surface_id_namespace_;
472   uint32_t next_surface_sequence_;
473
474   DISALLOW_COPY_AND_ASSIGN(LayerTreeHost);
475 };
476
477 }  // namespace cc
478
479 #endif  // CC_TREES_LAYER_TREE_HOST_H_