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"
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"
69 using blink::WebBeginFrameArgs
;
70 using blink::WebFloatPoint
;
72 using blink::WebSelection
;
74 using blink::WebTopControlsState
;
79 bool GetSwitchValueAsInt(const base::CommandLine
& command_line
,
80 const std::string
& switch_string
,
84 std::string string_value
= command_line
.GetSwitchValueASCII(switch_string
);
86 if (base::StringToInt(string_value
, &int_value
) &&
87 int_value
>= min_value
&& int_value
<= max_value
) {
91 LOG(WARNING
) << "Failed to parse switch " << switch_string
<< ": " <<
97 cc::LayerSelectionBound
ConvertWebSelectionBound(
98 const WebSelection
& web_selection
,
100 cc::LayerSelectionBound cc_bound
;
101 if (web_selection
.isNone())
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()) {
110 cc_bound
.type
= web_bound
.isTextDirectionRTL
? cc::SELECTION_BOUND_RIGHT
111 : cc::SELECTION_BOUND_LEFT
;
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
);
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();
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;
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);
172 default_tile_size
= 384;
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;
182 return gfx::Size(default_tile_size
, default_tile_size
);
185 // Check cc::TopControlsState, and blink::WebTopControlsState
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
);
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();
211 RenderWidgetCompositor::RenderWidgetCompositor(
212 RenderWidget
* widget
,
213 CompositorDependencies
* compositor_deps
)
214 : num_failed_recreate_attempts_(0),
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;
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 compositor_deps_
->IsThreadedAnimationEnabled();
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
)) {
261 GetSwitchValueAsInt(*cmd
,
262 switches::kDefaultTileWidth
,
264 std::numeric_limits
<int>::max(),
266 settings
.default_tile_size
.set_width(tile_width
);
268 if (cmd
->HasSwitch(switches::kDefaultTileHeight
)) {
270 GetSwitchValueAsInt(*cmd
,
271 switches::kDefaultTileHeight
,
273 std::numeric_limits
<int>::max(),
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_persistent_map_for_gpu_memory_buffers
=
306 compositor_deps_
->IsPersistentGpuMemoryBufferEnabled();
307 settings
.enable_elastic_overscroll
=
308 compositor_deps_
->IsElasticOverscrollEnabled();
309 settings
.use_image_texture_targets
=
310 compositor_deps_
->GetImageTextureTargets();
311 settings
.gather_pixel_refs
= compositor_deps_
->IsGatherPixelRefsEnabled();
313 if (cmd
->HasSwitch(cc::switches::kTopControlsShowThreshold
)) {
314 std::string top_threshold_str
=
315 cmd
->GetSwitchValueASCII(cc::switches::kTopControlsShowThreshold
);
316 double show_threshold
;
317 if (base::StringToDouble(top_threshold_str
, &show_threshold
) &&
318 show_threshold
>= 0.f
&& show_threshold
<= 1.f
)
319 settings
.top_controls_show_threshold
= show_threshold
;
322 if (cmd
->HasSwitch(cc::switches::kTopControlsHideThreshold
)) {
323 std::string top_threshold_str
=
324 cmd
->GetSwitchValueASCII(cc::switches::kTopControlsHideThreshold
);
325 double hide_threshold
;
326 if (base::StringToDouble(top_threshold_str
, &hide_threshold
) &&
327 hide_threshold
>= 0.f
&& hide_threshold
<= 1.f
)
328 settings
.top_controls_hide_threshold
= hide_threshold
;
331 settings
.verify_property_trees
=
332 cmd
->HasSwitch(cc::switches::kEnablePropertyTreeVerification
);
333 settings
.renderer_settings
.allow_antialiasing
&=
334 !cmd
->HasSwitch(cc::switches::kDisableCompositedAntialiasing
);
335 // The means the renderer compositor has 2 possible modes:
336 // - Threaded compositing with a scheduler.
337 // - Single threaded compositing without a scheduler (for layout tests only).
338 // Using the scheduler in layout tests introduces additional composite steps
339 // that create flakiness.
340 settings
.single_thread_proxy_scheduler
= false;
342 // These flags should be mirrored by UI versions in ui/compositor/.
343 settings
.initial_debug_state
.show_debug_borders
=
344 cmd
->HasSwitch(cc::switches::kShowCompositedLayerBorders
);
345 settings
.initial_debug_state
.show_fps_counter
=
346 cmd
->HasSwitch(cc::switches::kShowFPSCounter
);
347 settings
.initial_debug_state
.show_layer_animation_bounds_rects
=
348 cmd
->HasSwitch(cc::switches::kShowLayerAnimationBounds
);
349 settings
.initial_debug_state
.show_paint_rects
=
350 cmd
->HasSwitch(switches::kShowPaintRects
);
351 settings
.initial_debug_state
.show_property_changed_rects
=
352 cmd
->HasSwitch(cc::switches::kShowPropertyChangedRects
);
353 settings
.initial_debug_state
.show_surface_damage_rects
=
354 cmd
->HasSwitch(cc::switches::kShowSurfaceDamageRects
);
355 settings
.initial_debug_state
.show_screen_space_rects
=
356 cmd
->HasSwitch(cc::switches::kShowScreenSpaceRects
);
357 settings
.initial_debug_state
.show_replica_screen_space_rects
=
358 cmd
->HasSwitch(cc::switches::kShowReplicaScreenSpaceRects
);
360 settings
.initial_debug_state
.SetRecordRenderingStats(
361 cmd
->HasSwitch(cc::switches::kEnableGpuBenchmarking
));
363 if (cmd
->HasSwitch(cc::switches::kSlowDownRasterScaleFactor
)) {
364 const int kMinSlowDownScaleFactor
= 0;
365 const int kMaxSlowDownScaleFactor
= INT_MAX
;
368 cc::switches::kSlowDownRasterScaleFactor
,
369 kMinSlowDownScaleFactor
,
370 kMaxSlowDownScaleFactor
,
371 &settings
.initial_debug_state
.slow_down_raster_scale_factor
);
374 settings
.invert_viewport_scroll_order
=
375 cmd
->HasSwitch(switches::kInvertViewportScrollOrder
);
377 settings
.strict_layer_property_change_checking
=
378 cmd
->HasSwitch(cc::switches::kStrictLayerPropertyChangeChecking
);
380 #if defined(OS_ANDROID)
381 SynchronousCompositorFactory
* synchronous_compositor_factory
=
382 SynchronousCompositorFactory::GetInstance();
384 // We can't use GPU rasterization on low-end devices, because the Ganesh
385 // cache would consume too much memory.
386 if (base::SysInfo::IsLowEndDevice())
387 settings
.gpu_rasterization_enabled
= false;
388 settings
.using_synchronous_renderer_compositor
=
389 synchronous_compositor_factory
;
390 settings
.record_full_layer
= widget_
->DoesRecordFullLayer();
391 if (synchronous_compositor_factory
) {
392 // Android WebView uses system scrollbars, so make ours invisible.
393 settings
.scrollbar_animator
= cc::LayerTreeSettings::NO_ANIMATOR
;
394 settings
.solid_color_scrollbar_color
= SK_ColorTRANSPARENT
;
396 settings
.scrollbar_animator
= cc::LayerTreeSettings::LINEAR_FADE
;
397 settings
.scrollbar_fade_delay_ms
= 300;
398 settings
.scrollbar_fade_resize_delay_ms
= 2000;
399 settings
.scrollbar_fade_duration_ms
= 300;
400 settings
.solid_color_scrollbar_color
= SkColorSetARGB(128, 128, 128, 128);
402 settings
.renderer_settings
.highp_threshold_min
= 2048;
403 // Android WebView handles root layer flings itself.
404 settings
.ignore_root_layer_flings
=
405 synchronous_compositor_factory
;
406 // Memory policy on Android WebView does not depend on whether device is
407 // low end, so always use default policy.
408 bool use_low_memory_policy
=
409 base::SysInfo::IsLowEndDevice() && !synchronous_compositor_factory
;
410 // RGBA_4444 textures are only enabled by default for low end devices
411 // and are disabled for Android WebView as it doesn't support the format.
412 settings
.renderer_settings
.use_rgba_4444_textures
= use_low_memory_policy
;
413 if (use_low_memory_policy
) {
414 // On low-end we want to be very carefull about killing other
415 // apps. So initially we use 50% more memory to avoid flickering
416 // or raster-on-demand.
417 settings
.max_memory_for_prepaint_percentage
= 67;
419 // On other devices we have increased memory excessively to avoid
420 // raster-on-demand already, so now we reserve 50% _only_ to avoid
421 // raster-on-demand, and use 50% of the memory otherwise.
422 settings
.max_memory_for_prepaint_percentage
= 50;
424 // Webview does not own the surface so should not clear it.
425 settings
.renderer_settings
.should_clear_root_render_pass
=
426 !synchronous_compositor_factory
;
428 // TODO(danakj): Only do this on low end devices.
429 settings
.create_low_res_tiling
= true;
431 settings
.use_external_begin_frame_source
= true;
433 #elif !defined(OS_MACOSX)
434 if (ui::IsOverlayScrollbarEnabled()) {
435 settings
.scrollbar_animator
= cc::LayerTreeSettings::THINNING
;
436 settings
.solid_color_scrollbar_color
= SkColorSetARGB(128, 128, 128, 128);
438 settings
.scrollbar_animator
= cc::LayerTreeSettings::LINEAR_FADE
;
439 settings
.solid_color_scrollbar_color
= SkColorSetARGB(128, 128, 128, 128);
441 settings
.scrollbar_fade_delay_ms
= 500;
442 settings
.scrollbar_fade_resize_delay_ms
= 500;
443 settings
.scrollbar_fade_duration_ms
= 300;
446 if (cmd
->HasSwitch(switches::kEnableLowResTiling
))
447 settings
.create_low_res_tiling
= true;
448 if (cmd
->HasSwitch(switches::kDisableLowResTiling
))
449 settings
.create_low_res_tiling
= false;
450 if (cmd
->HasSwitch(cc::switches::kEnableBeginFrameScheduling
))
451 settings
.use_external_begin_frame_source
= true;
453 settings
.renderer_settings
.use_rgba_4444_textures
|=
454 cmd
->HasSwitch(switches::kEnableRGBA4444Textures
);
455 settings
.renderer_settings
.use_rgba_4444_textures
&=
456 !cmd
->HasSwitch(switches::kDisableRGBA4444Textures
);
458 if (widget_
->for_oopif()) {
459 // TODO(simonhong): Apply BeginFrame scheduling for OOPIF.
460 // See crbug.com/471411.
461 settings
.use_external_begin_frame_source
= false;
464 settings
.max_staging_buffer_usage_in_bytes
= 32 * 1024 * 1024; // 32MB
465 // Use 1/4th of staging buffers on low-end devices.
466 if (base::SysInfo::IsLowEndDevice())
467 settings
.max_staging_buffer_usage_in_bytes
/= 4;
469 scoped_refptr
<base::SingleThreadTaskRunner
> compositor_thread_task_runner
=
470 compositor_deps_
->GetCompositorImplThreadTaskRunner();
471 scoped_refptr
<base::SingleThreadTaskRunner
>
472 main_thread_compositor_task_runner
=
473 compositor_deps_
->GetCompositorMainThreadTaskRunner();
474 cc::SharedBitmapManager
* shared_bitmap_manager
=
475 compositor_deps_
->GetSharedBitmapManager();
476 gpu::GpuMemoryBufferManager
* gpu_memory_buffer_manager
=
477 compositor_deps_
->GetGpuMemoryBufferManager();
478 cc::TaskGraphRunner
* task_graph_runner
=
479 compositor_deps_
->GetTaskGraphRunner();
481 scoped_ptr
<cc::BeginFrameSource
> external_begin_frame_source
;
482 if (settings
.use_external_begin_frame_source
) {
483 external_begin_frame_source
=
484 compositor_deps_
->CreateExternalBeginFrameSource(widget_
->routing_id());
487 cc::LayerTreeHost::InitParams params
;
488 params
.client
= this;
489 params
.shared_bitmap_manager
= shared_bitmap_manager
;
490 params
.gpu_memory_buffer_manager
= gpu_memory_buffer_manager
;
491 params
.settings
= &settings
;
492 params
.task_graph_runner
= task_graph_runner
;
493 params
.main_task_runner
= main_thread_compositor_task_runner
;
494 params
.external_begin_frame_source
= external_begin_frame_source
.Pass();
495 if (compositor_thread_task_runner
.get()) {
496 layer_tree_host_
= cc::LayerTreeHost::CreateThreaded(
497 compositor_thread_task_runner
, ¶ms
);
499 layer_tree_host_
= cc::LayerTreeHost::CreateSingleThreaded(this, ¶ms
);
501 DCHECK(layer_tree_host_
);
504 RenderWidgetCompositor::~RenderWidgetCompositor() {}
506 const base::WeakPtr
<cc::InputHandler
>&
507 RenderWidgetCompositor::GetInputHandler() {
508 return layer_tree_host_
->GetInputHandler();
511 bool RenderWidgetCompositor::BeginMainFrameRequested() const {
512 return layer_tree_host_
->BeginMainFrameRequested();
515 void RenderWidgetCompositor::SetNeedsDisplayOnAllLayers() {
516 layer_tree_host_
->SetNeedsDisplayOnAllLayers();
519 void RenderWidgetCompositor::SetRasterizeOnlyVisibleContent() {
520 cc::LayerTreeDebugState current
= layer_tree_host_
->debug_state();
521 current
.rasterize_only_visible_content
= true;
522 layer_tree_host_
->SetDebugState(current
);
525 void RenderWidgetCompositor::SetNeedsRedrawRect(gfx::Rect damage_rect
) {
526 layer_tree_host_
->SetNeedsRedrawRect(damage_rect
);
529 void RenderWidgetCompositor::SetNeedsForcedRedraw() {
530 layer_tree_host_
->SetNextCommitForcesRedraw();
534 scoped_ptr
<cc::SwapPromiseMonitor
>
535 RenderWidgetCompositor::CreateLatencyInfoSwapPromiseMonitor(
536 ui::LatencyInfo
* latency
) {
537 return scoped_ptr
<cc::SwapPromiseMonitor
>(
538 new cc::LatencyInfoSwapPromiseMonitor(
539 latency
, layer_tree_host_
.get(), NULL
));
542 void RenderWidgetCompositor::QueueSwapPromise(
543 scoped_ptr
<cc::SwapPromise
> swap_promise
) {
544 layer_tree_host_
->QueueSwapPromise(swap_promise
.Pass());
547 int RenderWidgetCompositor::GetSourceFrameNumber() const {
548 return layer_tree_host_
->source_frame_number();
551 void RenderWidgetCompositor::SetNeedsUpdateLayers() {
552 layer_tree_host_
->SetNeedsUpdateLayers();
555 void RenderWidgetCompositor::SetNeedsCommit() {
556 layer_tree_host_
->SetNeedsCommit();
559 void RenderWidgetCompositor::NotifyInputThrottledUntilCommit() {
560 layer_tree_host_
->NotifyInputThrottledUntilCommit();
563 const cc::Layer
* RenderWidgetCompositor::GetRootLayer() const {
564 return layer_tree_host_
->root_layer();
567 int RenderWidgetCompositor::ScheduleMicroBenchmark(
568 const std::string
& name
,
569 scoped_ptr
<base::Value
> value
,
570 const base::Callback
<void(scoped_ptr
<base::Value
>)>& callback
) {
571 return layer_tree_host_
->ScheduleMicroBenchmark(name
, value
.Pass(), callback
);
574 bool RenderWidgetCompositor::SendMessageToMicroBenchmark(
576 scoped_ptr
<base::Value
> value
) {
577 return layer_tree_host_
->SendMessageToMicroBenchmark(id
, value
.Pass());
580 void RenderWidgetCompositor::StartCompositor() {
581 layer_tree_host_
->SetLayerTreeHostClientReady();
584 void RenderWidgetCompositor::setRootLayer(const blink::WebLayer
& layer
) {
585 layer_tree_host_
->SetRootLayer(
586 static_cast<const cc_blink::WebLayerImpl
*>(&layer
)->layer());
589 void RenderWidgetCompositor::clearRootLayer() {
590 layer_tree_host_
->SetRootLayer(scoped_refptr
<cc::Layer
>());
593 void RenderWidgetCompositor::attachCompositorAnimationTimeline(
594 blink::WebCompositorAnimationTimeline
* compositor_timeline
) {
595 DCHECK(compositor_timeline
);
596 DCHECK(layer_tree_host_
->animation_host());
597 layer_tree_host_
->animation_host()->AddAnimationTimeline(
598 static_cast<const cc_blink::WebCompositorAnimationTimelineImpl
*>(
599 compositor_timeline
)->animation_timeline());
602 void RenderWidgetCompositor::detachCompositorAnimationTimeline(
603 blink::WebCompositorAnimationTimeline
* compositor_timeline
) {
604 DCHECK(compositor_timeline
);
605 DCHECK(layer_tree_host_
->animation_host());
606 layer_tree_host_
->animation_host()->RemoveAnimationTimeline(
607 static_cast<const cc_blink::WebCompositorAnimationTimelineImpl
*>(
608 compositor_timeline
)->animation_timeline());
611 void RenderWidgetCompositor::setViewportSize(
613 const WebSize
& device_viewport_size
) {
614 layer_tree_host_
->SetViewportSize(device_viewport_size
);
617 void RenderWidgetCompositor::setViewportSize(
618 const WebSize
& device_viewport_size
) {
619 layer_tree_host_
->SetViewportSize(device_viewport_size
);
622 WebFloatPoint
RenderWidgetCompositor::adjustEventPointForPinchZoom(
623 const WebFloatPoint
& point
) const {
627 void RenderWidgetCompositor::setDeviceScaleFactor(float device_scale
) {
628 layer_tree_host_
->SetDeviceScaleFactor(device_scale
);
631 float RenderWidgetCompositor::deviceScaleFactor() const {
632 return layer_tree_host_
->device_scale_factor();
635 void RenderWidgetCompositor::setBackgroundColor(blink::WebColor color
) {
636 layer_tree_host_
->set_background_color(color
);
639 void RenderWidgetCompositor::setHasTransparentBackground(bool transparent
) {
640 layer_tree_host_
->set_has_transparent_background(transparent
);
643 void RenderWidgetCompositor::setVisible(bool visible
) {
644 layer_tree_host_
->SetVisible(visible
);
647 void RenderWidgetCompositor::setPageScaleFactorAndLimits(
648 float page_scale_factor
, float minimum
, float maximum
) {
649 layer_tree_host_
->SetPageScaleFactorAndLimits(
650 page_scale_factor
, minimum
, maximum
);
653 void RenderWidgetCompositor::startPageScaleAnimation(
654 const blink::WebPoint
& destination
,
656 float new_page_scale
,
657 double duration_sec
) {
658 base::TimeDelta duration
= base::TimeDelta::FromMicroseconds(
659 duration_sec
* base::Time::kMicrosecondsPerSecond
);
660 layer_tree_host_
->StartPageScaleAnimation(
661 gfx::Vector2d(destination
.x
, destination
.y
),
667 void RenderWidgetCompositor::heuristicsForGpuRasterizationUpdated(
668 bool matches_heuristics
) {
669 layer_tree_host_
->SetHasGpuRasterizationTrigger(matches_heuristics
);
672 void RenderWidgetCompositor::setNeedsAnimate() {
673 layer_tree_host_
->SetNeedsAnimate();
674 layer_tree_host_
->SetNeedsUpdateLayers();
677 void RenderWidgetCompositor::setNeedsBeginFrame() {
678 layer_tree_host_
->SetNeedsAnimate();
681 void RenderWidgetCompositor::setNeedsCompositorUpdate() {
682 layer_tree_host_
->SetNeedsUpdateLayers();
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
705 overscrollElasticityLayer
706 ? static_cast<const cc_blink::WebLayerImpl
*>(
707 overscrollElasticityLayer
)->layer()
709 static_cast<const cc_blink::WebLayerImpl
*>(pageScaleLayer
)->layer(),
710 static_cast<const cc_blink::WebLayerImpl
*>(innerViewportScrollLayer
)
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
717 outerViewportScrollLayer
718 ? static_cast<const cc_blink::WebLayerImpl
*>(outerViewportScrollLayer
)
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
);
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()));
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_
)
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()));
797 layer_tree_host_
->SetNeedsCommit();
801 void RenderWidgetCompositor::SynchronouslyComposite() {
802 DCHECK(CompositeIsSynchronous());
803 layer_tree_host_
->Composite(base::TimeTicks::Now());
806 void RenderWidgetCompositor::setDeferCommits(bool defer_commits
) {
807 layer_tree_host_
->SetDeferCommits(defer_commits
);
810 int RenderWidgetCompositor::layerTreeId() const {
811 return layer_tree_host_
->id();
814 void RenderWidgetCompositor::setShowFPSCounter(bool show
) {
815 cc::LayerTreeDebugState debug_state
= layer_tree_host_
->debug_state();
816 debug_state
.show_fps_counter
= show
;
817 layer_tree_host_
->SetDebugState(debug_state
);
820 void RenderWidgetCompositor::setShowPaintRects(bool show
) {
821 cc::LayerTreeDebugState debug_state
= layer_tree_host_
->debug_state();
822 debug_state
.show_paint_rects
= show
;
823 layer_tree_host_
->SetDebugState(debug_state
);
826 void RenderWidgetCompositor::setShowDebugBorders(bool show
) {
827 cc::LayerTreeDebugState debug_state
= layer_tree_host_
->debug_state();
828 debug_state
.show_debug_borders
= show
;
829 layer_tree_host_
->SetDebugState(debug_state
);
832 void RenderWidgetCompositor::setContinuousPaintingEnabled(bool enabled
) {
833 cc::LayerTreeDebugState debug_state
= layer_tree_host_
->debug_state();
834 debug_state
.continuous_painting
= enabled
;
835 layer_tree_host_
->SetDebugState(debug_state
);
838 void RenderWidgetCompositor::setShowScrollBottleneckRects(bool show
) {
839 cc::LayerTreeDebugState debug_state
= layer_tree_host_
->debug_state();
840 debug_state
.show_touch_event_handler_rects
= show
;
841 debug_state
.show_wheel_event_handler_rects
= show
;
842 debug_state
.show_non_fast_scrollable_rects
= show
;
843 layer_tree_host_
->SetDebugState(debug_state
);
846 void RenderWidgetCompositor::updateTopControlsState(
847 WebTopControlsState constraints
,
848 WebTopControlsState current
,
850 layer_tree_host_
->UpdateTopControlsState(ConvertTopControlsState(constraints
),
851 ConvertTopControlsState(current
),
855 void RenderWidgetCompositor::setTopControlsHeight(float height
, bool shrink
) {
856 layer_tree_host_
->SetTopControlsHeight(height
, shrink
);
859 void RenderWidgetCompositor::setTopControlsShownRatio(float ratio
) {
860 layer_tree_host_
->SetTopControlsShownRatio(ratio
);
863 void RenderWidgetCompositor::setHidePinchScrollbarsNearMinScale(bool hide
) {
864 layer_tree_host_
->set_hide_pinch_scrollbars_near_min_scale(hide
);
867 void RenderWidgetCompositor::WillBeginMainFrame() {
868 widget_
->WillBeginCompositorFrame();
871 void RenderWidgetCompositor::DidBeginMainFrame() {
874 void RenderWidgetCompositor::BeginMainFrame(const cc::BeginFrameArgs
& args
) {
875 double frame_time_sec
= (args
.frame_time
- base::TimeTicks()).InSecondsF();
876 double deadline_sec
= (args
.deadline
- base::TimeTicks()).InSecondsF();
877 double interval_sec
= args
.interval
.InSecondsF();
878 WebBeginFrameArgs web_begin_frame_args
=
879 WebBeginFrameArgs(frame_time_sec
, deadline_sec
, interval_sec
);
880 compositor_deps_
->GetRendererScheduler()->WillBeginFrame(args
);
881 widget_
->webwidget()->beginFrame(web_begin_frame_args
);
884 void RenderWidgetCompositor::BeginMainFrameNotExpectedSoon() {
885 compositor_deps_
->GetRendererScheduler()->BeginFrameNotExpectedSoon();
888 void RenderWidgetCompositor::Layout() {
889 widget_
->webwidget()->layout();
891 if (temporary_copy_output_request_
) {
892 // For WebViewImpl, this will always have a root layer. For other widgets,
893 // the widget may be closed before servicing this request, so ignore it.
894 if (cc::Layer
* root_layer
= layer_tree_host_
->root_layer()) {
895 root_layer
->RequestCopyOfOutput(temporary_copy_output_request_
.Pass());
897 temporary_copy_output_request_
->SendEmptyResult();
898 temporary_copy_output_request_
= nullptr;
903 void RenderWidgetCompositor::ApplyViewportDeltas(
904 const gfx::Vector2dF
& inner_delta
,
905 const gfx::Vector2dF
& outer_delta
,
906 const gfx::Vector2dF
& elastic_overscroll_delta
,
908 float top_controls_delta
) {
909 widget_
->webwidget()->applyViewportDeltas(
912 elastic_overscroll_delta
,
917 void RenderWidgetCompositor::RequestNewOutputSurface() {
918 // If the host is closing, then no more compositing is possible. This
919 // prevents shutdown races between handling the close message and
920 // the CreateOutputSurface task.
921 if (widget_
->host_closing())
925 num_failed_recreate_attempts_
>= OUTPUT_SURFACE_RETRIES_BEFORE_FALLBACK
;
926 scoped_ptr
<cc::OutputSurface
> surface(widget_
->CreateOutputSurface(fallback
));
929 DidFailToInitializeOutputSurface();
933 DCHECK_EQ(surface
->capabilities().max_frames_pending
, 1);
935 layer_tree_host_
->SetOutputSurface(surface
.Pass());
938 void RenderWidgetCompositor::DidInitializeOutputSurface() {
939 num_failed_recreate_attempts_
= 0;
942 void RenderWidgetCompositor::DidFailToInitializeOutputSurface() {
943 ++num_failed_recreate_attempts_
;
944 // Tolerate a certain number of recreation failures to work around races
945 // in the output-surface-lost machinery.
946 LOG_IF(FATAL
, (num_failed_recreate_attempts_
>= MAX_OUTPUT_SURFACE_RETRIES
))
947 << "Failed to create a fallback OutputSurface.";
949 base::ThreadTaskRunnerHandle::Get()->PostTask(
950 FROM_HERE
, base::Bind(&RenderWidgetCompositor::RequestNewOutputSurface
,
951 weak_factory_
.GetWeakPtr()));
954 void RenderWidgetCompositor::WillCommit() {
955 InvokeLayoutAndPaintCallback();
958 void RenderWidgetCompositor::DidCommit() {
959 DCHECK(!temporary_copy_output_request_
);
960 widget_
->DidCommitCompositorFrame();
961 compositor_deps_
->GetRendererScheduler()->DidCommitFrameToCompositor();
964 void RenderWidgetCompositor::DidCommitAndDrawFrame() {
965 widget_
->DidCommitAndDrawCompositorFrame();
968 void RenderWidgetCompositor::DidCompleteSwapBuffers() {
969 widget_
->DidCompleteSwapBuffers();
970 bool threaded
= !!compositor_deps_
->GetCompositorImplThreadTaskRunner().get();
972 widget_
->OnSwapBuffersComplete();
975 void RenderWidgetCompositor::DidCompletePageScaleAnimation() {
976 widget_
->DidCompletePageScaleAnimation();
979 void RenderWidgetCompositor::ScheduleAnimation() {
980 widget_
->scheduleAnimation();
983 void RenderWidgetCompositor::DidPostSwapBuffers() {
984 widget_
->OnSwapBuffersPosted();
987 void RenderWidgetCompositor::DidAbortSwapBuffers() {
988 widget_
->OnSwapBuffersAborted();
991 void RenderWidgetCompositor::RecordFrameTimingEvents(
992 scoped_ptr
<cc::FrameTimingTracker::CompositeTimingSet
> composite_events
,
993 scoped_ptr
<cc::FrameTimingTracker::MainFrameTimingSet
> main_frame_events
) {
994 for (const auto& composite_event
: *composite_events
) {
995 int64_t frameId
= composite_event
.first
;
996 const std::vector
<cc::FrameTimingTracker::CompositeTimingEvent
>& events
=
997 composite_event
.second
;
998 std::vector
<blink::WebFrameTimingEvent
> webEvents
;
999 for (size_t i
= 0; i
< events
.size(); ++i
) {
1000 webEvents
.push_back(blink::WebFrameTimingEvent(
1002 (events
[i
].timestamp
- base::TimeTicks()).InSecondsF()));
1004 widget_
->webwidget()->recordFrameTimingEvent(
1005 blink::WebWidget::CompositeEvent
, frameId
, webEvents
);
1007 for (const auto& main_frame_event
: *main_frame_events
) {
1008 int64_t frameId
= main_frame_event
.first
;
1009 const std::vector
<cc::FrameTimingTracker::MainFrameTimingEvent
>& events
=
1010 main_frame_event
.second
;
1011 std::vector
<blink::WebFrameTimingEvent
> webEvents
;
1012 for (size_t i
= 0; i
< events
.size(); ++i
) {
1013 webEvents
.push_back(blink::WebFrameTimingEvent(
1015 (events
[i
].timestamp
- base::TimeTicks()).InSecondsF(),
1016 (events
[i
].end_time
- base::TimeTicks()).InSecondsF()));
1018 widget_
->webwidget()->recordFrameTimingEvent(
1019 blink::WebWidget::RenderEvent
, frameId
, webEvents
);
1023 void RenderWidgetCompositor::RateLimitSharedMainThreadContext() {
1024 cc::ContextProvider
* provider
=
1025 compositor_deps_
->GetSharedMainThreadContextProvider();
1026 // provider can be NULL after the GPU process crashed enough times and we
1027 // don't want to restart it any more (falling back to software).
1030 provider
->ContextGL()->RateLimitOffscreenContextCHROMIUM();
1033 void RenderWidgetCompositor::SetSurfaceIdNamespace(
1034 uint32_t surface_id_namespace
) {
1035 layer_tree_host_
->set_surface_id_namespace(surface_id_namespace
);
1038 } // namespace content