- add sources.
[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 <string>
11 #include <vector>
12
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 "cc/animation/animation_events.h"
21 #include "cc/base/cc_export.h"
22 #include "cc/base/scoped_ptr_vector.h"
23 #include "cc/debug/micro_benchmark.h"
24 #include "cc/debug/micro_benchmark_controller.h"
25 #include "cc/input/input_handler.h"
26 #include "cc/input/scrollbar.h"
27 #include "cc/input/top_controls_state.h"
28 #include "cc/layers/layer_lists.h"
29 #include "cc/output/output_surface.h"
30 #include "cc/resources/resource_format.h"
31 #include "cc/resources/scoped_ui_resource.h"
32 #include "cc/resources/ui_resource_bitmap.h"
33 #include "cc/resources/ui_resource_client.h"
34 #include "cc/scheduler/rate_limiter.h"
35 #include "cc/trees/layer_tree_host_client.h"
36 #include "cc/trees/layer_tree_host_common.h"
37 #include "cc/trees/layer_tree_settings.h"
38 #include "cc/trees/occlusion_tracker.h"
39 #include "cc/trees/proxy.h"
40 #include "third_party/skia/include/core/SkColor.h"
41 #include "ui/events/latency_info.h"
42 #include "ui/gfx/rect.h"
43
44 namespace WebKit { class WebGraphicsContext3D; }
45
46 #if defined(COMPILER_GCC)
47 namespace BASE_HASH_NAMESPACE {
48 template <>
49 struct hash<WebKit::WebGraphicsContext3D*> {
50   size_t operator()(WebKit::WebGraphicsContext3D* ptr) const {
51     return hash<size_t>()(reinterpret_cast<size_t>(ptr));
52   }
53 };
54 }  // namespace BASE_HASH_NAMESPACE
55 #endif  // COMPILER
56
57 namespace cc {
58
59 class AnimationRegistrar;
60 class HeadsUpDisplayLayer;
61 class Layer;
62 class LayerTreeHostImpl;
63 class LayerTreeHostImplClient;
64 class PrioritizedResourceManager;
65 class PrioritizedResource;
66 class Region;
67 class RenderingStatsInstrumentation;
68 class ResourceProvider;
69 class ResourceUpdateQueue;
70 class SharedBitmapManager;
71 class TopControlsManager;
72 struct RenderingStats;
73 struct ScrollAndScaleSet;
74
75 // Provides information on an Impl's rendering capabilities back to the
76 // LayerTreeHost.
77 struct CC_EXPORT RendererCapabilities {
78   RendererCapabilities();
79   ~RendererCapabilities();
80
81   ResourceFormat best_texture_format;
82   bool using_partial_swap;
83   bool using_set_visibility;
84   bool using_egl_image;
85   bool allow_partial_texture_updates;
86   bool using_offscreen_context3d;
87   int max_texture_size;
88   bool avoid_pow2_textures;
89   bool using_map_image;
90   bool using_shared_memory_resources;
91   bool using_discard_framebuffer;
92 };
93
94 class CC_EXPORT UIResourceRequest {
95  public:
96   enum UIResourceRequestType {
97     UIResourceCreate,
98     UIResourceDelete,
99     UIResourceInvalidRequest
100   };
101
102   UIResourceRequest(UIResourceRequestType type, UIResourceId id);
103   UIResourceRequest(UIResourceRequestType type,
104                     UIResourceId id,
105                     const UIResourceBitmap& bitmap);
106   UIResourceRequest(const UIResourceRequest& request);
107
108   ~UIResourceRequest();
109
110   UIResourceRequestType GetType() const { return type_; }
111   UIResourceId GetId() const { return id_; }
112   UIResourceBitmap GetBitmap() const {
113     DCHECK(bitmap_);
114     return *bitmap_.get();
115   }
116
117   UIResourceRequest& operator=(const UIResourceRequest& request);
118
119  private:
120   UIResourceRequestType type_;
121   UIResourceId id_;
122   scoped_ptr<UIResourceBitmap> bitmap_;
123 };
124
125 class CC_EXPORT LayerTreeHost : NON_EXPORTED_BASE(public RateLimiterClient) {
126  public:
127   // The SharedBitmapManager will be used on the compositor thread.
128   static scoped_ptr<LayerTreeHost> Create(
129       LayerTreeHostClient* client,
130       SharedBitmapManager* manager,
131       const LayerTreeSettings& settings,
132       scoped_refptr<base::SingleThreadTaskRunner> impl_task_runner);
133   virtual ~LayerTreeHost();
134
135   void SetLayerTreeHostClientReady();
136
137   // Returns true if any LayerTreeHost is alive.
138   static bool AnyLayerTreeHostInstanceExists();
139
140   void set_needs_filter_context() { needs_filter_context_ = true; }
141   bool needs_offscreen_context() const {
142     return needs_filter_context_;
143   }
144
145   // LayerTreeHost interface to Proxy.
146   void WillBeginMainFrame() { client_->WillBeginMainFrame(); }
147   void DidBeginMainFrame();
148   void UpdateClientAnimations(base::TimeTicks monotonic_frame_begin_time);
149   void AnimateLayers(base::TimeTicks monotonic_frame_begin_time);
150   void DidStopFlinging();
151   void Layout();
152   void BeginCommitOnImplThread(LayerTreeHostImpl* host_impl);
153   void FinishCommitOnImplThread(LayerTreeHostImpl* host_impl);
154   void WillCommit();
155   void CommitComplete();
156   scoped_ptr<OutputSurface> CreateOutputSurface();
157   virtual scoped_ptr<LayerTreeHostImpl> CreateLayerTreeHostImpl(
158       LayerTreeHostImplClient* client);
159   void DidLoseOutputSurface();
160   bool output_surface_lost() const { return output_surface_lost_; }
161   enum CreateResult {
162     CreateSucceeded,
163     CreateFailedButTryAgain,
164     CreateFailedAndGaveUp,
165   };
166   CreateResult OnCreateAndInitializeOutputSurfaceAttempted(bool success);
167   void DidCommitAndDrawFrame() { client_->DidCommitAndDrawFrame(); }
168   void DidCompleteSwapBuffers() { client_->DidCompleteSwapBuffers(); }
169   void DeleteContentsTexturesOnImplThread(ResourceProvider* resource_provider);
170   virtual void AcquireLayerTextures();
171   // Returns false if we should abort this frame due to initialization failure.
172   bool InitializeOutputSurfaceIfNeeded();
173   bool UpdateLayers(ResourceUpdateQueue* queue);
174
175   LayerTreeHostClient* client() { return client_; }
176   const base::WeakPtr<InputHandler>& GetInputHandler() {
177     return input_handler_weak_ptr_;
178   }
179
180   void NotifyInputThrottledUntilCommit();
181
182   void Composite(base::TimeTicks frame_begin_time);
183
184   // Only used when compositing on the main thread.
185   void ScheduleComposite();
186
187   // Composites and attempts to read back the result into the provided
188   // buffer. If it wasn't possible, e.g. due to context lost, will return
189   // false.
190   bool CompositeAndReadback(void* pixels, gfx::Rect rect_in_device_viewport);
191
192   void FinishAllRendering();
193
194   void SetDeferCommits(bool defer_commits);
195
196   // Test only hook
197   virtual void DidDeferCommit();
198
199   int source_frame_number() const { return source_frame_number_; }
200
201   void SetNeedsDisplayOnAllLayers();
202
203   void CollectRenderingStats(RenderingStats* stats) const;
204
205   RenderingStatsInstrumentation* rendering_stats_instrumentation() const {
206     return rendering_stats_instrumentation_.get();
207   }
208
209   const RendererCapabilities& GetRendererCapabilities() const;
210
211   void SetNeedsAnimate();
212   virtual void SetNeedsUpdateLayers();
213   virtual void SetNeedsCommit();
214   virtual void SetNeedsFullTreeSync();
215   void SetNeedsRedraw();
216   void SetNeedsRedrawRect(gfx::Rect damage_rect);
217   bool CommitRequested() const;
218   bool BeginMainFrameRequested() const;
219
220   void SetNextCommitWaitsForActivation();
221
222   void SetNextCommitForcesRedraw();
223
224   void SetAnimationEvents(scoped_ptr<AnimationEventsVector> events,
225                           base::Time wall_clock_time);
226
227   void SetRootLayer(scoped_refptr<Layer> root_layer);
228   Layer* root_layer() { return root_layer_.get(); }
229   const Layer* root_layer() const { return root_layer_.get(); }
230   const Layer* page_scale_layer() const { return page_scale_layer_.get(); }
231   void RegisterViewportLayers(
232       scoped_refptr<Layer> page_scale_layer,
233       scoped_refptr<Layer> inner_viewport_scroll_layer,
234       scoped_refptr<Layer> outer_viewport_scroll_layer);
235
236   const LayerTreeSettings& settings() const { return settings_; }
237
238   void SetDebugState(const LayerTreeDebugState& debug_state);
239   const LayerTreeDebugState& debug_state() const { return debug_state_; }
240
241   void SetViewportSize(gfx::Size device_viewport_size);
242   void SetOverdrawBottomHeight(float overdraw_bottom_height);
243
244   gfx::Size device_viewport_size() const { return device_viewport_size_; }
245   float overdraw_bottom_height() const { return overdraw_bottom_height_; }
246
247   void ApplyPageScaleDeltaFromImplSide(float page_scale_delta);
248   void SetPageScaleFactorAndLimits(float page_scale_factor,
249                                    float min_page_scale_factor,
250                                    float max_page_scale_factor);
251   float page_scale_factor() const { return page_scale_factor_; }
252
253   SkColor background_color() const { return background_color_; }
254   void set_background_color(SkColor color) { background_color_ = color; }
255
256   void set_has_transparent_background(bool transparent) {
257     has_transparent_background_ = transparent;
258   }
259
260   void SetOverhangBitmap(const SkBitmap& bitmap);
261
262   PrioritizedResourceManager* contents_texture_manager() const {
263     return contents_texture_manager_.get();
264   }
265
266   void SetVisible(bool visible);
267   bool visible() const { return visible_; }
268
269   void StartPageScaleAnimation(gfx::Vector2d target_offset,
270                                bool use_anchor,
271                                float scale,
272                                base::TimeDelta duration);
273
274   void ApplyScrollAndScale(const ScrollAndScaleSet& info);
275
276   void SetImplTransform(const gfx::Transform& transform);
277   void SetLatencyInfo(const ui::LatencyInfo& latency_info);
278
279   virtual void StartRateLimiter(WebKit::WebGraphicsContext3D* context3d);
280   virtual void StopRateLimiter(WebKit::WebGraphicsContext3D* context3d);
281
282   // RateLimiterClient implementation.
283   virtual void RateLimit() OVERRIDE;
284
285   bool AlwaysUsePartialTextureUpdates();
286   size_t MaxPartialTextureUpdates() const;
287   bool RequestPartialTextureUpdate();
288
289   void SetDeviceScaleFactor(float device_scale_factor);
290   float device_scale_factor() const { return device_scale_factor_; }
291
292   void UpdateTopControlsState(TopControlsState constraints,
293                               TopControlsState current,
294                               bool animate);
295
296   HeadsUpDisplayLayer* hud_layer() const { return hud_layer_.get(); }
297
298   Proxy* proxy() const { return proxy_.get(); }
299
300   AnimationRegistrar* animation_registrar() const {
301     return animation_registrar_.get();
302   }
303
304   // Obtains a thorough dump of the LayerTreeHost as a value.
305   scoped_ptr<base::Value> AsValue() const;
306
307   bool in_paint_layer_contents() const { return in_paint_layer_contents_; }
308
309   // CreateUIResource creates a resource given a bitmap.  The bitmap is
310   // generated via an interface function, which is called when initializing the
311   // resource and when the resource has been lost (due to lost context).  The
312   // parameter of the interface is a single boolean, which indicates whether the
313   // resource has been lost or not.  CreateUIResource returns an Id of the
314   // resource, which is always positive.
315   virtual UIResourceId CreateUIResource(UIResourceClient* client);
316   // Deletes a UI resource.  May safely be called more than once.
317   virtual void DeleteUIResource(UIResourceId id);
318   // Put the recreation of all UI resources into the resource queue after they
319   // were evicted on the impl thread.
320   void RecreateUIResources();
321
322   virtual gfx::Size GetUIResourceSize(UIResourceId id) const;
323
324   bool UsingSharedMemoryResources();
325   int id() const { return tree_id_; }
326
327   bool ScheduleMicroBenchmark(const std::string& benchmark_name,
328                               scoped_ptr<base::Value> value,
329                               const MicroBenchmark::DoneCallback& callback);
330
331  protected:
332   LayerTreeHost(LayerTreeHostClient* client,
333                 SharedBitmapManager* manager,
334                 const LayerTreeSettings& settings);
335   bool Initialize(scoped_refptr<base::SingleThreadTaskRunner> impl_task_runner);
336   bool InitializeForTesting(scoped_ptr<Proxy> proxy_for_testing);
337   void SetOutputSurfaceLostForTesting(bool is_lost) {
338     output_surface_lost_ = is_lost;
339   }
340
341  private:
342   bool InitializeProxy(scoped_ptr<Proxy> proxy);
343
344   void PaintLayerContents(
345       const RenderSurfaceLayerList& render_surface_layer_list,
346       ResourceUpdateQueue* queue,
347       bool* did_paint_content,
348       bool* need_more_updates);
349   void PaintMasksForRenderSurface(Layer* render_surface_layer,
350                                   ResourceUpdateQueue* queue,
351                                   bool* did_paint_content,
352                                   bool* need_more_updates);
353   bool UpdateLayers(Layer* root_layer, ResourceUpdateQueue* queue);
354   void UpdateHudLayer();
355   void TriggerPrepaint();
356
357   void ReduceMemoryUsage();
358
359   void PrioritizeTextures(
360       const RenderSurfaceLayerList& render_surface_layer_list,
361       OverdrawMetrics* metrics);
362   void SetPrioritiesForSurfaces(size_t surface_memory_bytes);
363   void SetPrioritiesForLayers(const RenderSurfaceLayerList& update_list);
364   size_t CalculateMemoryForRenderSurfaces(
365       const RenderSurfaceLayerList& update_list);
366
367   bool AnimateLayersRecursive(Layer* current, base::TimeTicks time);
368
369   struct UIResourceClientData {
370     UIResourceClient* client;
371     gfx::Size size;
372   };
373
374   typedef base::hash_map<UIResourceId, UIResourceClientData>
375       UIResourceClientMap;
376   UIResourceClientMap ui_resource_client_map_;
377   int next_ui_resource_id_;
378
379   typedef std::list<UIResourceRequest> UIResourceRequestQueue;
380   UIResourceRequestQueue ui_resource_request_queue_;
381
382   void CalculateLCDTextMetricsCallback(Layer* layer);
383
384   bool animating_;
385   bool needs_full_tree_sync_;
386   bool needs_filter_context_;
387
388   base::CancelableClosure prepaint_callback_;
389
390   LayerTreeHostClient* client_;
391   scoped_ptr<Proxy> proxy_;
392
393   int source_frame_number_;
394   scoped_ptr<RenderingStatsInstrumentation> rendering_stats_instrumentation_;
395   MicroBenchmarkController micro_benchmark_controller_;
396
397
398   bool output_surface_can_be_initialized_;
399   bool output_surface_lost_;
400   int num_failed_recreate_attempts_;
401
402   scoped_refptr<Layer> root_layer_;
403   scoped_refptr<HeadsUpDisplayLayer> hud_layer_;
404
405   scoped_ptr<PrioritizedResourceManager> contents_texture_manager_;
406   scoped_ptr<PrioritizedResource> surface_memory_placeholder_;
407
408   base::WeakPtr<InputHandler> input_handler_weak_ptr_;
409   base::WeakPtr<TopControlsManager> top_controls_manager_weak_ptr_;
410
411   const LayerTreeSettings settings_;
412   LayerTreeDebugState debug_state_;
413
414   gfx::Size device_viewport_size_;
415   float overdraw_bottom_height_;
416   float device_scale_factor_;
417
418   bool visible_;
419
420   typedef base::hash_map<WebKit::WebGraphicsContext3D*,
421                          scoped_refptr<RateLimiter> > RateLimiterMap;
422   RateLimiterMap rate_limiters_;
423
424   float page_scale_factor_;
425   float min_page_scale_factor_;
426   float max_page_scale_factor_;
427   gfx::Transform impl_transform_;
428   bool trigger_idle_updates_;
429
430   SkColor background_color_;
431   bool has_transparent_background_;
432
433   // If set, this texture is used to fill in the parts of the screen not
434   // covered by layers.
435   scoped_ptr<ScopedUIResource> overhang_ui_resource_;
436
437   typedef ScopedPtrVector<PrioritizedResource> TextureList;
438   size_t partial_texture_update_requests_;
439
440   scoped_ptr<AnimationRegistrar> animation_registrar_;
441
442   struct PendingPageScaleAnimation {
443     gfx::Vector2d target_offset;
444     bool use_anchor;
445     float scale;
446     base::TimeDelta duration;
447   };
448   scoped_ptr<PendingPageScaleAnimation> pending_page_scale_animation_;
449
450   bool in_paint_layer_contents_;
451
452   ui::LatencyInfo latency_info_;
453
454   static const int kTotalFramesToUseForLCDTextMetrics = 50;
455   int total_frames_used_for_lcd_text_metrics_;
456
457   struct LCDTextMetrics {
458     LCDTextMetrics()
459         : total_num_cc_layers(0),
460           total_num_cc_layers_can_use_lcd_text(0),
461           total_num_cc_layers_will_use_lcd_text(0) {}
462
463     int64 total_num_cc_layers;
464     int64 total_num_cc_layers_can_use_lcd_text;
465     int64 total_num_cc_layers_will_use_lcd_text;
466   };
467   LCDTextMetrics lcd_text_metrics_;
468   int tree_id_;
469   bool next_commit_forces_redraw_;
470
471   scoped_refptr<Layer> page_scale_layer_;
472   scoped_refptr<Layer> inner_viewport_scroll_layer_;
473   scoped_refptr<Layer> outer_viewport_scroll_layer_;
474
475   SharedBitmapManager* shared_bitmap_manager_;
476
477   DISALLOW_COPY_AND_ASSIGN(LayerTreeHost);
478 };
479
480 }  // namespace cc
481
482 #endif  // CC_TREES_LAYER_TREE_HOST_H_