Pin Chrome's shortcut to the Win10 Start menu on install and OS upgrade.
[chromium-blink-merge.git] / content / renderer / gpu / render_widget_compositor.cc
blob4895617bb45c082b83e40891a354801a680a315c
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;
456 // When pinching in, only show the pinch-viewport overlay scrollbars if the
457 // page scale is at least some threshold away from the minimum. i.e. don't
458 // show the pinch scrollbars when at minimum scale.
459 settings.scrollbar_show_scale_threshold = 1.05f;
460 #endif
462 if (cmd->HasSwitch(switches::kEnableLowResTiling))
463 settings.create_low_res_tiling = true;
464 if (cmd->HasSwitch(switches::kDisableLowResTiling))
465 settings.create_low_res_tiling = false;
466 if (cmd->HasSwitch(cc::switches::kEnableBeginFrameScheduling))
467 settings.use_external_begin_frame_source = true;
469 if (widget_->for_oopif()) {
470 // TODO(simonhong): Apply BeginFrame scheduling for OOPIF.
471 // See crbug.com/471411.
472 settings.use_external_begin_frame_source = false;
475 scoped_refptr<base::SingleThreadTaskRunner> compositor_thread_task_runner =
476 compositor_deps_->GetCompositorImplThreadTaskRunner();
477 scoped_refptr<base::SingleThreadTaskRunner>
478 main_thread_compositor_task_runner =
479 compositor_deps_->GetCompositorMainThreadTaskRunner();
480 cc::SharedBitmapManager* shared_bitmap_manager =
481 compositor_deps_->GetSharedBitmapManager();
482 gpu::GpuMemoryBufferManager* gpu_memory_buffer_manager =
483 compositor_deps_->GetGpuMemoryBufferManager();
484 cc::TaskGraphRunner* task_graph_runner =
485 compositor_deps_->GetTaskGraphRunner();
487 scoped_ptr<cc::BeginFrameSource> external_begin_frame_source;
488 if (settings.use_external_begin_frame_source) {
489 external_begin_frame_source =
490 compositor_deps_->CreateExternalBeginFrameSource(widget_->routing_id());
493 cc::LayerTreeHost::InitParams params;
494 params.client = this;
495 params.shared_bitmap_manager = shared_bitmap_manager;
496 params.gpu_memory_buffer_manager = gpu_memory_buffer_manager;
497 params.settings = &settings;
498 params.task_graph_runner = task_graph_runner;
499 params.main_task_runner = main_thread_compositor_task_runner;
500 params.external_begin_frame_source = external_begin_frame_source.Pass();
501 if (compositor_thread_task_runner.get()) {
502 layer_tree_host_ = cc::LayerTreeHost::CreateThreaded(
503 compositor_thread_task_runner, &params);
504 } else {
505 layer_tree_host_ = cc::LayerTreeHost::CreateSingleThreaded(this, &params);
507 DCHECK(layer_tree_host_);
510 RenderWidgetCompositor::~RenderWidgetCompositor() {}
512 const base::WeakPtr<cc::InputHandler>&
513 RenderWidgetCompositor::GetInputHandler() {
514 return layer_tree_host_->GetInputHandler();
517 bool RenderWidgetCompositor::BeginMainFrameRequested() const {
518 return layer_tree_host_->BeginMainFrameRequested();
521 void RenderWidgetCompositor::SetNeedsDisplayOnAllLayers() {
522 layer_tree_host_->SetNeedsDisplayOnAllLayers();
525 void RenderWidgetCompositor::SetRasterizeOnlyVisibleContent() {
526 cc::LayerTreeDebugState current = layer_tree_host_->debug_state();
527 current.rasterize_only_visible_content = true;
528 layer_tree_host_->SetDebugState(current);
531 void RenderWidgetCompositor::SetNeedsRedrawRect(gfx::Rect damage_rect) {
532 layer_tree_host_->SetNeedsRedrawRect(damage_rect);
535 void RenderWidgetCompositor::SetNeedsForcedRedraw() {
536 layer_tree_host_->SetNextCommitForcesRedraw();
537 setNeedsAnimate();
540 scoped_ptr<cc::SwapPromiseMonitor>
541 RenderWidgetCompositor::CreateLatencyInfoSwapPromiseMonitor(
542 ui::LatencyInfo* latency) {
543 return scoped_ptr<cc::SwapPromiseMonitor>(
544 new cc::LatencyInfoSwapPromiseMonitor(
545 latency, layer_tree_host_.get(), NULL));
548 void RenderWidgetCompositor::QueueSwapPromise(
549 scoped_ptr<cc::SwapPromise> swap_promise) {
550 layer_tree_host_->QueueSwapPromise(swap_promise.Pass());
553 int RenderWidgetCompositor::GetSourceFrameNumber() const {
554 return layer_tree_host_->source_frame_number();
557 void RenderWidgetCompositor::SetNeedsUpdateLayers() {
558 layer_tree_host_->SetNeedsUpdateLayers();
561 void RenderWidgetCompositor::SetNeedsCommit() {
562 layer_tree_host_->SetNeedsCommit();
565 void RenderWidgetCompositor::NotifyInputThrottledUntilCommit() {
566 layer_tree_host_->NotifyInputThrottledUntilCommit();
569 const cc::Layer* RenderWidgetCompositor::GetRootLayer() const {
570 return layer_tree_host_->root_layer();
573 int RenderWidgetCompositor::ScheduleMicroBenchmark(
574 const std::string& name,
575 scoped_ptr<base::Value> value,
576 const base::Callback<void(scoped_ptr<base::Value>)>& callback) {
577 return layer_tree_host_->ScheduleMicroBenchmark(name, value.Pass(), callback);
580 bool RenderWidgetCompositor::SendMessageToMicroBenchmark(
581 int id,
582 scoped_ptr<base::Value> value) {
583 return layer_tree_host_->SendMessageToMicroBenchmark(id, value.Pass());
586 void RenderWidgetCompositor::StartCompositor() {
587 layer_tree_host_->SetLayerTreeHostClientReady();
590 void RenderWidgetCompositor::setRootLayer(const blink::WebLayer& layer) {
591 layer_tree_host_->SetRootLayer(
592 static_cast<const cc_blink::WebLayerImpl*>(&layer)->layer());
595 void RenderWidgetCompositor::clearRootLayer() {
596 layer_tree_host_->SetRootLayer(scoped_refptr<cc::Layer>());
599 void RenderWidgetCompositor::attachCompositorAnimationTimeline(
600 blink::WebCompositorAnimationTimeline* compositor_timeline) {
601 DCHECK(compositor_timeline);
602 DCHECK(layer_tree_host_->animation_host());
603 layer_tree_host_->animation_host()->AddAnimationTimeline(
604 static_cast<const cc_blink::WebCompositorAnimationTimelineImpl*>(
605 compositor_timeline)->animation_timeline());
608 void RenderWidgetCompositor::detachCompositorAnimationTimeline(
609 blink::WebCompositorAnimationTimeline* compositor_timeline) {
610 DCHECK(compositor_timeline);
611 DCHECK(layer_tree_host_->animation_host());
612 layer_tree_host_->animation_host()->RemoveAnimationTimeline(
613 static_cast<const cc_blink::WebCompositorAnimationTimelineImpl*>(
614 compositor_timeline)->animation_timeline());
617 void RenderWidgetCompositor::setViewportSize(
618 const WebSize&,
619 const WebSize& device_viewport_size) {
620 layer_tree_host_->SetViewportSize(device_viewport_size);
623 void RenderWidgetCompositor::setViewportSize(
624 const WebSize& device_viewport_size) {
625 layer_tree_host_->SetViewportSize(device_viewport_size);
628 WebSize RenderWidgetCompositor::layoutViewportSize() const {
629 return layer_tree_host_->device_viewport_size();
632 WebSize RenderWidgetCompositor::deviceViewportSize() const {
633 return layer_tree_host_->device_viewport_size();
636 WebFloatPoint RenderWidgetCompositor::adjustEventPointForPinchZoom(
637 const WebFloatPoint& point) const {
638 return point;
641 void RenderWidgetCompositor::setDeviceScaleFactor(float device_scale) {
642 layer_tree_host_->SetDeviceScaleFactor(device_scale);
645 float RenderWidgetCompositor::deviceScaleFactor() const {
646 return layer_tree_host_->device_scale_factor();
649 void RenderWidgetCompositor::setBackgroundColor(blink::WebColor color) {
650 layer_tree_host_->set_background_color(color);
653 void RenderWidgetCompositor::setHasTransparentBackground(bool transparent) {
654 layer_tree_host_->set_has_transparent_background(transparent);
657 void RenderWidgetCompositor::setVisible(bool visible) {
658 layer_tree_host_->SetVisible(visible);
661 void RenderWidgetCompositor::setPageScaleFactorAndLimits(
662 float page_scale_factor, float minimum, float maximum) {
663 layer_tree_host_->SetPageScaleFactorAndLimits(
664 page_scale_factor, minimum, maximum);
667 void RenderWidgetCompositor::startPageScaleAnimation(
668 const blink::WebPoint& destination,
669 bool use_anchor,
670 float new_page_scale,
671 double duration_sec) {
672 base::TimeDelta duration = base::TimeDelta::FromMicroseconds(
673 duration_sec * base::Time::kMicrosecondsPerSecond);
674 layer_tree_host_->StartPageScaleAnimation(
675 gfx::Vector2d(destination.x, destination.y),
676 use_anchor,
677 new_page_scale,
678 duration);
681 void RenderWidgetCompositor::heuristicsForGpuRasterizationUpdated(
682 bool matches_heuristics) {
683 layer_tree_host_->SetHasGpuRasterizationTrigger(matches_heuristics);
686 void RenderWidgetCompositor::setNeedsAnimate() {
687 layer_tree_host_->SetNeedsAnimate();
690 void RenderWidgetCompositor::didStopFlinging() {
691 layer_tree_host_->DidStopFlinging();
694 void RenderWidgetCompositor::registerForAnimations(blink::WebLayer* layer) {
695 cc::Layer* cc_layer = static_cast<cc_blink::WebLayerImpl*>(layer)->layer();
696 cc_layer->RegisterForAnimations(layer_tree_host_->animation_registrar());
699 void RenderWidgetCompositor::registerViewportLayers(
700 const blink::WebLayer* overscrollElasticityLayer,
701 const blink::WebLayer* pageScaleLayer,
702 const blink::WebLayer* innerViewportScrollLayer,
703 const blink::WebLayer* outerViewportScrollLayer) {
704 layer_tree_host_->RegisterViewportLayers(
705 // TODO(bokan): This check can probably be removed now, but it looks
706 // like overscroll elasticity may still be NULL until PinchViewport
707 // registers its layers.
708 // The scroll elasticity layer will only exist when using pinch virtual
709 // viewports.
710 overscrollElasticityLayer
711 ? static_cast<const cc_blink::WebLayerImpl*>(
712 overscrollElasticityLayer)->layer()
713 : NULL,
714 static_cast<const cc_blink::WebLayerImpl*>(pageScaleLayer)->layer(),
715 static_cast<const cc_blink::WebLayerImpl*>(innerViewportScrollLayer)
716 ->layer(),
717 // TODO(bokan): This check can probably be removed now, but it looks
718 // like overscroll elasticity may still be NULL until PinchViewport
719 // registers its layers.
720 // The outer viewport layer will only exist when using pinch virtual
721 // viewports.
722 outerViewportScrollLayer
723 ? static_cast<const cc_blink::WebLayerImpl*>(outerViewportScrollLayer)
724 ->layer()
725 : NULL);
728 void RenderWidgetCompositor::clearViewportLayers() {
729 layer_tree_host_->RegisterViewportLayers(
730 scoped_refptr<cc::Layer>(), scoped_refptr<cc::Layer>(),
731 scoped_refptr<cc::Layer>(), scoped_refptr<cc::Layer>());
734 void RenderWidgetCompositor::registerSelection(
735 const blink::WebSelection& selection) {
736 layer_tree_host_->RegisterSelection(ConvertWebSelection(selection));
739 void RenderWidgetCompositor::clearSelection() {
740 cc::LayerSelection empty_selection;
741 layer_tree_host_->RegisterSelection(empty_selection);
744 void CompositeAndReadbackAsyncCallback(
745 blink::WebCompositeAndReadbackAsyncCallback* callback,
746 scoped_ptr<cc::CopyOutputResult> result) {
747 if (result->HasBitmap()) {
748 scoped_ptr<SkBitmap> result_bitmap = result->TakeBitmap();
749 callback->didCompositeAndReadback(*result_bitmap);
750 } else {
751 callback->didCompositeAndReadback(SkBitmap());
755 bool RenderWidgetCompositor::CompositeIsSynchronous() const {
756 return !compositor_deps_->GetCompositorImplThreadTaskRunner().get() &&
757 !layer_tree_host_->settings().single_thread_proxy_scheduler;
760 void RenderWidgetCompositor::layoutAndPaintAsync(
761 blink::WebLayoutAndPaintAsyncCallback* callback) {
762 DCHECK(!temporary_copy_output_request_ && !layout_and_paint_async_callback_);
763 layout_and_paint_async_callback_ = callback;
765 if (CompositeIsSynchronous()) {
766 base::ThreadTaskRunnerHandle::Get()->PostTask(
767 FROM_HERE, base::Bind(&RenderWidgetCompositor::LayoutAndUpdateLayers,
768 weak_factory_.GetWeakPtr()));
769 } else {
770 layer_tree_host_->SetNeedsCommit();
774 void RenderWidgetCompositor::LayoutAndUpdateLayers() {
775 DCHECK(CompositeIsSynchronous());
776 layer_tree_host_->LayoutAndUpdateLayers();
777 InvokeLayoutAndPaintCallback();
780 void RenderWidgetCompositor::InvokeLayoutAndPaintCallback() {
781 if (!layout_and_paint_async_callback_)
782 return;
783 layout_and_paint_async_callback_->didLayoutAndPaint();
784 layout_and_paint_async_callback_ = nullptr;
787 void RenderWidgetCompositor::compositeAndReadbackAsync(
788 blink::WebCompositeAndReadbackAsyncCallback* callback) {
789 DCHECK(!temporary_copy_output_request_ && !layout_and_paint_async_callback_);
790 temporary_copy_output_request_ =
791 cc::CopyOutputRequest::CreateBitmapRequest(
792 base::Bind(&CompositeAndReadbackAsyncCallback, callback));
794 // Force a commit to happen. The temporary copy output request will
795 // be installed after layout which will happen as a part of the commit, for
796 // widgets that delay the creation of their output surface.
797 if (CompositeIsSynchronous()) {
798 base::ThreadTaskRunnerHandle::Get()->PostTask(
799 FROM_HERE, base::Bind(&RenderWidgetCompositor::SynchronouslyComposite,
800 weak_factory_.GetWeakPtr()));
801 } else {
802 layer_tree_host_->SetNeedsCommit();
806 void RenderWidgetCompositor::SynchronouslyComposite() {
807 DCHECK(CompositeIsSynchronous());
808 layer_tree_host_->Composite(base::TimeTicks::Now());
811 void RenderWidgetCompositor::finishAllRendering() {
812 layer_tree_host_->FinishAllRendering();
815 void RenderWidgetCompositor::setDeferCommits(bool defer_commits) {
816 layer_tree_host_->SetDeferCommits(defer_commits);
819 int RenderWidgetCompositor::layerTreeId() const {
820 return layer_tree_host_->id();
823 void RenderWidgetCompositor::setShowFPSCounter(bool show) {
824 cc::LayerTreeDebugState debug_state = layer_tree_host_->debug_state();
825 debug_state.show_fps_counter = show;
826 layer_tree_host_->SetDebugState(debug_state);
829 void RenderWidgetCompositor::setShowPaintRects(bool show) {
830 cc::LayerTreeDebugState debug_state = layer_tree_host_->debug_state();
831 debug_state.show_paint_rects = show;
832 layer_tree_host_->SetDebugState(debug_state);
835 void RenderWidgetCompositor::setShowDebugBorders(bool show) {
836 cc::LayerTreeDebugState debug_state = layer_tree_host_->debug_state();
837 debug_state.show_debug_borders = show;
838 layer_tree_host_->SetDebugState(debug_state);
841 void RenderWidgetCompositor::setContinuousPaintingEnabled(bool enabled) {
842 cc::LayerTreeDebugState debug_state = layer_tree_host_->debug_state();
843 debug_state.continuous_painting = enabled;
844 layer_tree_host_->SetDebugState(debug_state);
847 void RenderWidgetCompositor::setShowScrollBottleneckRects(bool show) {
848 cc::LayerTreeDebugState debug_state = layer_tree_host_->debug_state();
849 debug_state.show_touch_event_handler_rects = show;
850 debug_state.show_wheel_event_handler_rects = show;
851 debug_state.show_non_fast_scrollable_rects = show;
852 layer_tree_host_->SetDebugState(debug_state);
855 void RenderWidgetCompositor::updateTopControlsState(
856 WebTopControlsState constraints,
857 WebTopControlsState current,
858 bool animate) {
859 layer_tree_host_->UpdateTopControlsState(ConvertTopControlsState(constraints),
860 ConvertTopControlsState(current),
861 animate);
864 void RenderWidgetCompositor::setTopControlsHeight(float height, bool shrink) {
865 layer_tree_host_->SetTopControlsHeight(height, shrink);
868 void RenderWidgetCompositor::setTopControlsShownRatio(float ratio) {
869 layer_tree_host_->SetTopControlsShownRatio(ratio);
872 void RenderWidgetCompositor::WillBeginMainFrame() {
873 widget_->WillBeginCompositorFrame();
876 void RenderWidgetCompositor::DidBeginMainFrame() {
879 void RenderWidgetCompositor::BeginMainFrame(const cc::BeginFrameArgs& args) {
880 double frame_time_sec = (args.frame_time - base::TimeTicks()).InSecondsF();
881 double deadline_sec = (args.deadline - base::TimeTicks()).InSecondsF();
882 double interval_sec = args.interval.InSecondsF();
883 WebBeginFrameArgs web_begin_frame_args =
884 WebBeginFrameArgs(frame_time_sec, deadline_sec, interval_sec);
885 compositor_deps_->GetRendererScheduler()->WillBeginFrame(args);
886 widget_->webwidget()->beginFrame(web_begin_frame_args);
889 void RenderWidgetCompositor::BeginMainFrameNotExpectedSoon() {
890 compositor_deps_->GetRendererScheduler()->BeginFrameNotExpectedSoon();
893 void RenderWidgetCompositor::Layout() {
894 widget_->webwidget()->layout();
896 if (temporary_copy_output_request_) {
897 // For WebViewImpl, this will always have a root layer. For other widgets,
898 // the widget may be closed before servicing this request, so ignore it.
899 if (cc::Layer* root_layer = layer_tree_host_->root_layer()) {
900 root_layer->RequestCopyOfOutput(temporary_copy_output_request_.Pass());
901 } else {
902 temporary_copy_output_request_->SendEmptyResult();
903 temporary_copy_output_request_ = nullptr;
908 void RenderWidgetCompositor::ApplyViewportDeltas(
909 const gfx::Vector2dF& inner_delta,
910 const gfx::Vector2dF& outer_delta,
911 const gfx::Vector2dF& elastic_overscroll_delta,
912 float page_scale,
913 float top_controls_delta) {
914 widget_->webwidget()->applyViewportDeltas(
915 inner_delta,
916 outer_delta,
917 elastic_overscroll_delta,
918 page_scale,
919 top_controls_delta);
922 void RenderWidgetCompositor::RequestNewOutputSurface() {
923 // If the host is closing, then no more compositing is possible. This
924 // prevents shutdown races between handling the close message and
925 // the CreateOutputSurface task.
926 if (widget_->host_closing())
927 return;
929 bool fallback =
930 num_failed_recreate_attempts_ >= OUTPUT_SURFACE_RETRIES_BEFORE_FALLBACK;
931 scoped_ptr<cc::OutputSurface> surface(widget_->CreateOutputSurface(fallback));
933 if (!surface) {
934 DidFailToInitializeOutputSurface();
935 return;
938 DCHECK_EQ(surface->capabilities().max_frames_pending, 1);
940 layer_tree_host_->SetOutputSurface(surface.Pass());
943 void RenderWidgetCompositor::DidInitializeOutputSurface() {
944 num_failed_recreate_attempts_ = 0;
947 void RenderWidgetCompositor::DidFailToInitializeOutputSurface() {
948 ++num_failed_recreate_attempts_;
949 // Tolerate a certain number of recreation failures to work around races
950 // in the output-surface-lost machinery.
951 LOG_IF(FATAL, (num_failed_recreate_attempts_ >= MAX_OUTPUT_SURFACE_RETRIES))
952 << "Failed to create a fallback OutputSurface.";
954 base::ThreadTaskRunnerHandle::Get()->PostTask(
955 FROM_HERE, base::Bind(&RenderWidgetCompositor::RequestNewOutputSurface,
956 weak_factory_.GetWeakPtr()));
959 void RenderWidgetCompositor::WillCommit() {
960 InvokeLayoutAndPaintCallback();
963 void RenderWidgetCompositor::DidCommit() {
964 DCHECK(!temporary_copy_output_request_);
965 widget_->DidCommitCompositorFrame();
966 compositor_deps_->GetRendererScheduler()->DidCommitFrameToCompositor();
969 void RenderWidgetCompositor::DidCommitAndDrawFrame() {
970 widget_->DidCommitAndDrawCompositorFrame();
973 void RenderWidgetCompositor::DidCompleteSwapBuffers() {
974 widget_->DidCompleteSwapBuffers();
975 bool threaded = !!compositor_deps_->GetCompositorImplThreadTaskRunner().get();
976 if (!threaded)
977 widget_->OnSwapBuffersComplete();
980 void RenderWidgetCompositor::DidCompletePageScaleAnimation() {
981 widget_->DidCompletePageScaleAnimation();
984 void RenderWidgetCompositor::ScheduleAnimation() {
985 widget_->scheduleAnimation();
988 void RenderWidgetCompositor::DidPostSwapBuffers() {
989 widget_->OnSwapBuffersPosted();
992 void RenderWidgetCompositor::DidAbortSwapBuffers() {
993 widget_->OnSwapBuffersAborted();
996 void RenderWidgetCompositor::RecordFrameTimingEvents(
997 scoped_ptr<cc::FrameTimingTracker::CompositeTimingSet> composite_events,
998 scoped_ptr<cc::FrameTimingTracker::MainFrameTimingSet> main_frame_events) {
999 for (const auto& composite_event : *composite_events ) {
1000 int64_t frameId = composite_event.first;
1001 const std::vector<cc::FrameTimingTracker::CompositeTimingEvent>& events =
1002 composite_event.second;
1003 std::vector<blink::WebFrameTimingEvent> webEvents;
1004 for (size_t i = 0; i < events.size(); ++i) {
1005 webEvents.push_back(blink::WebFrameTimingEvent(
1006 events[i].frame_id,
1007 (events[i].timestamp - base::TimeTicks()).InSecondsF()));
1009 widget_->webwidget()->recordFrameTimingEvent(
1010 blink::WebWidget::CompositeEvent, frameId, webEvents);
1012 for (const auto& main_frame_event : *main_frame_events ) {
1013 int64_t frameId = main_frame_event.first;
1014 const std::vector<cc::FrameTimingTracker::MainFrameTimingEvent>& events =
1015 main_frame_event.second;
1016 std::vector<blink::WebFrameTimingEvent> webEvents;
1017 for (size_t i = 0; i < events.size(); ++i) {
1018 webEvents.push_back(blink::WebFrameTimingEvent(
1019 events[i].frame_id,
1020 (events[i].timestamp - base::TimeTicks()).InSecondsF(),
1021 (events[i].end_time - base::TimeTicks()).InSecondsF()));
1023 widget_->webwidget()->recordFrameTimingEvent(
1024 blink::WebWidget::RenderEvent, frameId, webEvents);
1028 void RenderWidgetCompositor::RateLimitSharedMainThreadContext() {
1029 cc::ContextProvider* provider =
1030 compositor_deps_->GetSharedMainThreadContextProvider();
1031 // provider can be NULL after the GPU process crashed enough times and we
1032 // don't want to restart it any more (falling back to software).
1033 if (!provider)
1034 return;
1035 provider->ContextGL()->RateLimitOffscreenContextCHROMIUM();
1038 void RenderWidgetCompositor::SetSurfaceIdNamespace(
1039 uint32_t surface_id_namespace) {
1040 layer_tree_host_->set_surface_id_namespace(surface_id_namespace);
1043 } // namespace content