Upstreaming browser/ui/uikit_ui_util from iOS.
[chromium-blink-merge.git] / content / renderer / gpu / render_widget_compositor.cc
blob942470b580592b7a038a6335420b56b0a19f6de9
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.
5 #include "content/renderer/gpu/render_widget_compositor.h"
7 #include <limits>
8 #include <string>
10 #include "base/command_line.h"
11 #include "base/location.h"
12 #include "base/logging.h"
13 #include "base/metrics/field_trial.h"
14 #include "base/single_thread_task_runner.h"
15 #include "base/strings/string_number_conversions.h"
16 #include "base/synchronization/lock.h"
17 #include "base/sys_info.h"
18 #include "base/thread_task_runner_handle.h"
19 #include "base/time/time.h"
20 #include "base/values.h"
21 #include "cc/animation/animation_host.h"
22 #include "cc/animation/animation_timeline.h"
23 #include "cc/base/switches.h"
24 #include "cc/blink/web_compositor_animation_timeline_impl.h"
25 #include "cc/blink/web_layer_impl.h"
26 #include "cc/debug/layer_tree_debug_state.h"
27 #include "cc/debug/micro_benchmark.h"
28 #include "cc/input/layer_selection_bound.h"
29 #include "cc/layers/layer.h"
30 #include "cc/output/begin_frame_args.h"
31 #include "cc/output/copy_output_request.h"
32 #include "cc/output/copy_output_result.h"
33 #include "cc/output/latency_info_swap_promise.h"
34 #include "cc/output/swap_promise.h"
35 #include "cc/resources/single_release_callback.h"
36 #include "cc/scheduler/begin_frame_source.h"
37 #include "cc/trees/latency_info_swap_promise_monitor.h"
38 #include "cc/trees/layer_tree_host.h"
39 #include "components/scheduler/renderer/renderer_scheduler.h"
40 #include "content/common/content_switches_internal.h"
41 #include "content/common/gpu/client/context_provider_command_buffer.h"
42 #include "content/public/common/content_switches.h"
43 #include "content/renderer/input/input_handler_manager.h"
44 #include "gpu/command_buffer/client/gles2_interface.h"
45 #include "third_party/WebKit/public/platform/WebCompositeAndReadbackAsyncCallback.h"
46 #include "third_party/WebKit/public/platform/WebLayoutAndPaintAsyncCallback.h"
47 #include "third_party/WebKit/public/platform/WebSize.h"
48 #include "third_party/WebKit/public/web/WebKit.h"
49 #include "third_party/WebKit/public/web/WebRuntimeFeatures.h"
50 #include "third_party/WebKit/public/web/WebSelection.h"
51 #include "third_party/WebKit/public/web/WebWidget.h"
52 #include "ui/gl/gl_switches.h"
53 #include "ui/native_theme/native_theme_switches.h"
55 #if defined(OS_ANDROID)
56 #include "base/android/build_info.h"
57 #include "content/renderer/android/synchronous_compositor_factory.h"
58 #include "ui/gfx/android/device_display_info.h"
59 #endif
61 namespace base {
62 class Value;
65 namespace cc {
66 class Layer;
69 using blink::WebBeginFrameArgs;
70 using blink::WebFloatPoint;
71 using blink::WebRect;
72 using blink::WebSelection;
73 using blink::WebSize;
74 using blink::WebTopControlsState;
76 namespace content {
77 namespace {
79 bool GetSwitchValueAsInt(const base::CommandLine& command_line,
80 const std::string& switch_string,
81 int min_value,
82 int max_value,
83 int* result) {
84 std::string string_value = command_line.GetSwitchValueASCII(switch_string);
85 int int_value;
86 if (base::StringToInt(string_value, &int_value) &&
87 int_value >= min_value && int_value <= max_value) {
88 *result = int_value;
89 return true;
90 } else {
91 LOG(WARNING) << "Failed to parse switch " << switch_string << ": " <<
92 string_value;
93 return false;
97 cc::LayerSelectionBound ConvertWebSelectionBound(
98 const WebSelection& web_selection,
99 bool is_start) {
100 cc::LayerSelectionBound cc_bound;
101 if (web_selection.isNone())
102 return cc_bound;
104 const blink::WebSelectionBound& web_bound =
105 is_start ? web_selection.start() : web_selection.end();
106 DCHECK(web_bound.layerId);
107 cc_bound.type = cc::SELECTION_BOUND_CENTER;
108 if (web_selection.isRange()) {
109 if (is_start) {
110 cc_bound.type = web_bound.isTextDirectionRTL ? cc::SELECTION_BOUND_RIGHT
111 : cc::SELECTION_BOUND_LEFT;
112 } else {
113 cc_bound.type = web_bound.isTextDirectionRTL ? cc::SELECTION_BOUND_LEFT
114 : cc::SELECTION_BOUND_RIGHT;
117 cc_bound.layer_id = web_bound.layerId;
118 cc_bound.edge_top = gfx::Point(web_bound.edgeTopInLayer);
119 cc_bound.edge_bottom = gfx::Point(web_bound.edgeBottomInLayer);
120 return cc_bound;
123 cc::LayerSelection ConvertWebSelection(const WebSelection& web_selection) {
124 cc::LayerSelection cc_selection;
125 cc_selection.start = ConvertWebSelectionBound(web_selection, true);
126 cc_selection.end = ConvertWebSelectionBound(web_selection, false);
127 cc_selection.is_editable = web_selection.isEditable();
128 cc_selection.is_empty_text_form_control =
129 web_selection.isEmptyTextFormControl();
130 return cc_selection;
133 gfx::Size CalculateDefaultTileSize(RenderWidget* widget) {
134 int default_tile_size = 256;
135 #if defined(OS_ANDROID)
136 // TODO(epenner): unify this for all platforms if it
137 // makes sense (http://crbug.com/159524)
139 gfx::DeviceDisplayInfo info;
140 bool real_size_supported = true;
141 int display_width = info.GetPhysicalDisplayWidth();
142 int display_height = info.GetPhysicalDisplayHeight();
143 if (display_width == 0 || display_height == 0) {
144 real_size_supported = false;
145 display_width = info.GetDisplayWidth();
146 display_height = info.GetDisplayHeight();
149 int portrait_width = std::min(display_width, display_height);
150 int landscape_width = std::max(display_width, display_height);
152 if (real_size_supported) {
153 // Maximum HD dimensions should be 768x1280
154 // Maximum FHD dimensions should be 1200x1920
155 if (portrait_width > 768 || landscape_width > 1280)
156 default_tile_size = 384;
157 if (portrait_width > 1200 || landscape_width > 1920)
158 default_tile_size = 512;
160 // Adjust for some resolutions that barely straddle an extra
161 // tile when in portrait mode. This helps worst case scroll/raster
162 // by not needing a full extra tile for each row.
163 if (default_tile_size == 256 && portrait_width == 768)
164 default_tile_size += 32;
165 if (default_tile_size == 384 && portrait_width == 1200)
166 default_tile_size += 32;
167 } else {
168 // We don't know the exact resolution due to screen controls etc.
169 // So this just estimates the values above using tile counts.
170 int numTiles = (display_width * display_height) / (256 * 256);
171 if (numTiles > 16)
172 default_tile_size = 384;
173 if (numTiles >= 40)
174 default_tile_size = 512;
176 #elif defined(OS_CHROMEOS)
177 // Use 512 for high DPI (dsf=2.0f) devices.
178 if (widget->screen_info().deviceScaleFactor >= 2.0f)
179 default_tile_size = 512;
180 #endif
182 return gfx::Size(default_tile_size, default_tile_size);
185 // Check cc::TopControlsState, and blink::WebTopControlsState
186 // are kept in sync.
187 static_assert(int(blink::WebTopControlsBoth) == int(cc::BOTH),
188 "mismatching enums: BOTH");
189 static_assert(int(blink::WebTopControlsHidden) == int(cc::HIDDEN),
190 "mismatching enums: HIDDEN");
191 static_assert(int(blink::WebTopControlsShown) == int(cc::SHOWN),
192 "mismatching enums: SHOWN");
194 static cc::TopControlsState ConvertTopControlsState(
195 WebTopControlsState state) {
196 return static_cast<cc::TopControlsState>(state);
199 } // namespace
201 // static
202 scoped_ptr<RenderWidgetCompositor> RenderWidgetCompositor::Create(
203 RenderWidget* widget,
204 CompositorDependencies* compositor_deps) {
205 scoped_ptr<RenderWidgetCompositor> compositor(
206 new RenderWidgetCompositor(widget, compositor_deps));
207 compositor->Initialize();
208 return compositor;
211 RenderWidgetCompositor::RenderWidgetCompositor(
212 RenderWidget* widget,
213 CompositorDependencies* compositor_deps)
214 : num_failed_recreate_attempts_(0),
215 widget_(widget),
216 compositor_deps_(compositor_deps),
217 layout_and_paint_async_callback_(nullptr),
218 weak_factory_(this) {
221 void RenderWidgetCompositor::Initialize() {
222 base::CommandLine* cmd = base::CommandLine::ForCurrentProcess();
224 cc::LayerTreeSettings settings;
226 // For web contents, layer transforms should scale up the contents of layers
227 // to keep content always crisp when possible.
228 settings.layer_transforms_should_scale_layer_contents = true;
230 if (cmd->HasSwitch(switches::kDisableGpuVsync)) {
231 std::string display_vsync_string =
232 cmd->GetSwitchValueASCII(switches::kDisableGpuVsync);
233 if (display_vsync_string == "gpu") {
234 settings.renderer_settings.disable_display_vsync = true;
235 } else if (display_vsync_string == "beginframe") {
236 settings.wait_for_beginframe_interval = false;
237 } else {
238 settings.renderer_settings.disable_display_vsync = true;
239 settings.wait_for_beginframe_interval = false;
242 settings.main_frame_before_activation_enabled =
243 cmd->HasSwitch(cc::switches::kEnableMainFrameBeforeActivation) &&
244 !cmd->HasSwitch(cc::switches::kDisableMainFrameBeforeActivation);
245 settings.accelerated_animation_enabled =
246 !cmd->HasSwitch(cc::switches::kDisableThreadedAnimation);
247 const std::string slimming_group =
248 base::FieldTrialList::FindFullName("SlimmingPaint");
249 settings.use_display_lists =
250 (cmd->HasSwitch(switches::kEnableSlimmingPaint) ||
251 !cmd->HasSwitch(switches::kDisableSlimmingPaint)) &&
252 (slimming_group != "DisableSlimmingPaint");
253 if (cmd->HasSwitch(switches::kEnableCompositorAnimationTimelines)) {
254 settings.use_compositor_animation_timelines = true;
255 blink::WebRuntimeFeatures::enableCompositorAnimationTimelines(true);
258 settings.default_tile_size = CalculateDefaultTileSize(widget_);
259 if (cmd->HasSwitch(switches::kDefaultTileWidth)) {
260 int tile_width = 0;
261 GetSwitchValueAsInt(*cmd,
262 switches::kDefaultTileWidth,
264 std::numeric_limits<int>::max(),
265 &tile_width);
266 settings.default_tile_size.set_width(tile_width);
268 if (cmd->HasSwitch(switches::kDefaultTileHeight)) {
269 int tile_height = 0;
270 GetSwitchValueAsInt(*cmd,
271 switches::kDefaultTileHeight,
273 std::numeric_limits<int>::max(),
274 &tile_height);
275 settings.default_tile_size.set_height(tile_height);
278 int max_untiled_layer_width = settings.max_untiled_layer_size.width();
279 if (cmd->HasSwitch(switches::kMaxUntiledLayerWidth)) {
280 GetSwitchValueAsInt(*cmd, switches::kMaxUntiledLayerWidth, 1,
281 std::numeric_limits<int>::max(),
282 &max_untiled_layer_width);
284 int max_untiled_layer_height = settings.max_untiled_layer_size.height();
285 if (cmd->HasSwitch(switches::kMaxUntiledLayerHeight)) {
286 GetSwitchValueAsInt(*cmd, switches::kMaxUntiledLayerHeight, 1,
287 std::numeric_limits<int>::max(),
288 &max_untiled_layer_height);
291 settings.max_untiled_layer_size = gfx::Size(max_untiled_layer_width,
292 max_untiled_layer_height);
294 settings.gpu_rasterization_msaa_sample_count =
295 compositor_deps_->GetGpuRasterizationMSAASampleCount();
296 settings.gpu_rasterization_forced =
297 compositor_deps_->IsGpuRasterizationForced();
298 settings.gpu_rasterization_enabled =
299 compositor_deps_->IsGpuRasterizationEnabled();
301 settings.can_use_lcd_text = compositor_deps_->IsLcdTextEnabled();
302 settings.use_distance_field_text =
303 compositor_deps_->IsDistanceFieldTextEnabled();
304 settings.use_zero_copy = compositor_deps_->IsZeroCopyEnabled();
305 settings.use_one_copy = compositor_deps_->IsOneCopyEnabled();
306 settings.enable_elastic_overscroll =
307 compositor_deps_->IsElasticOverscrollEnabled();
308 settings.use_image_texture_target = compositor_deps_->GetImageTextureTarget();
309 settings.gather_pixel_refs = compositor_deps_->IsGatherPixelRefsEnabled();
311 if (cmd->HasSwitch(cc::switches::kTopControlsShowThreshold)) {
312 std::string top_threshold_str =
313 cmd->GetSwitchValueASCII(cc::switches::kTopControlsShowThreshold);
314 double show_threshold;
315 if (base::StringToDouble(top_threshold_str, &show_threshold) &&
316 show_threshold >= 0.f && show_threshold <= 1.f)
317 settings.top_controls_show_threshold = show_threshold;
320 if (cmd->HasSwitch(cc::switches::kTopControlsHideThreshold)) {
321 std::string top_threshold_str =
322 cmd->GetSwitchValueASCII(cc::switches::kTopControlsHideThreshold);
323 double hide_threshold;
324 if (base::StringToDouble(top_threshold_str, &hide_threshold) &&
325 hide_threshold >= 0.f && hide_threshold <= 1.f)
326 settings.top_controls_hide_threshold = hide_threshold;
329 settings.verify_property_trees =
330 cmd->HasSwitch(cc::switches::kEnablePropertyTreeVerification);
331 settings.renderer_settings.allow_antialiasing &=
332 !cmd->HasSwitch(cc::switches::kDisableCompositedAntialiasing);
333 // The means the renderer compositor has 2 possible modes:
334 // - Threaded compositing with a scheduler.
335 // - Single threaded compositing without a scheduler (for layout tests only).
336 // Using the scheduler in layout tests introduces additional composite steps
337 // that create flakiness.
338 settings.single_thread_proxy_scheduler = false;
340 // These flags should be mirrored by UI versions in ui/compositor/.
341 settings.initial_debug_state.show_debug_borders =
342 cmd->HasSwitch(cc::switches::kShowCompositedLayerBorders);
343 settings.initial_debug_state.show_fps_counter =
344 cmd->HasSwitch(cc::switches::kShowFPSCounter);
345 settings.initial_debug_state.show_layer_animation_bounds_rects =
346 cmd->HasSwitch(cc::switches::kShowLayerAnimationBounds);
347 settings.initial_debug_state.show_paint_rects =
348 cmd->HasSwitch(switches::kShowPaintRects);
349 settings.initial_debug_state.show_property_changed_rects =
350 cmd->HasSwitch(cc::switches::kShowPropertyChangedRects);
351 settings.initial_debug_state.show_surface_damage_rects =
352 cmd->HasSwitch(cc::switches::kShowSurfaceDamageRects);
353 settings.initial_debug_state.show_screen_space_rects =
354 cmd->HasSwitch(cc::switches::kShowScreenSpaceRects);
355 settings.initial_debug_state.show_replica_screen_space_rects =
356 cmd->HasSwitch(cc::switches::kShowReplicaScreenSpaceRects);
358 settings.initial_debug_state.SetRecordRenderingStats(
359 cmd->HasSwitch(cc::switches::kEnableGpuBenchmarking));
361 if (cmd->HasSwitch(cc::switches::kSlowDownRasterScaleFactor)) {
362 const int kMinSlowDownScaleFactor = 0;
363 const int kMaxSlowDownScaleFactor = INT_MAX;
364 GetSwitchValueAsInt(
365 *cmd,
366 cc::switches::kSlowDownRasterScaleFactor,
367 kMinSlowDownScaleFactor,
368 kMaxSlowDownScaleFactor,
369 &settings.initial_debug_state.slow_down_raster_scale_factor);
372 settings.invert_viewport_scroll_order =
373 cmd->HasSwitch(switches::kInvertViewportScrollOrder);
375 if (cmd->HasSwitch(cc::switches::kMaxUnusedResourceMemoryUsagePercentage)) {
376 int max_unused_resource_memory_percentage;
377 if (GetSwitchValueAsInt(
378 *cmd,
379 cc::switches::kMaxUnusedResourceMemoryUsagePercentage,
380 0, 100,
381 &max_unused_resource_memory_percentage)) {
382 settings.max_unused_resource_memory_percentage =
383 max_unused_resource_memory_percentage;
387 settings.strict_layer_property_change_checking =
388 cmd->HasSwitch(cc::switches::kStrictLayerPropertyChangeChecking);
390 #if defined(OS_ANDROID)
391 SynchronousCompositorFactory* synchronous_compositor_factory =
392 SynchronousCompositorFactory::GetInstance();
394 // We can't use GPU rasterization on low-end devices, because the Ganesh
395 // cache would consume too much memory.
396 if (base::SysInfo::IsLowEndDevice())
397 settings.gpu_rasterization_enabled = false;
398 settings.using_synchronous_renderer_compositor =
399 synchronous_compositor_factory;
400 settings.record_full_layer = widget_->DoesRecordFullLayer();
401 settings.max_partial_texture_updates = 0;
402 if (synchronous_compositor_factory) {
403 // Android WebView uses system scrollbars, so make ours invisible.
404 settings.scrollbar_animator = cc::LayerTreeSettings::NO_ANIMATOR;
405 settings.solid_color_scrollbar_color = SK_ColorTRANSPARENT;
406 } else {
407 settings.scrollbar_animator = cc::LayerTreeSettings::LINEAR_FADE;
408 settings.scrollbar_fade_delay_ms = 300;
409 settings.scrollbar_fade_resize_delay_ms = 2000;
410 settings.scrollbar_fade_duration_ms = 300;
411 settings.solid_color_scrollbar_color = SkColorSetARGB(128, 128, 128, 128);
413 settings.renderer_settings.highp_threshold_min = 2048;
414 // Android WebView handles root layer flings itself.
415 settings.ignore_root_layer_flings =
416 synchronous_compositor_factory;
417 // Memory policy on Android WebView does not depend on whether device is
418 // low end, so always use default policy.
419 bool use_low_memory_policy =
420 base::SysInfo::IsLowEndDevice() && !synchronous_compositor_factory;
421 // RGBA_4444 textures are only enabled for low end devices
422 // and are disabled for Android WebView as it doesn't support the format.
423 settings.renderer_settings.use_rgba_4444_textures = use_low_memory_policy;
424 if (use_low_memory_policy) {
425 // On low-end we want to be very carefull about killing other
426 // apps. So initially we use 50% more memory to avoid flickering
427 // or raster-on-demand.
428 settings.max_memory_for_prepaint_percentage = 67;
429 } else {
430 // On other devices we have increased memory excessively to avoid
431 // raster-on-demand already, so now we reserve 50% _only_ to avoid
432 // raster-on-demand, and use 50% of the memory otherwise.
433 settings.max_memory_for_prepaint_percentage = 50;
435 // Webview does not own the surface so should not clear it.
436 settings.renderer_settings.should_clear_root_render_pass =
437 !synchronous_compositor_factory;
439 // TODO(danakj): Only do this on low end devices.
440 settings.create_low_res_tiling = true;
442 settings.use_external_begin_frame_source = true;
444 #elif !defined(OS_MACOSX)
445 if (ui::IsOverlayScrollbarEnabled()) {
446 settings.scrollbar_animator = cc::LayerTreeSettings::THINNING;
447 settings.solid_color_scrollbar_color = SkColorSetARGB(128, 128, 128, 128);
448 } else {
449 settings.scrollbar_animator = cc::LayerTreeSettings::LINEAR_FADE;
450 settings.solid_color_scrollbar_color = SkColorSetARGB(128, 128, 128, 128);
452 settings.scrollbar_fade_delay_ms = 500;
453 settings.scrollbar_fade_resize_delay_ms = 500;
454 settings.scrollbar_fade_duration_ms = 300;
455 #endif
457 if (cmd->HasSwitch(switches::kEnableLowResTiling))
458 settings.create_low_res_tiling = true;
459 if (cmd->HasSwitch(switches::kDisableLowResTiling))
460 settings.create_low_res_tiling = false;
461 if (cmd->HasSwitch(cc::switches::kEnableBeginFrameScheduling))
462 settings.use_external_begin_frame_source = true;
464 if (widget_->for_oopif()) {
465 // TODO(simonhong): Apply BeginFrame scheduling for OOPIF.
466 // See crbug.com/471411.
467 settings.use_external_begin_frame_source = false;
470 scoped_refptr<base::SingleThreadTaskRunner> compositor_thread_task_runner =
471 compositor_deps_->GetCompositorImplThreadTaskRunner();
472 scoped_refptr<base::SingleThreadTaskRunner>
473 main_thread_compositor_task_runner =
474 compositor_deps_->GetCompositorMainThreadTaskRunner();
475 cc::SharedBitmapManager* shared_bitmap_manager =
476 compositor_deps_->GetSharedBitmapManager();
477 gpu::GpuMemoryBufferManager* gpu_memory_buffer_manager =
478 compositor_deps_->GetGpuMemoryBufferManager();
479 cc::TaskGraphRunner* task_graph_runner =
480 compositor_deps_->GetTaskGraphRunner();
482 scoped_ptr<cc::BeginFrameSource> external_begin_frame_source;
483 if (settings.use_external_begin_frame_source) {
484 external_begin_frame_source =
485 compositor_deps_->CreateExternalBeginFrameSource(widget_->routing_id());
488 cc::LayerTreeHost::InitParams params;
489 params.client = this;
490 params.shared_bitmap_manager = shared_bitmap_manager;
491 params.gpu_memory_buffer_manager = gpu_memory_buffer_manager;
492 params.settings = &settings;
493 params.task_graph_runner = task_graph_runner;
494 params.main_task_runner = main_thread_compositor_task_runner;
495 params.external_begin_frame_source = external_begin_frame_source.Pass();
496 if (compositor_thread_task_runner.get()) {
497 layer_tree_host_ = cc::LayerTreeHost::CreateThreaded(
498 compositor_thread_task_runner, &params);
499 } else {
500 layer_tree_host_ = cc::LayerTreeHost::CreateSingleThreaded(this, &params);
502 DCHECK(layer_tree_host_);
505 RenderWidgetCompositor::~RenderWidgetCompositor() {}
507 const base::WeakPtr<cc::InputHandler>&
508 RenderWidgetCompositor::GetInputHandler() {
509 return layer_tree_host_->GetInputHandler();
512 bool RenderWidgetCompositor::BeginMainFrameRequested() const {
513 return layer_tree_host_->BeginMainFrameRequested();
516 void RenderWidgetCompositor::SetNeedsDisplayOnAllLayers() {
517 layer_tree_host_->SetNeedsDisplayOnAllLayers();
520 void RenderWidgetCompositor::SetRasterizeOnlyVisibleContent() {
521 cc::LayerTreeDebugState current = layer_tree_host_->debug_state();
522 current.rasterize_only_visible_content = true;
523 layer_tree_host_->SetDebugState(current);
526 void RenderWidgetCompositor::SetNeedsRedrawRect(gfx::Rect damage_rect) {
527 layer_tree_host_->SetNeedsRedrawRect(damage_rect);
530 void RenderWidgetCompositor::SetNeedsForcedRedraw() {
531 layer_tree_host_->SetNextCommitForcesRedraw();
532 setNeedsAnimate();
535 scoped_ptr<cc::SwapPromiseMonitor>
536 RenderWidgetCompositor::CreateLatencyInfoSwapPromiseMonitor(
537 ui::LatencyInfo* latency) {
538 return scoped_ptr<cc::SwapPromiseMonitor>(
539 new cc::LatencyInfoSwapPromiseMonitor(
540 latency, layer_tree_host_.get(), NULL));
543 void RenderWidgetCompositor::QueueSwapPromise(
544 scoped_ptr<cc::SwapPromise> swap_promise) {
545 layer_tree_host_->QueueSwapPromise(swap_promise.Pass());
548 int RenderWidgetCompositor::GetSourceFrameNumber() const {
549 return layer_tree_host_->source_frame_number();
552 void RenderWidgetCompositor::SetNeedsUpdateLayers() {
553 layer_tree_host_->SetNeedsUpdateLayers();
556 void RenderWidgetCompositor::SetNeedsCommit() {
557 layer_tree_host_->SetNeedsCommit();
560 void RenderWidgetCompositor::NotifyInputThrottledUntilCommit() {
561 layer_tree_host_->NotifyInputThrottledUntilCommit();
564 const cc::Layer* RenderWidgetCompositor::GetRootLayer() const {
565 return layer_tree_host_->root_layer();
568 int RenderWidgetCompositor::ScheduleMicroBenchmark(
569 const std::string& name,
570 scoped_ptr<base::Value> value,
571 const base::Callback<void(scoped_ptr<base::Value>)>& callback) {
572 return layer_tree_host_->ScheduleMicroBenchmark(name, value.Pass(), callback);
575 bool RenderWidgetCompositor::SendMessageToMicroBenchmark(
576 int id,
577 scoped_ptr<base::Value> value) {
578 return layer_tree_host_->SendMessageToMicroBenchmark(id, value.Pass());
581 void RenderWidgetCompositor::StartCompositor() {
582 layer_tree_host_->SetLayerTreeHostClientReady();
585 void RenderWidgetCompositor::setRootLayer(const blink::WebLayer& layer) {
586 layer_tree_host_->SetRootLayer(
587 static_cast<const cc_blink::WebLayerImpl*>(&layer)->layer());
590 void RenderWidgetCompositor::clearRootLayer() {
591 layer_tree_host_->SetRootLayer(scoped_refptr<cc::Layer>());
594 void RenderWidgetCompositor::attachCompositorAnimationTimeline(
595 blink::WebCompositorAnimationTimeline* compositor_timeline) {
596 DCHECK(compositor_timeline);
597 DCHECK(layer_tree_host_->animation_host());
598 layer_tree_host_->animation_host()->AddAnimationTimeline(
599 static_cast<const cc_blink::WebCompositorAnimationTimelineImpl*>(
600 compositor_timeline)->animation_timeline());
603 void RenderWidgetCompositor::detachCompositorAnimationTimeline(
604 blink::WebCompositorAnimationTimeline* compositor_timeline) {
605 DCHECK(compositor_timeline);
606 DCHECK(layer_tree_host_->animation_host());
607 layer_tree_host_->animation_host()->RemoveAnimationTimeline(
608 static_cast<const cc_blink::WebCompositorAnimationTimelineImpl*>(
609 compositor_timeline)->animation_timeline());
612 void RenderWidgetCompositor::setViewportSize(
613 const WebSize&,
614 const WebSize& device_viewport_size) {
615 layer_tree_host_->SetViewportSize(device_viewport_size);
618 void RenderWidgetCompositor::setViewportSize(
619 const WebSize& device_viewport_size) {
620 layer_tree_host_->SetViewportSize(device_viewport_size);
623 WebSize RenderWidgetCompositor::layoutViewportSize() const {
624 return layer_tree_host_->device_viewport_size();
627 WebSize RenderWidgetCompositor::deviceViewportSize() const {
628 return layer_tree_host_->device_viewport_size();
631 WebFloatPoint RenderWidgetCompositor::adjustEventPointForPinchZoom(
632 const WebFloatPoint& point) const {
633 return point;
636 void RenderWidgetCompositor::setDeviceScaleFactor(float device_scale) {
637 layer_tree_host_->SetDeviceScaleFactor(device_scale);
640 float RenderWidgetCompositor::deviceScaleFactor() const {
641 return layer_tree_host_->device_scale_factor();
644 void RenderWidgetCompositor::setBackgroundColor(blink::WebColor color) {
645 layer_tree_host_->set_background_color(color);
648 void RenderWidgetCompositor::setHasTransparentBackground(bool transparent) {
649 layer_tree_host_->set_has_transparent_background(transparent);
652 void RenderWidgetCompositor::setVisible(bool visible) {
653 layer_tree_host_->SetVisible(visible);
656 void RenderWidgetCompositor::setPageScaleFactorAndLimits(
657 float page_scale_factor, float minimum, float maximum) {
658 layer_tree_host_->SetPageScaleFactorAndLimits(
659 page_scale_factor, minimum, maximum);
662 void RenderWidgetCompositor::startPageScaleAnimation(
663 const blink::WebPoint& destination,
664 bool use_anchor,
665 float new_page_scale,
666 double duration_sec) {
667 base::TimeDelta duration = base::TimeDelta::FromMicroseconds(
668 duration_sec * base::Time::kMicrosecondsPerSecond);
669 layer_tree_host_->StartPageScaleAnimation(
670 gfx::Vector2d(destination.x, destination.y),
671 use_anchor,
672 new_page_scale,
673 duration);
676 void RenderWidgetCompositor::heuristicsForGpuRasterizationUpdated(
677 bool matches_heuristics) {
678 layer_tree_host_->SetHasGpuRasterizationTrigger(matches_heuristics);
681 void RenderWidgetCompositor::setNeedsAnimate() {
682 layer_tree_host_->SetNeedsAnimate();
685 void RenderWidgetCompositor::didStopFlinging() {
686 layer_tree_host_->DidStopFlinging();
689 void RenderWidgetCompositor::registerForAnimations(blink::WebLayer* layer) {
690 cc::Layer* cc_layer = static_cast<cc_blink::WebLayerImpl*>(layer)->layer();
691 cc_layer->RegisterForAnimations(layer_tree_host_->animation_registrar());
694 void RenderWidgetCompositor::registerViewportLayers(
695 const blink::WebLayer* overscrollElasticityLayer,
696 const blink::WebLayer* pageScaleLayer,
697 const blink::WebLayer* innerViewportScrollLayer,
698 const blink::WebLayer* outerViewportScrollLayer) {
699 layer_tree_host_->RegisterViewportLayers(
700 // TODO(bokan): This check can probably be removed now, but it looks
701 // like overscroll elasticity may still be NULL until PinchViewport
702 // registers its layers.
703 // The scroll elasticity layer will only exist when using pinch virtual
704 // viewports.
705 overscrollElasticityLayer
706 ? static_cast<const cc_blink::WebLayerImpl*>(
707 overscrollElasticityLayer)->layer()
708 : NULL,
709 static_cast<const cc_blink::WebLayerImpl*>(pageScaleLayer)->layer(),
710 static_cast<const cc_blink::WebLayerImpl*>(innerViewportScrollLayer)
711 ->layer(),
712 // TODO(bokan): This check can probably be removed now, but it looks
713 // like overscroll elasticity may still be NULL until PinchViewport
714 // registers its layers.
715 // The outer viewport layer will only exist when using pinch virtual
716 // viewports.
717 outerViewportScrollLayer
718 ? static_cast<const cc_blink::WebLayerImpl*>(outerViewportScrollLayer)
719 ->layer()
720 : NULL);
723 void RenderWidgetCompositor::clearViewportLayers() {
724 layer_tree_host_->RegisterViewportLayers(
725 scoped_refptr<cc::Layer>(), scoped_refptr<cc::Layer>(),
726 scoped_refptr<cc::Layer>(), scoped_refptr<cc::Layer>());
729 void RenderWidgetCompositor::registerSelection(
730 const blink::WebSelection& selection) {
731 layer_tree_host_->RegisterSelection(ConvertWebSelection(selection));
734 void RenderWidgetCompositor::clearSelection() {
735 cc::LayerSelection empty_selection;
736 layer_tree_host_->RegisterSelection(empty_selection);
739 void CompositeAndReadbackAsyncCallback(
740 blink::WebCompositeAndReadbackAsyncCallback* callback,
741 scoped_ptr<cc::CopyOutputResult> result) {
742 if (result->HasBitmap()) {
743 scoped_ptr<SkBitmap> result_bitmap = result->TakeBitmap();
744 callback->didCompositeAndReadback(*result_bitmap);
745 } else {
746 callback->didCompositeAndReadback(SkBitmap());
750 bool RenderWidgetCompositor::CompositeIsSynchronous() const {
751 return !compositor_deps_->GetCompositorImplThreadTaskRunner().get() &&
752 !layer_tree_host_->settings().single_thread_proxy_scheduler;
755 void RenderWidgetCompositor::layoutAndPaintAsync(
756 blink::WebLayoutAndPaintAsyncCallback* callback) {
757 DCHECK(!temporary_copy_output_request_ && !layout_and_paint_async_callback_);
758 layout_and_paint_async_callback_ = callback;
760 if (CompositeIsSynchronous()) {
761 base::ThreadTaskRunnerHandle::Get()->PostTask(
762 FROM_HERE, base::Bind(&RenderWidgetCompositor::LayoutAndUpdateLayers,
763 weak_factory_.GetWeakPtr()));
764 } else {
765 layer_tree_host_->SetNeedsCommit();
769 void RenderWidgetCompositor::LayoutAndUpdateLayers() {
770 DCHECK(CompositeIsSynchronous());
771 layer_tree_host_->LayoutAndUpdateLayers();
772 InvokeLayoutAndPaintCallback();
775 void RenderWidgetCompositor::InvokeLayoutAndPaintCallback() {
776 if (!layout_and_paint_async_callback_)
777 return;
778 layout_and_paint_async_callback_->didLayoutAndPaint();
779 layout_and_paint_async_callback_ = nullptr;
782 void RenderWidgetCompositor::compositeAndReadbackAsync(
783 blink::WebCompositeAndReadbackAsyncCallback* callback) {
784 DCHECK(!temporary_copy_output_request_ && !layout_and_paint_async_callback_);
785 temporary_copy_output_request_ =
786 cc::CopyOutputRequest::CreateBitmapRequest(
787 base::Bind(&CompositeAndReadbackAsyncCallback, callback));
789 // Force a commit to happen. The temporary copy output request will
790 // be installed after layout which will happen as a part of the commit, for
791 // widgets that delay the creation of their output surface.
792 if (CompositeIsSynchronous()) {
793 base::ThreadTaskRunnerHandle::Get()->PostTask(
794 FROM_HERE, base::Bind(&RenderWidgetCompositor::SynchronouslyComposite,
795 weak_factory_.GetWeakPtr()));
796 } else {
797 layer_tree_host_->SetNeedsCommit();
801 void RenderWidgetCompositor::SynchronouslyComposite() {
802 DCHECK(CompositeIsSynchronous());
803 layer_tree_host_->Composite(base::TimeTicks::Now());
806 void RenderWidgetCompositor::finishAllRendering() {
807 layer_tree_host_->FinishAllRendering();
810 void RenderWidgetCompositor::setDeferCommits(bool defer_commits) {
811 layer_tree_host_->SetDeferCommits(defer_commits);
814 int RenderWidgetCompositor::layerTreeId() const {
815 return layer_tree_host_->id();
818 void RenderWidgetCompositor::setShowFPSCounter(bool show) {
819 cc::LayerTreeDebugState debug_state = layer_tree_host_->debug_state();
820 debug_state.show_fps_counter = show;
821 layer_tree_host_->SetDebugState(debug_state);
824 void RenderWidgetCompositor::setShowPaintRects(bool show) {
825 cc::LayerTreeDebugState debug_state = layer_tree_host_->debug_state();
826 debug_state.show_paint_rects = show;
827 layer_tree_host_->SetDebugState(debug_state);
830 void RenderWidgetCompositor::setShowDebugBorders(bool show) {
831 cc::LayerTreeDebugState debug_state = layer_tree_host_->debug_state();
832 debug_state.show_debug_borders = show;
833 layer_tree_host_->SetDebugState(debug_state);
836 void RenderWidgetCompositor::setContinuousPaintingEnabled(bool enabled) {
837 cc::LayerTreeDebugState debug_state = layer_tree_host_->debug_state();
838 debug_state.continuous_painting = enabled;
839 layer_tree_host_->SetDebugState(debug_state);
842 void RenderWidgetCompositor::setShowScrollBottleneckRects(bool show) {
843 cc::LayerTreeDebugState debug_state = layer_tree_host_->debug_state();
844 debug_state.show_touch_event_handler_rects = show;
845 debug_state.show_wheel_event_handler_rects = show;
846 debug_state.show_non_fast_scrollable_rects = show;
847 layer_tree_host_->SetDebugState(debug_state);
850 void RenderWidgetCompositor::updateTopControlsState(
851 WebTopControlsState constraints,
852 WebTopControlsState current,
853 bool animate) {
854 layer_tree_host_->UpdateTopControlsState(ConvertTopControlsState(constraints),
855 ConvertTopControlsState(current),
856 animate);
859 void RenderWidgetCompositor::setTopControlsHeight(float height, bool shrink) {
860 layer_tree_host_->SetTopControlsHeight(height, shrink);
863 void RenderWidgetCompositor::setTopControlsShownRatio(float ratio) {
864 layer_tree_host_->SetTopControlsShownRatio(ratio);
867 void RenderWidgetCompositor::setHidePinchScrollbarsNearMinScale(bool hide) {
868 layer_tree_host_->set_hide_pinch_scrollbars_near_min_scale(hide);
871 void RenderWidgetCompositor::WillBeginMainFrame() {
872 widget_->WillBeginCompositorFrame();
875 void RenderWidgetCompositor::DidBeginMainFrame() {
878 void RenderWidgetCompositor::BeginMainFrame(const cc::BeginFrameArgs& args) {
879 double frame_time_sec = (args.frame_time - base::TimeTicks()).InSecondsF();
880 double deadline_sec = (args.deadline - base::TimeTicks()).InSecondsF();
881 double interval_sec = args.interval.InSecondsF();
882 WebBeginFrameArgs web_begin_frame_args =
883 WebBeginFrameArgs(frame_time_sec, deadline_sec, interval_sec);
884 compositor_deps_->GetRendererScheduler()->WillBeginFrame(args);
885 widget_->webwidget()->beginFrame(web_begin_frame_args);
888 void RenderWidgetCompositor::BeginMainFrameNotExpectedSoon() {
889 compositor_deps_->GetRendererScheduler()->BeginFrameNotExpectedSoon();
892 void RenderWidgetCompositor::Layout() {
893 widget_->webwidget()->layout();
895 if (temporary_copy_output_request_) {
896 // For WebViewImpl, this will always have a root layer. For other widgets,
897 // the widget may be closed before servicing this request, so ignore it.
898 if (cc::Layer* root_layer = layer_tree_host_->root_layer()) {
899 root_layer->RequestCopyOfOutput(temporary_copy_output_request_.Pass());
900 } else {
901 temporary_copy_output_request_->SendEmptyResult();
902 temporary_copy_output_request_ = nullptr;
907 void RenderWidgetCompositor::ApplyViewportDeltas(
908 const gfx::Vector2dF& inner_delta,
909 const gfx::Vector2dF& outer_delta,
910 const gfx::Vector2dF& elastic_overscroll_delta,
911 float page_scale,
912 float top_controls_delta) {
913 widget_->webwidget()->applyViewportDeltas(
914 inner_delta,
915 outer_delta,
916 elastic_overscroll_delta,
917 page_scale,
918 top_controls_delta);
921 void RenderWidgetCompositor::RequestNewOutputSurface() {
922 // If the host is closing, then no more compositing is possible. This
923 // prevents shutdown races between handling the close message and
924 // the CreateOutputSurface task.
925 if (widget_->host_closing())
926 return;
928 bool fallback =
929 num_failed_recreate_attempts_ >= OUTPUT_SURFACE_RETRIES_BEFORE_FALLBACK;
930 scoped_ptr<cc::OutputSurface> surface(widget_->CreateOutputSurface(fallback));
932 if (!surface) {
933 DidFailToInitializeOutputSurface();
934 return;
937 DCHECK_EQ(surface->capabilities().max_frames_pending, 1);
939 layer_tree_host_->SetOutputSurface(surface.Pass());
942 void RenderWidgetCompositor::DidInitializeOutputSurface() {
943 num_failed_recreate_attempts_ = 0;
946 void RenderWidgetCompositor::DidFailToInitializeOutputSurface() {
947 ++num_failed_recreate_attempts_;
948 // Tolerate a certain number of recreation failures to work around races
949 // in the output-surface-lost machinery.
950 LOG_IF(FATAL, (num_failed_recreate_attempts_ >= MAX_OUTPUT_SURFACE_RETRIES))
951 << "Failed to create a fallback OutputSurface.";
953 base::ThreadTaskRunnerHandle::Get()->PostTask(
954 FROM_HERE, base::Bind(&RenderWidgetCompositor::RequestNewOutputSurface,
955 weak_factory_.GetWeakPtr()));
958 void RenderWidgetCompositor::WillCommit() {
959 InvokeLayoutAndPaintCallback();
962 void RenderWidgetCompositor::DidCommit() {
963 DCHECK(!temporary_copy_output_request_);
964 widget_->DidCommitCompositorFrame();
965 compositor_deps_->GetRendererScheduler()->DidCommitFrameToCompositor();
968 void RenderWidgetCompositor::DidCommitAndDrawFrame() {
969 widget_->DidCommitAndDrawCompositorFrame();
972 void RenderWidgetCompositor::DidCompleteSwapBuffers() {
973 widget_->DidCompleteSwapBuffers();
974 bool threaded = !!compositor_deps_->GetCompositorImplThreadTaskRunner().get();
975 if (!threaded)
976 widget_->OnSwapBuffersComplete();
979 void RenderWidgetCompositor::DidCompletePageScaleAnimation() {
980 widget_->DidCompletePageScaleAnimation();
983 void RenderWidgetCompositor::ScheduleAnimation() {
984 widget_->scheduleAnimation();
987 void RenderWidgetCompositor::DidPostSwapBuffers() {
988 widget_->OnSwapBuffersPosted();
991 void RenderWidgetCompositor::DidAbortSwapBuffers() {
992 widget_->OnSwapBuffersAborted();
995 void RenderWidgetCompositor::RecordFrameTimingEvents(
996 scoped_ptr<cc::FrameTimingTracker::CompositeTimingSet> composite_events,
997 scoped_ptr<cc::FrameTimingTracker::MainFrameTimingSet> main_frame_events) {
998 for (const auto& composite_event : *composite_events ) {
999 int64_t frameId = composite_event.first;
1000 const std::vector<cc::FrameTimingTracker::CompositeTimingEvent>& events =
1001 composite_event.second;
1002 std::vector<blink::WebFrameTimingEvent> webEvents;
1003 for (size_t i = 0; i < events.size(); ++i) {
1004 webEvents.push_back(blink::WebFrameTimingEvent(
1005 events[i].frame_id,
1006 (events[i].timestamp - base::TimeTicks()).InSecondsF()));
1008 widget_->webwidget()->recordFrameTimingEvent(
1009 blink::WebWidget::CompositeEvent, frameId, webEvents);
1011 for (const auto& main_frame_event : *main_frame_events ) {
1012 int64_t frameId = main_frame_event.first;
1013 const std::vector<cc::FrameTimingTracker::MainFrameTimingEvent>& events =
1014 main_frame_event.second;
1015 std::vector<blink::WebFrameTimingEvent> webEvents;
1016 for (size_t i = 0; i < events.size(); ++i) {
1017 webEvents.push_back(blink::WebFrameTimingEvent(
1018 events[i].frame_id,
1019 (events[i].timestamp - base::TimeTicks()).InSecondsF(),
1020 (events[i].end_time - base::TimeTicks()).InSecondsF()));
1022 widget_->webwidget()->recordFrameTimingEvent(
1023 blink::WebWidget::RenderEvent, frameId, webEvents);
1027 void RenderWidgetCompositor::RateLimitSharedMainThreadContext() {
1028 cc::ContextProvider* provider =
1029 compositor_deps_->GetSharedMainThreadContextProvider();
1030 // provider can be NULL after the GPU process crashed enough times and we
1031 // don't want to restart it any more (falling back to software).
1032 if (!provider)
1033 return;
1034 provider->ContextGL()->RateLimitOffscreenContextCHROMIUM();
1037 void RenderWidgetCompositor::SetSurfaceIdNamespace(
1038 uint32_t surface_id_namespace) {
1039 layer_tree_host_->set_surface_id_namespace(surface_id_namespace);
1042 } // namespace content