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