summaryrefslogtreecommitdiffstats
path: root/cc/trees/layer_tree_host_impl.h
blob: f65922aa8769dc7e50f2ef96cdba562d85d7fc7f (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
// Copyright 2011 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#ifndef CC_TREES_LAYER_TREE_HOST_IMPL_H_
#define CC_TREES_LAYER_TREE_HOST_IMPL_H_

#include <string>
#include <vector>

#include "base/basictypes.h"
#include "base/memory/scoped_ptr.h"
#include "base/time.h"
#include "cc/animation/animation_events.h"
#include "cc/animation/animation_registrar.h"
#include "cc/base/cc_export.h"
#include "cc/input/input_handler.h"
#include "cc/input/layer_scroll_offset_delegate.h"
#include "cc/input/top_controls_manager_client.h"
#include "cc/layers/layer_lists.h"
#include "cc/layers/render_pass_sink.h"
#include "cc/output/output_surface_client.h"
#include "cc/output/renderer.h"
#include "cc/quads/render_pass.h"
#include "cc/resources/tile_manager.h"
#include "skia/ext/refptr.h"
#include "third_party/skia/include/core/SkColor.h"
#include "third_party/skia/include/core/SkPicture.h"
#include "ui/base/latency_info.h"
#include "ui/gfx/rect.h"

namespace cc {

class CompletionEvent;
class CompositorFrameMetadata;
class DebugRectHistory;
class FrameRateCounter;
class LayerImpl;
class LayerTreeHostImplTimeSourceAdapter;
class LayerTreeImpl;
class PageScaleAnimation;
class PaintTimeCounter;
class MemoryHistory;
class RenderingStatsInstrumentation;
class RenderPassDrawQuad;
class ResourceProvider;
class TopControlsManager;
struct RendererCapabilities;

// LayerTreeHost->Proxy callback interface.
class LayerTreeHostImplClient {
 public:
  virtual void DidLoseOutputSurfaceOnImplThread() = 0;
  virtual void OnSwapBuffersCompleteOnImplThread() = 0;
  virtual void OnVSyncParametersChanged(base::TimeTicks timebase,
                                        base::TimeDelta interval) = 0;
  virtual void BeginFrameOnImplThread(base::TimeTicks frame_time) = 0;
  virtual void OnCanDrawStateChanged(bool can_draw) = 0;
  virtual void OnHasPendingTreeStateChanged(bool has_pending_tree) = 0;
  virtual void SetNeedsRedrawOnImplThread() = 0;
  virtual void SetNeedsRedrawRectOnImplThread(gfx::Rect damage_rect) = 0;
  virtual void DidInitializeVisibleTileOnImplThread() = 0;
  virtual void SetNeedsCommitOnImplThread() = 0;
  virtual void SetNeedsManageTilesOnImplThread() = 0;
  virtual void PostAnimationEventsToMainThreadOnImplThread(
      scoped_ptr<AnimationEventsVector> events,
      base::Time wall_clock_time) = 0;
  // Returns true if resources were deleted by this call.
  virtual bool ReduceContentsTextureMemoryOnImplThread(
      size_t limit_bytes,
      int priority_cutoff) = 0;
  virtual void ReduceWastedContentsTextureMemoryOnImplThread() = 0;
  virtual void SendManagedMemoryStats() = 0;
  virtual bool IsInsideDraw() = 0;
  virtual void RenewTreePriority() = 0;
  virtual void RequestScrollbarAnimationOnImplThread(base::TimeDelta delay) = 0;
  virtual void DidActivatePendingTree() = 0;

 protected:
  virtual ~LayerTreeHostImplClient() {}
};

// LayerTreeHostImpl owns the LayerImpl trees as well as associated rendering
// state.
class CC_EXPORT LayerTreeHostImpl
    : public InputHandler,
      public RendererClient,
      public TileManagerClient,
      public OutputSurfaceClient,
      public TopControlsManagerClient,
      public base::SupportsWeakPtr<LayerTreeHostImpl> {
 public:
  static scoped_ptr<LayerTreeHostImpl> Create(
      const LayerTreeSettings& settings,
      LayerTreeHostImplClient* client,
      Proxy* proxy,
      RenderingStatsInstrumentation* rendering_stats_instrumentation);
  virtual ~LayerTreeHostImpl();

  // InputHandler implementation
  virtual void BindToClient(InputHandlerClient* client) OVERRIDE;
  virtual InputHandler::ScrollStatus ScrollBegin(
      gfx::Point viewport_point,
      InputHandler::ScrollInputType type) OVERRIDE;
  virtual bool ScrollBy(gfx::Point viewport_point,
                        gfx::Vector2dF scroll_delta) OVERRIDE;
  virtual bool ScrollVerticallyByPage(gfx::Point viewport_point,
                                      ScrollDirection direction) OVERRIDE;
  virtual void SetRootLayerScrollOffsetDelegate(
      LayerScrollOffsetDelegate* root_layer_scroll_offset_delegate) OVERRIDE;
  virtual void OnRootLayerDelegatedScrollOffsetChanged() OVERRIDE;
  virtual void ScrollEnd() OVERRIDE;
  virtual InputHandler::ScrollStatus FlingScrollBegin() OVERRIDE;
  virtual void NotifyCurrentFlingVelocity(gfx::Vector2dF velocity) OVERRIDE;
  virtual void PinchGestureBegin() OVERRIDE;
  virtual void PinchGestureUpdate(float magnify_delta,
                                  gfx::Point anchor) OVERRIDE;
  virtual void PinchGestureEnd() OVERRIDE;
  virtual void StartPageScaleAnimation(gfx::Vector2d target_offset,
                                       bool anchor_point,
                                       float page_scale,
                                       base::TimeTicks start_time,
                                       base::TimeDelta duration) OVERRIDE;
  virtual void ScheduleAnimation() OVERRIDE;
  virtual bool HaveTouchEventHandlersAt(gfx::Point viewport_port) OVERRIDE;

  // TopControlsManagerClient implementation.
  virtual void DidChangeTopControlsPosition() OVERRIDE;
  virtual bool HaveRootScrollLayer() const OVERRIDE;

  void StartScrollbarAnimation(base::TimeTicks now);

  struct CC_EXPORT FrameData : public RenderPassSink {
    FrameData();
    virtual ~FrameData();

    std::vector<gfx::Rect> occluding_screen_space_rects;
    std::vector<gfx::Rect> non_occluding_screen_space_rects;
    RenderPassList render_passes;
    RenderPassIdHashMap render_passes_by_id;
    const LayerImplList* render_surface_layer_list;
    LayerImplList will_draw_layers;
    bool contains_incomplete_tile;
    bool has_no_damage;
    ui::LatencyInfo latency_info;

    // RenderPassSink implementation.
    virtual void AppendRenderPass(scoped_ptr<RenderPass> render_pass) OVERRIDE;
  };

  virtual void BeginCommit();
  virtual void CommitComplete();
  virtual void Animate(base::TimeTicks monotonic_time,
                       base::Time wall_clock_time);
  virtual void UpdateAnimationState(bool start_ready_animations);
  void MainThreadHasStoppedFlinging();
  void UpdateBackgroundAnimateTicking(bool should_background_tick);
  void SetViewportDamage(gfx::Rect damage_rect);

  void ManageTiles();

  // Returns false if problems occured preparing the frame, and we should try
  // to avoid displaying the frame. If PrepareToDraw is called, DidDrawAllLayers
  // must also be called, regardless of whether DrawLayers is called between the
  // two.
  virtual bool PrepareToDraw(FrameData* frame,
                             gfx::Rect device_viewport_damage_rect);
  virtual void DrawLayers(FrameData* frame, base::TimeTicks frame_begin_time);
  // Must be called if and only if PrepareToDraw was called.
  void DidDrawAllLayers(const FrameData& frame);

  const LayerTreeSettings& settings() const { return settings_; }

  // Returns the currently visible viewport size in DIP. This value excludes
  // the URL bar and non-overlay scrollbars.
  gfx::SizeF VisibleViewportSize() const;

  // RendererClient implementation
 private:
  virtual gfx::Size DeviceViewportSize() const OVERRIDE;
  virtual float DeviceScaleFactor() const OVERRIDE;
  virtual const LayerTreeSettings& Settings() const OVERRIDE;
 public:
  virtual void DidLoseOutputSurface() OVERRIDE;
  virtual void OnSwapBuffersComplete() OVERRIDE;
  virtual void SetFullRootLayerDamage() OVERRIDE;
  virtual void SetManagedMemoryPolicy(const ManagedMemoryPolicy& policy)
      OVERRIDE;
  virtual void EnforceManagedMemoryPolicy(const ManagedMemoryPolicy& policy)
      OVERRIDE;
  virtual bool HasImplThread() const OVERRIDE;
  virtual bool ShouldClearRootRenderPass() const OVERRIDE;
  virtual CompositorFrameMetadata MakeCompositorFrameMetadata() const OVERRIDE;
  virtual bool AllowPartialSwap() const OVERRIDE;

  // TileManagerClient implementation.
  virtual void ScheduleManageTiles() OVERRIDE;
  virtual void DidInitializeVisibleTile() OVERRIDE;
  virtual bool ShouldForceTileUploadsRequiredForActivationToComplete() const
      OVERRIDE;

  // OutputSurfaceClient implementation.
  virtual void SetNeedsRedrawRect(gfx::Rect rect) OVERRIDE;
  virtual void OnVSyncParametersChanged(base::TimeTicks timebase,
                                        base::TimeDelta interval) OVERRIDE;
  virtual void BeginFrame(base::TimeTicks frame_time)
      OVERRIDE;
  virtual void OnSendFrameToParentCompositorAck(const CompositorFrameAck& ack)
      OVERRIDE;

  // Called from LayerTreeImpl.
  void OnCanDrawStateChangedForTree();

  // Implementation
  bool CanDraw();
  OutputSurface* output_surface() const { return output_surface_.get(); }

  std::string LayerTreeAsText() const;
  std::string LayerTreeAsJson() const;

  void FinishAllRendering();
  int SourceAnimationFrameNumber() const;

  virtual bool InitializeRenderer(scoped_ptr<OutputSurface> output_surface);
  bool IsContextLost();
  TileManager* tile_manager() { return tile_manager_.get(); }
  Renderer* renderer() { return renderer_.get(); }
  const RendererCapabilities& GetRendererCapabilities() const;

  virtual bool SwapBuffers(const FrameData& frame);
  void SetNeedsBeginFrame(bool enable);

  void Readback(void* pixels, gfx::Rect rect_in_device_viewport);

  LayerTreeImpl* active_tree() { return active_tree_.get(); }
  const LayerTreeImpl* active_tree() const { return active_tree_.get(); }
  LayerTreeImpl* pending_tree() { return pending_tree_.get(); }
  const LayerTreeImpl* pending_tree() const { return pending_tree_.get(); }
  const LayerTreeImpl* recycle_tree() const { return recycle_tree_.get(); }
  void CreatePendingTree();
  void CheckForCompletedTileUploads();
  virtual bool ActivatePendingTreeIfNeeded();

  // Shortcuts to layers on the active tree.
  LayerImpl* RootLayer() const;
  LayerImpl* RootScrollLayer() const;
  LayerImpl* CurrentlyScrollingLayer() const;

  virtual void SetVisible(bool visible);
  bool visible() const { return visible_; }

  void SetNeedsCommit() { client_->SetNeedsCommitOnImplThread(); }
  void SetNeedsRedraw() { client_->SetNeedsRedrawOnImplThread(); }

  ManagedMemoryPolicy ActualManagedMemoryPolicy() const;

  size_t memory_allocation_limit_bytes() const {
    return managed_memory_policy_.bytes_limit_when_visible;
  }

  void SetViewportSize(gfx::Size device_viewport_size);
  gfx::Size device_viewport_size() const { return device_viewport_size_; }

  void SetOverdrawBottomHeight(float overdraw_bottom_height);
  float overdraw_bottom_height() const { return overdraw_bottom_height_; }

  void SetDeviceScaleFactor(float device_scale_factor);
  float device_scale_factor() const { return device_scale_factor_; }

  scoped_ptr<ScrollAndScaleSet> ProcessScrollDeltas();

  bool needs_animate_layers() const {
    return !animation_registrar_->active_animation_controllers().empty();
  }

  void SendManagedMemoryStats(
      size_t memory_visible_bytes,
      size_t memory_visible_and_nearby_bytes,
      size_t memory_use_bytes);

  void set_max_memory_needed_bytes(size_t bytes) {
    max_memory_needed_bytes_ = bytes;
  }

  FrameRateCounter* fps_counter() {
    return fps_counter_.get();
  }
  PaintTimeCounter* paint_time_counter() {
    return paint_time_counter_.get();
  }
  MemoryHistory* memory_history() {
    return memory_history_.get();
  }
  DebugRectHistory* debug_rect_history() {
    return debug_rect_history_.get();
  }
  ResourceProvider* resource_provider() {
    return resource_provider_.get();
  }
  TopControlsManager* top_controls_manager() {
    return top_controls_manager_.get();
  }

  Proxy* proxy() const { return proxy_; }

  AnimationRegistrar* animation_registrar() const {
    return animation_registrar_.get();
  }

  void SetDebugState(const LayerTreeDebugState& debug_state);
  const LayerTreeDebugState& debug_state() const { return debug_state_; }

  class CC_EXPORT CullRenderPassesWithCachedTextures {
 public:
    bool ShouldRemoveRenderPass(const RenderPassDrawQuad& quad,
                                const FrameData& frame) const;

    // Iterates from the root first, in order to remove the surfaces closest
    // to the root with cached textures, and all surfaces that draw into
    // them.
    size_t RenderPassListBegin(const RenderPassList& list) const {
      return list.size() - 1;
    }
    size_t RenderPassListEnd(const RenderPassList& list) const { return 0 - 1; }
    size_t RenderPassListNext(size_t it) const { return it - 1; }

    explicit CullRenderPassesWithCachedTextures(Renderer* renderer)
        : renderer_(renderer) {}
 private:
    Renderer* renderer_;
  };

  class CC_EXPORT CullRenderPassesWithNoQuads {
 public:
    bool ShouldRemoveRenderPass(const RenderPassDrawQuad& quad,
                                const FrameData& frame) const;

    // Iterates in draw order, so that when a surface is removed, and its
    // target becomes empty, then its target can be removed also.
    size_t RenderPassListBegin(const RenderPassList& list) const { return 0; }
    size_t RenderPassListEnd(const RenderPassList& list) const {
      return list.size();
    }
    size_t RenderPassListNext(size_t it) const { return it + 1; }
  };

  template <typename RenderPassCuller>
      static void RemoveRenderPasses(RenderPassCuller culler, FrameData* frame);

  skia::RefPtr<SkPicture> CapturePicture();

  gfx::Vector2dF accumulated_root_overscroll() const {
    return accumulated_root_overscroll_;
  }
  gfx::Vector2dF current_fling_velocity() const {
    return current_fling_velocity_;
  }

  bool pinch_gesture_active() const { return pinch_gesture_active_; }

  void SetTreePriority(TreePriority priority);

  void ResetCurrentFrameTimeForNextFrame();
  base::TimeTicks CurrentFrameTimeTicks();
  base::Time CurrentFrameTime();

  scoped_ptr<base::Value> AsValue() const;
  scoped_ptr<base::Value> ActivationStateAsValue() const;

  bool page_scale_animation_active() const { return !!page_scale_animation_; }

 protected:
  LayerTreeHostImpl(
      const LayerTreeSettings& settings,
      LayerTreeHostImplClient* client,
      Proxy* proxy,
      RenderingStatsInstrumentation* rendering_stats_instrumentation);
  void ActivatePendingTree();

  // Virtual for testing.
  virtual void AnimateLayers(base::TimeTicks monotonic_time,
                             base::Time wall_clock_time);

  // Virtual for testing.
  virtual base::TimeDelta LowFrequencyAnimationInterval() const;

  const AnimationRegistrar::AnimationControllerMap&
      active_animation_controllers() const {
    return animation_registrar_->active_animation_controllers();
  }

  LayerTreeHostImplClient* client_;
  Proxy* proxy_;

 private:
  void AnimatePageScale(base::TimeTicks monotonic_time);
  void AnimateScrollbars(base::TimeTicks monotonic_time);
  void AnimateTopControls(base::TimeTicks monotonic_time);

  gfx::Vector2dF ScrollLayerWithViewportSpaceDelta(
      LayerImpl* layer_impl,
      float scale_from_viewport_to_screen_space,
      gfx::PointF viewport_point,
      gfx::Vector2dF viewport_delta);

  void UpdateMaxScrollOffset();
  void TrackDamageForAllSurfaces(
      LayerImpl* root_draw_layer,
      const LayerImplList& render_surface_layer_list);

  void UpdateTileManagerMemoryPolicy(const ManagedMemoryPolicy& policy);

  // Returns false if the frame should not be displayed. This function should
  // only be called from PrepareToDraw, as DidDrawAllLayers must be called
  // if this helper function is called.
  bool CalculateRenderPasses(FrameData* frame);

  void ClearRenderSurfaces();
  bool EnsureRenderSurfaceLayerList();
  void ClearCurrentlyScrollingLayer();

  void AnimateScrollbarsRecursive(LayerImpl* layer,
                                  base::TimeTicks time);

  void DumpRenderSurfaces(std::string* str,
                          int indent,
                          const LayerImpl* layer) const;

  static LayerImpl* GetNonCompositedContentLayerRecursive(LayerImpl* layer);

  void StartScrollbarAnimationRecursive(LayerImpl* layer, base::TimeTicks time);

  scoped_ptr<OutputSurface> output_surface_;

  // |resource_provider_| and |tile_manager_| can be NULL, e.g. when using tile-
  // free rendering - see OutputSurface::ForcedDrawToSoftwareDevice().
  scoped_ptr<ResourceProvider> resource_provider_;
  scoped_ptr<TileManager> tile_manager_;
  scoped_ptr<Renderer> renderer_;

  // Tree currently being drawn.
  scoped_ptr<LayerTreeImpl> active_tree_;

  // In impl-side painting mode, tree with possibly incomplete rasterized
  // content. May be promoted to active by ActivatePendingTreeIfNeeded().
  scoped_ptr<LayerTreeImpl> pending_tree_;

  // In impl-side painting mode, inert tree with layers that can be recycled
  // by the next sync from the main thread.
  scoped_ptr<LayerTreeImpl> recycle_tree_;

  InputHandlerClient* input_handler_client_;
  bool did_lock_scrolling_layer_;
  bool should_bubble_scrolls_;
  bool wheel_scrolling_;
  // The optional delegate for the root layer scroll offset.
  LayerScrollOffsetDelegate* root_layer_scroll_offset_delegate_;
  LayerTreeSettings settings_;
  LayerTreeDebugState debug_state_;
  gfx::Size device_viewport_size_;
  float overdraw_bottom_height_;
  float device_scale_factor_;
  bool visible_;
  ManagedMemoryPolicy managed_memory_policy_;

  gfx::Vector2dF accumulated_root_overscroll_;
  gfx::Vector2dF current_fling_velocity_;

  bool pinch_gesture_active_;
  gfx::Point previous_pinch_anchor_;

  // This is set by AnimateLayers() and used by UpdateAnimationState()
  // when sending animation events to the main thread.
  base::Time last_animation_time_;

  scoped_ptr<TopControlsManager> top_controls_manager_;

  scoped_ptr<PageScaleAnimation> page_scale_animation_;

  // This is used for ticking animations slowly when hidden.
  scoped_ptr<LayerTreeHostImplTimeSourceAdapter> time_source_client_adapter_;

  scoped_ptr<FrameRateCounter> fps_counter_;
  scoped_ptr<PaintTimeCounter> paint_time_counter_;
  scoped_ptr<MemoryHistory> memory_history_;
  scoped_ptr<DebugRectHistory> debug_rect_history_;

  // The maximum memory that would be used by the prioritized resource
  // manager, if there were no limit on memory usage.
  size_t max_memory_needed_bytes_;

  size_t last_sent_memory_visible_bytes_;
  size_t last_sent_memory_visible_and_nearby_bytes_;
  size_t last_sent_memory_use_bytes_;

  gfx::Rect viewport_damage_rect_;

  base::TimeTicks current_frame_timeticks_;
  base::Time current_frame_time_;

  scoped_ptr<AnimationRegistrar> animation_registrar_;

  RenderingStatsInstrumentation* rendering_stats_instrumentation_;

  DISALLOW_COPY_AND_ASSIGN(LayerTreeHostImpl);
};

}  // namespace cc

#endif  // CC_TREES_LAYER_TREE_HOST_IMPL_H_