Upstream version 9.38.198.0
[platform/framework/web/crosswalk.git] / src / content / renderer / gpu / render_widget_compositor.cc
1 // Copyright (c) 2013 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 #include "content/renderer/gpu/render_widget_compositor.h"
6
7 #include <limits>
8 #include <string>
9
10 #include "base/command_line.h"
11 #include "base/logging.h"
12 #include "base/strings/string_number_conversions.h"
13 #include "base/synchronization/lock.h"
14 #include "base/sys_info.h"
15 #include "base/time/time.h"
16 #include "base/values.h"
17 #include "cc/base/latency_info_swap_promise.h"
18 #include "cc/base/latency_info_swap_promise_monitor.h"
19 #include "cc/base/swap_promise.h"
20 #include "cc/base/switches.h"
21 #include "cc/debug/layer_tree_debug_state.h"
22 #include "cc/debug/micro_benchmark.h"
23 #include "cc/input/layer_selection_bound.h"
24 #include "cc/layers/layer.h"
25 #include "cc/output/copy_output_request.h"
26 #include "cc/output/copy_output_result.h"
27 #include "cc/resources/single_release_callback.h"
28 #include "cc/trees/layer_tree_host.h"
29 #include "content/child/child_shared_bitmap_manager.h"
30 #include "content/common/content_switches_internal.h"
31 #include "content/common/gpu/client/context_provider_command_buffer.h"
32 #include "content/public/common/content_switches.h"
33 #include "content/renderer/compositor_bindings/web_layer_impl.h"
34 #include "content/renderer/input/input_handler_manager.h"
35 #include "content/renderer/render_thread_impl.h"
36 #include "gpu/command_buffer/client/gles2_interface.h"
37 #include "third_party/WebKit/public/platform/WebCompositeAndReadbackAsyncCallback.h"
38 #include "third_party/WebKit/public/platform/WebSelectionBound.h"
39 #include "third_party/WebKit/public/platform/WebSize.h"
40 #include "third_party/WebKit/public/web/WebWidget.h"
41 #include "ui/gfx/frame_time.h"
42 #include "ui/gl/gl_switches.h"
43 #include "ui/native_theme/native_theme_switches.h"
44
45 #if defined(OS_ANDROID)
46 #include "content/renderer/android/synchronous_compositor_factory.h"
47 #include "ui/gfx/android/device_display_info.h"
48 #endif
49
50 namespace base {
51 class Value;
52 }
53
54 namespace cc {
55 class Layer;
56 }
57
58 using blink::WebFloatPoint;
59 using blink::WebSelectionBound;
60 using blink::WebSize;
61 using blink::WebRect;
62
63 namespace content {
64 namespace {
65
66 bool GetSwitchValueAsInt(
67     const CommandLine& command_line,
68     const std::string& switch_string,
69     int min_value,
70     int max_value,
71     int* result) {
72   std::string string_value = command_line.GetSwitchValueASCII(switch_string);
73   int int_value;
74   if (base::StringToInt(string_value, &int_value) &&
75       int_value >= min_value && int_value <= max_value) {
76     *result = int_value;
77     return true;
78   } else {
79     LOG(WARNING) << "Failed to parse switch " << switch_string  << ": " <<
80         string_value;
81     return false;
82   }
83 }
84
85 cc::LayerSelectionBound ConvertWebSelectionBound(
86     const WebSelectionBound& bound) {
87   DCHECK(bound.layerId);
88
89   cc::LayerSelectionBound result;
90   switch (bound.type) {
91     case blink::WebSelectionBound::Caret:
92       result.type = cc::SELECTION_BOUND_CENTER;
93       break;
94     case blink::WebSelectionBound::SelectionLeft:
95       result.type = cc::SELECTION_BOUND_LEFT;
96       break;
97     case blink::WebSelectionBound::SelectionRight:
98       result.type = cc::SELECTION_BOUND_RIGHT;
99       break;
100   }
101   result.layer_id = bound.layerId;
102   result.layer_rect = gfx::Rect(bound.edgeRectInLayer);
103   return result;
104 }
105
106 gfx::Size CalculateDefaultTileSize() {
107   int default_tile_size = 256;
108 #if defined(OS_ANDROID)
109   // TODO(epenner): unify this for all platforms if it
110   // makes sense (http://crbug.com/159524)
111
112   gfx::DeviceDisplayInfo info;
113   bool real_size_supported = true;
114   int display_width = info.GetPhysicalDisplayWidth();
115   int display_height = info.GetPhysicalDisplayHeight();
116   if (display_width == 0 || display_height == 0) {
117     real_size_supported = false;
118     display_width = info.GetDisplayWidth();
119     display_height = info.GetDisplayHeight();
120   }
121
122   int portrait_width = std::min(display_width, display_height);
123   int landscape_width = std::max(display_width, display_height);
124
125   if (real_size_supported) {
126     // Maximum HD dimensions should be 768x1280
127     // Maximum FHD dimensions should be 1200x1920
128     if (portrait_width > 768 || landscape_width > 1280)
129       default_tile_size = 384;
130     if (portrait_width > 1200 || landscape_width > 1920)
131       default_tile_size = 512;
132
133     // Adjust for some resolutions that barely straddle an extra
134     // tile when in portrait mode. This helps worst case scroll/raster
135     // by not needing a full extra tile for each row.
136     if (default_tile_size == 256 && portrait_width == 768)
137       default_tile_size += 32;
138     if (default_tile_size == 384 && portrait_width == 1200)
139       default_tile_size += 32;
140   } else {
141     // We don't know the exact resolution due to screen controls etc.
142     // So this just estimates the values above using tile counts.
143     int numTiles = (display_width * display_height) / (256 * 256);
144     if (numTiles > 16)
145       default_tile_size = 384;
146     if (numTiles >= 40)
147       default_tile_size = 512;
148   }
149 #endif
150   return gfx::Size(default_tile_size, default_tile_size);
151 }
152
153 }  // namespace
154
155 // static
156 scoped_ptr<RenderWidgetCompositor> RenderWidgetCompositor::Create(
157     RenderWidget* widget,
158     bool threaded) {
159   scoped_ptr<RenderWidgetCompositor> compositor(
160       new RenderWidgetCompositor(widget, threaded));
161
162   CommandLine* cmd = CommandLine::ForCurrentProcess();
163
164   cc::LayerTreeSettings settings;
165
166   // For web contents, layer transforms should scale up the contents of layers
167   // to keep content always crisp when possible.
168   settings.layer_transforms_should_scale_layer_contents = true;
169
170   settings.throttle_frame_production =
171       !cmd->HasSwitch(switches::kDisableGpuVsync);
172   settings.begin_frame_scheduling_enabled =
173       cmd->HasSwitch(switches::kEnableBeginFrameScheduling);
174   settings.main_frame_before_activation_enabled =
175       cmd->HasSwitch(cc::switches::kEnableMainFrameBeforeActivation) &&
176       !cmd->HasSwitch(cc::switches::kDisableMainFrameBeforeActivation);
177   settings.main_frame_before_draw_enabled =
178       !cmd->HasSwitch(cc::switches::kDisableMainFrameBeforeDraw);
179   settings.report_overscroll_only_for_scrollable_axes = true;
180   settings.accelerated_animation_enabled =
181       !cmd->HasSwitch(cc::switches::kDisableThreadedAnimation);
182
183   settings.default_tile_size = CalculateDefaultTileSize();
184   if (cmd->HasSwitch(switches::kDefaultTileWidth)) {
185     int tile_width = 0;
186     GetSwitchValueAsInt(*cmd,
187                         switches::kDefaultTileWidth,
188                         1,
189                         std::numeric_limits<int>::max(),
190                         &tile_width);
191     settings.default_tile_size.set_width(tile_width);
192   }
193   if (cmd->HasSwitch(switches::kDefaultTileHeight)) {
194     int tile_height = 0;
195     GetSwitchValueAsInt(*cmd,
196                         switches::kDefaultTileHeight,
197                         1,
198                         std::numeric_limits<int>::max(),
199                         &tile_height);
200     settings.default_tile_size.set_height(tile_height);
201   }
202
203   int max_untiled_layer_width = settings.max_untiled_layer_size.width();
204   if (cmd->HasSwitch(switches::kMaxUntiledLayerWidth)) {
205     GetSwitchValueAsInt(*cmd, switches::kMaxUntiledLayerWidth, 1,
206                         std::numeric_limits<int>::max(),
207                         &max_untiled_layer_width);
208   }
209   int max_untiled_layer_height = settings.max_untiled_layer_size.height();
210   if (cmd->HasSwitch(switches::kMaxUntiledLayerHeight)) {
211     GetSwitchValueAsInt(*cmd, switches::kMaxUntiledLayerHeight, 1,
212                         std::numeric_limits<int>::max(),
213                         &max_untiled_layer_height);
214   }
215
216   settings.max_untiled_layer_size = gfx::Size(max_untiled_layer_width,
217                                            max_untiled_layer_height);
218
219   RenderThreadImpl* render_thread = RenderThreadImpl::current();
220   // render_thread may be NULL in tests.
221   if (render_thread) {
222     settings.impl_side_painting =
223         render_thread->is_impl_side_painting_enabled();
224     settings.gpu_rasterization_forced =
225         render_thread->is_gpu_rasterization_forced();
226     settings.gpu_rasterization_enabled =
227         render_thread->is_gpu_rasterization_enabled();
228     settings.create_low_res_tiling = render_thread->is_low_res_tiling_enabled();
229     settings.can_use_lcd_text = render_thread->is_lcd_text_enabled();
230     settings.use_distance_field_text =
231         render_thread->is_distance_field_text_enabled();
232     settings.use_zero_copy = render_thread->is_zero_copy_enabled();
233     settings.use_one_copy = render_thread->is_one_copy_enabled();
234   }
235
236   if (cmd->HasSwitch(switches::kEnableBleedingEdgeRenderingFastPaths)) {
237     settings.recording_mode = cc::LayerTreeSettings::RecordWithSkRecord;
238   }
239
240   settings.calculate_top_controls_position =
241       cmd->HasSwitch(cc::switches::kEnableTopControlsPositionCalculation);
242   if (cmd->HasSwitch(cc::switches::kTopControlsHeight)) {
243     std::string controls_height_str =
244         cmd->GetSwitchValueASCII(cc::switches::kTopControlsHeight);
245     double controls_height;
246     if (base::StringToDouble(controls_height_str, &controls_height) &&
247         controls_height > 0)
248       settings.top_controls_height = controls_height;
249   }
250
251   if (settings.calculate_top_controls_position &&
252       settings.top_controls_height <= 0) {
253     DCHECK(false)
254         << "Top controls repositioning enabled without valid height set.";
255     settings.calculate_top_controls_position = false;
256   }
257
258   if (cmd->HasSwitch(cc::switches::kTopControlsShowThreshold)) {
259       std::string top_threshold_str =
260           cmd->GetSwitchValueASCII(cc::switches::kTopControlsShowThreshold);
261       double show_threshold;
262       if (base::StringToDouble(top_threshold_str, &show_threshold) &&
263           show_threshold >= 0.f && show_threshold <= 1.f)
264         settings.top_controls_show_threshold = show_threshold;
265   }
266
267   if (cmd->HasSwitch(cc::switches::kTopControlsHideThreshold)) {
268       std::string top_threshold_str =
269           cmd->GetSwitchValueASCII(cc::switches::kTopControlsHideThreshold);
270       double hide_threshold;
271       if (base::StringToDouble(top_threshold_str, &hide_threshold) &&
272           hide_threshold >= 0.f && hide_threshold <= 1.f)
273         settings.top_controls_hide_threshold = hide_threshold;
274   }
275
276   settings.use_pinch_virtual_viewport =
277       cmd->HasSwitch(cc::switches::kEnablePinchVirtualViewport);
278   settings.allow_antialiasing &=
279       !cmd->HasSwitch(cc::switches::kDisableCompositedAntialiasing);
280
281   // These flags should be mirrored by UI versions in ui/compositor/.
282   settings.initial_debug_state.show_debug_borders =
283       cmd->HasSwitch(cc::switches::kShowCompositedLayerBorders);
284   settings.initial_debug_state.show_fps_counter =
285       cmd->HasSwitch(cc::switches::kShowFPSCounter);
286   settings.initial_debug_state.show_layer_animation_bounds_rects =
287       cmd->HasSwitch(cc::switches::kShowLayerAnimationBounds);
288   settings.initial_debug_state.show_paint_rects =
289       cmd->HasSwitch(switches::kShowPaintRects);
290   settings.initial_debug_state.show_property_changed_rects =
291       cmd->HasSwitch(cc::switches::kShowPropertyChangedRects);
292   settings.initial_debug_state.show_surface_damage_rects =
293       cmd->HasSwitch(cc::switches::kShowSurfaceDamageRects);
294   settings.initial_debug_state.show_screen_space_rects =
295       cmd->HasSwitch(cc::switches::kShowScreenSpaceRects);
296   settings.initial_debug_state.show_replica_screen_space_rects =
297       cmd->HasSwitch(cc::switches::kShowReplicaScreenSpaceRects);
298   settings.initial_debug_state.show_occluding_rects =
299       cmd->HasSwitch(cc::switches::kShowOccludingRects);
300   settings.initial_debug_state.show_non_occluding_rects =
301       cmd->HasSwitch(cc::switches::kShowNonOccludingRects);
302
303   settings.initial_debug_state.SetRecordRenderingStats(
304       cmd->HasSwitch(cc::switches::kEnableGpuBenchmarking));
305
306   if (cmd->HasSwitch(cc::switches::kSlowDownRasterScaleFactor)) {
307     const int kMinSlowDownScaleFactor = 0;
308     const int kMaxSlowDownScaleFactor = INT_MAX;
309     GetSwitchValueAsInt(
310         *cmd,
311         cc::switches::kSlowDownRasterScaleFactor,
312         kMinSlowDownScaleFactor,
313         kMaxSlowDownScaleFactor,
314         &settings.initial_debug_state.slow_down_raster_scale_factor);
315   }
316
317   if (cmd->HasSwitch(cc::switches::kMaxTilesForInterestArea)) {
318     int max_tiles_for_interest_area;
319     if (GetSwitchValueAsInt(*cmd,
320                             cc::switches::kMaxTilesForInterestArea,
321                             1, std::numeric_limits<int>::max(),
322                             &max_tiles_for_interest_area))
323       settings.max_tiles_for_interest_area = max_tiles_for_interest_area;
324   }
325
326   if (cmd->HasSwitch(cc::switches::kMaxUnusedResourceMemoryUsagePercentage)) {
327     int max_unused_resource_memory_percentage;
328     if (GetSwitchValueAsInt(
329             *cmd,
330             cc::switches::kMaxUnusedResourceMemoryUsagePercentage,
331             0, 100,
332             &max_unused_resource_memory_percentage)) {
333       settings.max_unused_resource_memory_percentage =
334           max_unused_resource_memory_percentage;
335     }
336   }
337
338   settings.strict_layer_property_change_checking =
339       cmd->HasSwitch(cc::switches::kStrictLayerPropertyChangeChecking);
340
341 #if defined(OS_ANDROID)
342   SynchronousCompositorFactory* synchronous_compositor_factory =
343       SynchronousCompositorFactory::GetInstance();
344
345   settings.using_synchronous_renderer_compositor =
346       synchronous_compositor_factory;
347   settings.record_full_layer =
348       synchronous_compositor_factory &&
349       synchronous_compositor_factory->RecordFullLayer();
350   settings.report_overscroll_only_for_scrollable_axes =
351       !synchronous_compositor_factory;
352   settings.max_partial_texture_updates = 0;
353   if (synchronous_compositor_factory) {
354     // Android WebView uses system scrollbars, so make ours invisible.
355     settings.scrollbar_animator = cc::LayerTreeSettings::NoAnimator;
356     settings.solid_color_scrollbar_color = SK_ColorTRANSPARENT;
357   } else {
358     settings.scrollbar_animator = cc::LayerTreeSettings::LinearFade;
359     settings.scrollbar_fade_delay_ms = 300;
360     settings.scrollbar_fade_duration_ms = 300;
361     settings.solid_color_scrollbar_color = SkColorSetARGB(128, 128, 128, 128);
362   }
363   settings.highp_threshold_min = 2048;
364   // Android WebView handles root layer flings itself.
365   settings.ignore_root_layer_flings =
366       synchronous_compositor_factory;
367   // Memory policy on Android WebView does not depend on whether device is
368   // low end, so always use default policy.
369   bool is_low_end_device =
370       base::SysInfo::IsLowEndDevice() && !synchronous_compositor_factory;
371   // RGBA_4444 textures are only enabled for low end devices
372   // and are disabled for Android WebView as it doesn't support the format.
373   settings.use_rgba_4444_textures = is_low_end_device;
374   if (is_low_end_device) {
375     // On low-end we want to be very carefull about killing other
376     // apps. So initially we use 50% more memory to avoid flickering
377     // or raster-on-demand.
378     settings.max_memory_for_prepaint_percentage = 67;
379   } else {
380     // On other devices we have increased memory excessively to avoid
381     // raster-on-demand already, so now we reserve 50% _only_ to avoid
382     // raster-on-demand, and use 50% of the memory otherwise.
383     settings.max_memory_for_prepaint_percentage = 50;
384   }
385   // Webview does not own the surface so should not clear it.
386   settings.should_clear_root_render_pass =
387       !synchronous_compositor_factory;
388
389 #elif !defined(OS_MACOSX)
390   if (ui::IsOverlayScrollbarEnabled()) {
391 #if defined(OS_TIZEN)
392     // Tizen fades out the scrollbar after contents interaction ends.
393     settings.scrollbar_animator = cc::LayerTreeSettings::LinearFade;
394 #else
395     settings.scrollbar_animator = cc::LayerTreeSettings::Thinning;
396 #endif
397     settings.solid_color_scrollbar_color = SkColorSetARGB(128, 128, 128, 128);
398   } else if (cmd->HasSwitch(cc::switches::kEnablePinchVirtualViewport)) {
399     // use_pinch_zoom_scrollbars is only true on desktop when non-overlay
400     // scrollbars are in use.
401     settings.use_pinch_zoom_scrollbars = true;
402     settings.scrollbar_animator = cc::LayerTreeSettings::LinearFade;
403     settings.solid_color_scrollbar_color = SkColorSetARGB(128, 128, 128, 128);
404   }
405   settings.scrollbar_fade_delay_ms = 500;
406   settings.scrollbar_fade_duration_ms = 300;
407 #endif
408
409   compositor->Initialize(settings);
410
411   return compositor.Pass();
412 }
413
414 RenderWidgetCompositor::RenderWidgetCompositor(RenderWidget* widget,
415                                                bool threaded)
416     : threaded_(threaded),
417       suppress_schedule_composite_(false),
418       widget_(widget) {
419 }
420
421 RenderWidgetCompositor::~RenderWidgetCompositor() {}
422
423 const base::WeakPtr<cc::InputHandler>&
424 RenderWidgetCompositor::GetInputHandler() {
425   return layer_tree_host_->GetInputHandler();
426 }
427
428 void RenderWidgetCompositor::SetSuppressScheduleComposite(bool suppress) {
429   if (suppress_schedule_composite_ == suppress)
430     return;
431
432   if (suppress)
433     TRACE_EVENT_ASYNC_BEGIN0(
434         "gpu", "RenderWidgetCompositor::SetSuppressScheduleComposite", this);
435   else
436     TRACE_EVENT_ASYNC_END0(
437         "gpu", "RenderWidgetCompositor::SetSuppressScheduleComposite", this);
438   suppress_schedule_composite_ = suppress;
439 }
440
441 bool RenderWidgetCompositor::BeginMainFrameRequested() const {
442   return layer_tree_host_->BeginMainFrameRequested();
443 }
444
445 void RenderWidgetCompositor::UpdateAnimations(base::TimeTicks time) {
446   layer_tree_host_->UpdateClientAnimations(time);
447 }
448
449 void RenderWidgetCompositor::SetNeedsDisplayOnAllLayers() {
450   layer_tree_host_->SetNeedsDisplayOnAllLayers();
451 }
452
453 void RenderWidgetCompositor::SetRasterizeOnlyVisibleContent() {
454   cc::LayerTreeDebugState current = layer_tree_host_->debug_state();
455   current.rasterize_only_visible_content = true;
456   layer_tree_host_->SetDebugState(current);
457 }
458
459 void RenderWidgetCompositor::UpdateTopControlsState(
460     cc::TopControlsState constraints,
461     cc::TopControlsState current,
462     bool animate) {
463   layer_tree_host_->UpdateTopControlsState(constraints,
464                                            current,
465                                            animate);
466 }
467
468 void RenderWidgetCompositor::SetOverdrawBottomHeight(
469     float overdraw_bottom_height) {
470   layer_tree_host_->SetOverdrawBottomHeight(overdraw_bottom_height);
471 }
472
473 void RenderWidgetCompositor::SetNeedsRedrawRect(gfx::Rect damage_rect) {
474   layer_tree_host_->SetNeedsRedrawRect(damage_rect);
475 }
476
477 void RenderWidgetCompositor::SetNeedsForcedRedraw() {
478   layer_tree_host_->SetNextCommitForcesRedraw();
479   setNeedsAnimate();
480 }
481
482 scoped_ptr<cc::SwapPromiseMonitor>
483 RenderWidgetCompositor::CreateLatencyInfoSwapPromiseMonitor(
484     ui::LatencyInfo* latency) {
485   return scoped_ptr<cc::SwapPromiseMonitor>(
486       new cc::LatencyInfoSwapPromiseMonitor(
487           latency, layer_tree_host_.get(), NULL));
488 }
489
490 void RenderWidgetCompositor::QueueSwapPromise(
491     scoped_ptr<cc::SwapPromise> swap_promise) {
492   layer_tree_host_->QueueSwapPromise(swap_promise.Pass());
493 }
494
495 int RenderWidgetCompositor::GetLayerTreeId() const {
496   return layer_tree_host_->id();
497 }
498
499 int RenderWidgetCompositor::GetSourceFrameNumber() const {
500   return layer_tree_host_->source_frame_number();
501 }
502
503 void RenderWidgetCompositor::SetNeedsCommit() {
504   layer_tree_host_->SetNeedsCommit();
505 }
506
507 void RenderWidgetCompositor::NotifyInputThrottledUntilCommit() {
508   layer_tree_host_->NotifyInputThrottledUntilCommit();
509 }
510
511 const cc::Layer* RenderWidgetCompositor::GetRootLayer() const {
512   return layer_tree_host_->root_layer();
513 }
514
515 int RenderWidgetCompositor::ScheduleMicroBenchmark(
516     const std::string& name,
517     scoped_ptr<base::Value> value,
518     const base::Callback<void(scoped_ptr<base::Value>)>& callback) {
519   return layer_tree_host_->ScheduleMicroBenchmark(name, value.Pass(), callback);
520 }
521
522 bool RenderWidgetCompositor::SendMessageToMicroBenchmark(
523     int id,
524     scoped_ptr<base::Value> value) {
525   return layer_tree_host_->SendMessageToMicroBenchmark(id, value.Pass());
526 }
527
528 void RenderWidgetCompositor::Initialize(cc::LayerTreeSettings settings) {
529   scoped_refptr<base::MessageLoopProxy> compositor_message_loop_proxy;
530   RenderThreadImpl* render_thread = RenderThreadImpl::current();
531   cc::SharedBitmapManager* shared_bitmap_manager = NULL;
532   // render_thread may be NULL in tests.
533   if (render_thread) {
534     compositor_message_loop_proxy =
535         render_thread->compositor_message_loop_proxy();
536     shared_bitmap_manager = render_thread->shared_bitmap_manager();
537   }
538   if (compositor_message_loop_proxy.get()) {
539     layer_tree_host_ = cc::LayerTreeHost::CreateThreaded(
540         this,
541         shared_bitmap_manager,
542         settings,
543         base::MessageLoopProxy::current(),
544         compositor_message_loop_proxy);
545   } else {
546     layer_tree_host_ = cc::LayerTreeHost::CreateSingleThreaded(
547         this,
548         this,
549         shared_bitmap_manager,
550         settings,
551         base::MessageLoopProxy::current());
552   }
553   DCHECK(layer_tree_host_);
554 }
555
556 void RenderWidgetCompositor::setSurfaceReady() {
557   layer_tree_host_->SetLayerTreeHostClientReady();
558 }
559
560 void RenderWidgetCompositor::setRootLayer(const blink::WebLayer& layer) {
561   layer_tree_host_->SetRootLayer(
562       static_cast<const WebLayerImpl*>(&layer)->layer());
563 }
564
565 void RenderWidgetCompositor::clearRootLayer() {
566   layer_tree_host_->SetRootLayer(scoped_refptr<cc::Layer>());
567 }
568
569 void RenderWidgetCompositor::setViewportSize(
570     const WebSize&,
571     const WebSize& device_viewport_size) {
572   layer_tree_host_->SetViewportSize(device_viewport_size);
573 }
574
575 void RenderWidgetCompositor::setViewportSize(
576     const WebSize& device_viewport_size) {
577   layer_tree_host_->SetViewportSize(device_viewport_size);
578 }
579
580 WebSize RenderWidgetCompositor::layoutViewportSize() const {
581   return layer_tree_host_->device_viewport_size();
582 }
583
584 WebSize RenderWidgetCompositor::deviceViewportSize() const {
585   return layer_tree_host_->device_viewport_size();
586 }
587
588 WebFloatPoint RenderWidgetCompositor::adjustEventPointForPinchZoom(
589     const WebFloatPoint& point) const {
590   return point;
591 }
592
593 void RenderWidgetCompositor::setDeviceScaleFactor(float device_scale) {
594   layer_tree_host_->SetDeviceScaleFactor(device_scale);
595 }
596
597 float RenderWidgetCompositor::deviceScaleFactor() const {
598   return layer_tree_host_->device_scale_factor();
599 }
600
601 void RenderWidgetCompositor::setBackgroundColor(blink::WebColor color) {
602   layer_tree_host_->set_background_color(color);
603 }
604
605 void RenderWidgetCompositor::setHasTransparentBackground(bool transparent) {
606   layer_tree_host_->set_has_transparent_background(transparent);
607 }
608
609 void RenderWidgetCompositor::setOverhangBitmap(const SkBitmap& bitmap) {
610   layer_tree_host_->SetOverhangBitmap(bitmap);
611 }
612
613 void RenderWidgetCompositor::setVisible(bool visible) {
614   layer_tree_host_->SetVisible(visible);
615 }
616
617 void RenderWidgetCompositor::setPageScaleFactorAndLimits(
618     float page_scale_factor, float minimum, float maximum) {
619   layer_tree_host_->SetPageScaleFactorAndLimits(
620       page_scale_factor, minimum, maximum);
621 }
622
623 void RenderWidgetCompositor::startPageScaleAnimation(
624     const blink::WebPoint& destination,
625     bool use_anchor,
626     float new_page_scale,
627     double duration_sec) {
628   base::TimeDelta duration = base::TimeDelta::FromMicroseconds(
629       duration_sec * base::Time::kMicrosecondsPerSecond);
630   layer_tree_host_->StartPageScaleAnimation(
631       gfx::Vector2d(destination.x, destination.y),
632       use_anchor,
633       new_page_scale,
634       duration);
635 }
636
637 void RenderWidgetCompositor::heuristicsForGpuRasterizationUpdated(
638     bool matches_heuristics) {
639   layer_tree_host_->SetHasGpuRasterizationTrigger(matches_heuristics);
640 }
641
642 void RenderWidgetCompositor::setNeedsAnimate() {
643   layer_tree_host_->SetNeedsAnimate();
644 }
645
646 bool RenderWidgetCompositor::commitRequested() const {
647   return layer_tree_host_->CommitRequested();
648 }
649
650 void RenderWidgetCompositor::didStopFlinging() {
651   layer_tree_host_->DidStopFlinging();
652 }
653
654 void RenderWidgetCompositor::registerForAnimations(blink::WebLayer* layer) {
655   cc::Layer* cc_layer = static_cast<WebLayerImpl*>(layer)->layer();
656   cc_layer->layer_animation_controller()->SetAnimationRegistrar(
657       layer_tree_host_->animation_registrar());
658 }
659
660 void RenderWidgetCompositor::registerViewportLayers(
661     const blink::WebLayer* pageScaleLayer,
662     const blink::WebLayer* innerViewportScrollLayer,
663     const blink::WebLayer* outerViewportScrollLayer) {
664   layer_tree_host_->RegisterViewportLayers(
665       static_cast<const WebLayerImpl*>(pageScaleLayer)->layer(),
666       static_cast<const WebLayerImpl*>(innerViewportScrollLayer)->layer(),
667       // The outer viewport layer will only exist when using pinch virtual
668       // viewports.
669       outerViewportScrollLayer
670           ? static_cast<const WebLayerImpl*>(outerViewportScrollLayer)->layer()
671           : NULL);
672 }
673
674 void RenderWidgetCompositor::clearViewportLayers() {
675   layer_tree_host_->RegisterViewportLayers(scoped_refptr<cc::Layer>(),
676                                            scoped_refptr<cc::Layer>(),
677                                            scoped_refptr<cc::Layer>());
678 }
679
680 void RenderWidgetCompositor::registerSelection(
681     const blink::WebSelectionBound& start,
682     const blink::WebSelectionBound& end) {
683   layer_tree_host_->RegisterSelection(ConvertWebSelectionBound(start),
684                                       ConvertWebSelectionBound(end));
685 }
686
687 void RenderWidgetCompositor::clearSelection() {
688   cc::LayerSelectionBound empty_selection;
689   layer_tree_host_->RegisterSelection(empty_selection, empty_selection);
690 }
691
692 void CompositeAndReadbackAsyncCallback(
693     blink::WebCompositeAndReadbackAsyncCallback* callback,
694     scoped_ptr<cc::CopyOutputResult> result) {
695   if (result->HasBitmap()) {
696     scoped_ptr<SkBitmap> result_bitmap = result->TakeBitmap();
697     callback->didCompositeAndReadback(*result_bitmap);
698   } else {
699     callback->didCompositeAndReadback(SkBitmap());
700   }
701 }
702
703 void RenderWidgetCompositor::compositeAndReadbackAsync(
704     blink::WebCompositeAndReadbackAsyncCallback* callback) {
705   DCHECK(layer_tree_host_->root_layer());
706   scoped_ptr<cc::CopyOutputRequest> request =
707       cc::CopyOutputRequest::CreateBitmapRequest(
708           base::Bind(&CompositeAndReadbackAsyncCallback, callback));
709   layer_tree_host_->root_layer()->RequestCopyOfOutput(request.Pass());
710   if (!threaded_) {
711     widget_->webwidget()->animate(0.0);
712     widget_->webwidget()->layout();
713     layer_tree_host_->Composite(gfx::FrameTime::Now());
714   }
715 }
716
717 void RenderWidgetCompositor::finishAllRendering() {
718   layer_tree_host_->FinishAllRendering();
719 }
720
721 void RenderWidgetCompositor::setDeferCommits(bool defer_commits) {
722   layer_tree_host_->SetDeferCommits(defer_commits);
723 }
724
725 void RenderWidgetCompositor::setShowFPSCounter(bool show) {
726   cc::LayerTreeDebugState debug_state = layer_tree_host_->debug_state();
727   debug_state.show_fps_counter = show;
728   layer_tree_host_->SetDebugState(debug_state);
729 }
730
731 void RenderWidgetCompositor::setShowPaintRects(bool show) {
732   cc::LayerTreeDebugState debug_state = layer_tree_host_->debug_state();
733   debug_state.show_paint_rects = show;
734   layer_tree_host_->SetDebugState(debug_state);
735 }
736
737 void RenderWidgetCompositor::setShowDebugBorders(bool show) {
738   cc::LayerTreeDebugState debug_state = layer_tree_host_->debug_state();
739   debug_state.show_debug_borders = show;
740   layer_tree_host_->SetDebugState(debug_state);
741 }
742
743 void RenderWidgetCompositor::setContinuousPaintingEnabled(bool enabled) {
744   cc::LayerTreeDebugState debug_state = layer_tree_host_->debug_state();
745   debug_state.continuous_painting = enabled;
746   layer_tree_host_->SetDebugState(debug_state);
747 }
748
749 void RenderWidgetCompositor::setShowScrollBottleneckRects(bool show) {
750   cc::LayerTreeDebugState debug_state = layer_tree_host_->debug_state();
751   debug_state.show_touch_event_handler_rects = show;
752   debug_state.show_wheel_event_handler_rects = show;
753   debug_state.show_non_fast_scrollable_rects = show;
754   layer_tree_host_->SetDebugState(debug_state);
755 }
756
757 void RenderWidgetCompositor::WillBeginMainFrame(int frame_id) {
758   widget_->InstrumentWillBeginFrame(frame_id);
759   widget_->willBeginCompositorFrame();
760 }
761
762 void RenderWidgetCompositor::DidBeginMainFrame() {
763   widget_->InstrumentDidBeginFrame();
764 }
765
766 void RenderWidgetCompositor::Animate(base::TimeTicks frame_begin_time) {
767   widget_->webwidget()->animate(
768       (frame_begin_time - base::TimeTicks()).InSecondsF());
769 }
770
771 void RenderWidgetCompositor::Layout() {
772   widget_->webwidget()->layout();
773 }
774
775 void RenderWidgetCompositor::ApplyScrollAndScale(
776     const gfx::Vector2d& scroll_delta,
777     float page_scale) {
778   widget_->webwidget()->applyScrollAndScale(scroll_delta, page_scale);
779 }
780
781 scoped_ptr<cc::OutputSurface> RenderWidgetCompositor::CreateOutputSurface(
782     bool fallback) {
783   return widget_->CreateOutputSurface(fallback);
784 }
785
786 void RenderWidgetCompositor::DidInitializeOutputSurface() {
787 }
788
789 void RenderWidgetCompositor::WillCommit() {
790   widget_->InstrumentWillComposite();
791 }
792
793 void RenderWidgetCompositor::DidCommit() {
794   widget_->DidCommitCompositorFrame();
795   widget_->didBecomeReadyForAdditionalInput();
796 }
797
798 void RenderWidgetCompositor::DidCommitAndDrawFrame() {
799   widget_->didCommitAndDrawCompositorFrame();
800 }
801
802 void RenderWidgetCompositor::DidCompleteSwapBuffers() {
803   widget_->didCompleteSwapBuffers();
804   if (!threaded_)
805     widget_->OnSwapBuffersComplete();
806 }
807
808 void RenderWidgetCompositor::ScheduleComposite() {
809   if (!suppress_schedule_composite_)
810     widget_->scheduleComposite();
811 }
812
813 void RenderWidgetCompositor::ScheduleAnimation() {
814   widget_->scheduleAnimation();
815 }
816
817 void RenderWidgetCompositor::DidPostSwapBuffers() {
818   widget_->OnSwapBuffersPosted();
819 }
820
821 void RenderWidgetCompositor::DidAbortSwapBuffers() {
822   widget_->OnSwapBuffersAborted();
823 }
824
825 void RenderWidgetCompositor::RateLimitSharedMainThreadContext() {
826   cc::ContextProvider* provider =
827       RenderThreadImpl::current()->SharedMainThreadContextProvider().get();
828   provider->ContextGL()->RateLimitOffscreenContextCHROMIUM();
829 }
830
831 }  // namespace content