Upstream version 5.34.104.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/occlusion_tracker.h"
40 #include "cc/trees/proxy.h"
41 #include "third_party/skia/include/core/SkColor.h"
42 #include "ui/gfx/rect.h"
43
44 namespace cc {
45
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;
63
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);
72
73   RendererCapabilities();
74   ~RendererCapabilities();
75
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;
82 };
83
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);
92
93   static scoped_ptr<LayerTreeHost> CreateSingleThreaded(
94       LayerTreeHostClient* client,
95       LayerTreeHostSingleThreadClient* single_thread_client,
96       SharedBitmapManager* manager,
97       const LayerTreeSettings& settings);
98   virtual ~LayerTreeHost();
99
100   void SetLayerTreeHostClientReady();
101
102   void set_needs_filter_context() { needs_filter_context_ = true; }
103   bool needs_offscreen_context() const {
104     return needs_filter_context_;
105   }
106
107   // LayerTreeHost interface to Proxy.
108   void WillBeginMainFrame() {
109     client_->WillBeginMainFrame(source_frame_number_);
110   }
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,
129   };
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);
139
140   LayerTreeHostClient* client() { return client_; }
141   const base::WeakPtr<InputHandler>& GetInputHandler() {
142     return input_handler_weak_ptr_;
143   }
144
145   void NotifyInputThrottledUntilCommit();
146
147   void Composite(base::TimeTicks frame_begin_time);
148
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);
154
155   void FinishAllRendering();
156
157   void SetDeferCommits(bool defer_commits);
158
159   // Test only hook
160   virtual void DidDeferCommit();
161
162   int source_frame_number() const { return source_frame_number_; }
163
164   void SetNeedsDisplayOnAllLayers();
165
166   void CollectRenderingStats(RenderingStats* stats) const;
167
168   RenderingStatsInstrumentation* rendering_stats_instrumentation() const {
169     return rendering_stats_instrumentation_.get();
170   }
171
172   const RendererCapabilities& GetRendererCapabilities() const;
173
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;
182
183   void SetNextCommitWaitsForActivation();
184
185   void SetNextCommitForcesRedraw();
186
187   void SetAnimationEvents(scoped_ptr<AnimationEventsVector> events,
188                           base::Time wall_clock_time);
189
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);
198   Layer* inner_viewport_scroll_layer() const {
199     return inner_viewport_scroll_layer_.get();
200   }
201   Layer* outer_viewport_scroll_layer() const {
202     return outer_viewport_scroll_layer_.get();
203   }
204
205   const LayerTreeSettings& settings() const { return settings_; }
206
207   void SetDebugState(const LayerTreeDebugState& debug_state);
208   const LayerTreeDebugState& debug_state() const { return debug_state_; }
209
210   void SetViewportSize(const gfx::Size& device_viewport_size);
211   void SetOverdrawBottomHeight(float overdraw_bottom_height);
212
213   gfx::Size device_viewport_size() const { return device_viewport_size_; }
214   float overdraw_bottom_height() const { return overdraw_bottom_height_; }
215
216   void ApplyPageScaleDeltaFromImplSide(float page_scale_delta);
217   void SetPageScaleFactorAndLimits(float page_scale_factor,
218                                    float min_page_scale_factor,
219                                    float max_page_scale_factor);
220   float page_scale_factor() const { return page_scale_factor_; }
221
222   SkColor background_color() const { return background_color_; }
223   void set_background_color(SkColor color) { background_color_ = color; }
224
225   void set_has_transparent_background(bool transparent) {
226     has_transparent_background_ = transparent;
227   }
228
229   void SetOverhangBitmap(const SkBitmap& bitmap);
230
231   PrioritizedResourceManager* contents_texture_manager() const {
232     return contents_texture_manager_.get();
233   }
234
235   void SetVisible(bool visible);
236   bool visible() const { return visible_; }
237
238   void StartPageScaleAnimation(const gfx::Vector2d& target_offset,
239                                bool use_anchor,
240                                float scale,
241                                base::TimeDelta duration);
242
243   void ApplyScrollAndScale(const ScrollAndScaleSet& info);
244   gfx::Vector2d DistributeScrollOffsetToViewports(const gfx::Vector2d offset,
245                                                   Layer* layer);
246
247   void SetImplTransform(const gfx::Transform& transform);
248
249   // Virtual for tests.
250   virtual void StartRateLimiter();
251   virtual void StopRateLimiter();
252
253   void RateLimit();
254
255   bool AlwaysUsePartialTextureUpdates();
256   size_t MaxPartialTextureUpdates() const;
257   bool RequestPartialTextureUpdate();
258
259   void SetDeviceScaleFactor(float device_scale_factor);
260   float device_scale_factor() const { return device_scale_factor_; }
261
262   void UpdateTopControlsState(TopControlsState constraints,
263                               TopControlsState current,
264                               bool animate);
265
266   HeadsUpDisplayLayer* hud_layer() const { return hud_layer_.get(); }
267
268   Proxy* proxy() const { return proxy_.get(); }
269
270   AnimationRegistrar* animation_registrar() const {
271     return animation_registrar_.get();
272   }
273
274   // Obtains a thorough dump of the LayerTreeHost as a value.
275   scoped_ptr<base::Value> AsValue() const;
276
277   bool in_paint_layer_contents() const { return in_paint_layer_contents_; }
278
279   // CreateUIResource creates a resource given a bitmap.  The bitmap is
280   // generated via an interface function, which is called when initializing the
281   // resource and when the resource has been lost (due to lost context).  The
282   // parameter of the interface is a single boolean, which indicates whether the
283   // resource has been lost or not.  CreateUIResource returns an Id of the
284   // resource, which is always positive.
285   virtual UIResourceId CreateUIResource(UIResourceClient* client);
286   // Deletes a UI resource.  May safely be called more than once.
287   virtual void DeleteUIResource(UIResourceId id);
288   // Put the recreation of all UI resources into the resource queue after they
289   // were evicted on the impl thread.
290   void RecreateUIResources();
291
292   virtual gfx::Size GetUIResourceSize(UIResourceId id) const;
293
294   bool UsingSharedMemoryResources();
295   int id() const { return id_; }
296
297   bool ScheduleMicroBenchmark(const std::string& benchmark_name,
298                               scoped_ptr<base::Value> value,
299                               const MicroBenchmark::DoneCallback& callback);
300
301   // When a SwapPromiseMonitor is created on the main thread, it calls
302   // InsertSwapPromiseMonitor() to register itself with LayerTreeHost.
303   // When the monitor is destroyed, it calls RemoveSwapPromiseMonitor()
304   // to unregister itself.
305   void InsertSwapPromiseMonitor(SwapPromiseMonitor* monitor);
306   void RemoveSwapPromiseMonitor(SwapPromiseMonitor* monitor);
307
308   // Call this function when you expect there to be a swap buffer.
309   // See swap_promise.h for how to use SwapPromise.
310   void QueueSwapPromise(scoped_ptr<SwapPromise> swap_promise);
311
312   void BreakSwapPromises(SwapPromise::DidNotSwapReason reason);
313
314  protected:
315   LayerTreeHost(LayerTreeHostClient* client,
316                 SharedBitmapManager* manager,
317                 const LayerTreeSettings& settings);
318   void InitializeThreaded(
319       scoped_refptr<base::SingleThreadTaskRunner> impl_task_runner);
320   void InitializeSingleThreaded(
321       LayerTreeHostSingleThreadClient* single_thread_client);
322   void InitializeForTesting(scoped_ptr<Proxy> proxy_for_testing);
323   void SetOutputSurfaceLostForTesting(bool is_lost) {
324     output_surface_lost_ = is_lost;
325   }
326
327   MicroBenchmarkController micro_benchmark_controller_;
328
329  private:
330   void InitializeProxy(scoped_ptr<Proxy> proxy);
331
332   void PaintLayerContents(
333       const RenderSurfaceLayerList& render_surface_layer_list,
334       ResourceUpdateQueue* queue,
335       bool* did_paint_content,
336       bool* need_more_updates);
337   void PaintMasksForRenderSurface(Layer* render_surface_layer,
338                                   ResourceUpdateQueue* queue,
339                                   bool* did_paint_content,
340                                   bool* need_more_updates);
341   bool UpdateLayers(Layer* root_layer, ResourceUpdateQueue* queue);
342   void UpdateHudLayer();
343   void TriggerPrepaint();
344
345   void ReduceMemoryUsage();
346
347   void PrioritizeTextures(
348       const RenderSurfaceLayerList& render_surface_layer_list,
349       OverdrawMetrics* metrics);
350   void SetPrioritiesForSurfaces(size_t surface_memory_bytes);
351   void SetPrioritiesForLayers(const RenderSurfaceLayerList& update_list);
352   size_t CalculateMemoryForRenderSurfaces(
353       const RenderSurfaceLayerList& update_list);
354
355   bool AnimateLayersRecursive(Layer* current, base::TimeTicks time);
356
357   struct UIResourceClientData {
358     UIResourceClient* client;
359     gfx::Size size;
360   };
361
362   typedef base::hash_map<UIResourceId, UIResourceClientData>
363       UIResourceClientMap;
364   UIResourceClientMap ui_resource_client_map_;
365   int next_ui_resource_id_;
366
367   typedef std::list<UIResourceRequest> UIResourceRequestQueue;
368   UIResourceRequestQueue ui_resource_request_queue_;
369
370   void CalculateLCDTextMetricsCallback(Layer* layer);
371
372   void NotifySwapPromiseMonitorsOfSetNeedsCommit();
373
374   bool animating_;
375   bool needs_full_tree_sync_;
376   bool needs_filter_context_;
377
378   base::CancelableClosure prepaint_callback_;
379
380   LayerTreeHostClient* client_;
381   scoped_ptr<Proxy> proxy_;
382
383   int source_frame_number_;
384   scoped_ptr<RenderingStatsInstrumentation> rendering_stats_instrumentation_;
385
386   bool output_surface_can_be_initialized_;
387   bool output_surface_lost_;
388   int num_failed_recreate_attempts_;
389
390   scoped_refptr<Layer> root_layer_;
391   scoped_refptr<HeadsUpDisplayLayer> hud_layer_;
392
393   scoped_ptr<PrioritizedResourceManager> contents_texture_manager_;
394   scoped_ptr<PrioritizedResource> surface_memory_placeholder_;
395
396   base::WeakPtr<InputHandler> input_handler_weak_ptr_;
397   base::WeakPtr<TopControlsManager> top_controls_manager_weak_ptr_;
398
399   const LayerTreeSettings settings_;
400   LayerTreeDebugState debug_state_;
401
402   gfx::Size device_viewport_size_;
403   float overdraw_bottom_height_;
404   float device_scale_factor_;
405
406   bool visible_;
407
408   base::OneShotTimer<LayerTreeHost> rate_limit_timer_;
409
410   float page_scale_factor_;
411   float min_page_scale_factor_;
412   float max_page_scale_factor_;
413   gfx::Transform impl_transform_;
414   bool trigger_idle_updates_;
415
416   SkColor background_color_;
417   bool has_transparent_background_;
418
419   // If set, this texture is used to fill in the parts of the screen not
420   // covered by layers.
421   scoped_ptr<ScopedUIResource> overhang_ui_resource_;
422
423   typedef ScopedPtrVector<PrioritizedResource> TextureList;
424   size_t partial_texture_update_requests_;
425
426   scoped_ptr<AnimationRegistrar> animation_registrar_;
427
428   struct PendingPageScaleAnimation {
429     gfx::Vector2d target_offset;
430     bool use_anchor;
431     float scale;
432     base::TimeDelta duration;
433   };
434   scoped_ptr<PendingPageScaleAnimation> pending_page_scale_animation_;
435
436   bool in_paint_layer_contents_;
437
438   static const int kTotalFramesToUseForLCDTextMetrics = 50;
439   int total_frames_used_for_lcd_text_metrics_;
440
441   struct LCDTextMetrics {
442     LCDTextMetrics()
443         : total_num_cc_layers(0),
444           total_num_cc_layers_can_use_lcd_text(0),
445           total_num_cc_layers_will_use_lcd_text(0) {}
446
447     int64 total_num_cc_layers;
448     int64 total_num_cc_layers_can_use_lcd_text;
449     int64 total_num_cc_layers_will_use_lcd_text;
450   };
451   LCDTextMetrics lcd_text_metrics_;
452   int id_;
453   bool next_commit_forces_redraw_;
454
455   scoped_refptr<Layer> page_scale_layer_;
456   scoped_refptr<Layer> inner_viewport_scroll_layer_;
457   scoped_refptr<Layer> outer_viewport_scroll_layer_;
458
459   SharedBitmapManager* shared_bitmap_manager_;
460
461   ScopedPtrVector<SwapPromise> swap_promise_list_;
462   std::set<SwapPromiseMonitor*> swap_promise_monitor_;
463
464   DISALLOW_COPY_AND_ASSIGN(LayerTreeHost);
465 };
466
467 }  // namespace cc
468
469 #endif  // CC_TREES_LAYER_TREE_HOST_H_