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

#include "content/renderer/gpu/render_widget_compositor.h"

#include <limits>

#include "base/command_line.h"
#include "base/logging.h"
#include "base/string_number_conversions.h"
#include "base/synchronization/lock.h"
#include "base/time.h"
#include "cc/context_provider.h"
#include "cc/layer.h"
#include "cc/layer_tree_debug_state.h"
#include "cc/layer_tree_host.h"
#include "cc/switches.h"
#include "cc/thread_impl.h"
#include "content/public/common/content_switches.h"
#include "content/renderer/gpu/compositor_thread.h"
#include "content/renderer/render_thread_impl.h"
#include "third_party/WebKit/Source/Platform/chromium/public/WebLayerTreeViewClient.h"
#include "third_party/WebKit/Source/Platform/chromium/public/WebSize.h"
#include "ui/gl/gl_switches.h"
#include "webkit/compositor_bindings/web_layer_impl.h"
#include "webkit/compositor_bindings/web_to_ccinput_handler_adapter.h"

namespace cc {
class Layer;
}

using WebKit::WebFloatPoint;
using WebKit::WebSize;
using WebKit::WebRect;

namespace content {
namespace {

bool GetSwitchValueAsInt(
    const CommandLine& command_line,
    const std::string& switch_string,
    int min_value,
    int max_value,
    int* result) {
  std::string string_value = command_line.GetSwitchValueASCII(switch_string);
  int int_value;
  if (base::StringToInt(string_value, &int_value) &&
      int_value >= min_value && int_value <= max_value) {
    *result = int_value;
    return true;
  } else {
    LOG(WARNING) << "Failed to parse switch " << switch_string  << ": " <<
        string_value;
    return false;
  }
}

bool GetSwitchValueAsFloat(
    const CommandLine& command_line,
    const std::string& switch_string,
    float min_value,
    float max_value,
    float* result) {
  std::string string_value = command_line.GetSwitchValueASCII(switch_string);
  double double_value;
  if (base::StringToDouble(string_value, &double_value) &&
      double_value >= min_value && double_value <= max_value) {
    *result = static_cast<float>(double_value);
    return true;
  } else {
    LOG(WARNING) << "Failed to parse switch " << switch_string  << ": " <<
        string_value;
    return false;
  }
}


}  // namespace

// static
scoped_ptr<RenderWidgetCompositor> RenderWidgetCompositor::Create(
      RenderWidget* widget,
      WebKit::WebLayerTreeViewClient* client,
      WebKit::WebLayerTreeView::Settings web_settings) {
  scoped_ptr<RenderWidgetCompositor> comp(
      new RenderWidgetCompositor(widget, client));

  CommandLine* cmd = CommandLine::ForCurrentProcess();

  cc::LayerTreeSettings settings;
  settings.acceleratePainting =
      cmd->HasSwitch(switches::kEnableAcceleratedPainting);
  settings.renderVSyncEnabled = !cmd->HasSwitch(switches::kDisableGpuVsync);
  settings.perTilePaintingEnabled =
      cmd->HasSwitch(cc::switches::kEnablePerTilePainting);
  settings.acceleratedAnimationEnabled =
      !cmd->HasSwitch(cc::switches::kDisableThreadedAnimation);

  int default_tile_width = settings.defaultTileSize.width();
  if (cmd->HasSwitch(switches::kDefaultTileWidth)) {
    GetSwitchValueAsInt(*cmd, switches::kDefaultTileWidth, 1,
                        std::numeric_limits<int>::max(), &default_tile_width);
  }
  int default_tile_height = settings.defaultTileSize.height();
  if (cmd->HasSwitch(switches::kDefaultTileHeight)) {
    GetSwitchValueAsInt(*cmd, switches::kDefaultTileHeight, 1,
                        std::numeric_limits<int>::max(), &default_tile_height);
  }
  settings.defaultTileSize = gfx::Size(default_tile_width, default_tile_height);

  int max_untiled_layer_width = settings.maxUntiledLayerSize.width();
  if (cmd->HasSwitch(switches::kMaxUntiledLayerWidth)) {
    GetSwitchValueAsInt(*cmd, switches::kMaxUntiledLayerWidth, 1,
                        std::numeric_limits<int>::max(),
                        &max_untiled_layer_width);
  }
  int max_untiled_layer_height = settings.maxUntiledLayerSize.height();
  if (cmd->HasSwitch(switches::kMaxUntiledLayerHeight)) {
    GetSwitchValueAsInt(*cmd, switches::kMaxUntiledLayerHeight, 1,
                        std::numeric_limits<int>::max(),
                        &max_untiled_layer_height);
  }

  settings.maxUntiledLayerSize = gfx::Size(max_untiled_layer_width,
                                           max_untiled_layer_height);

  settings.rightAlignedSchedulingEnabled =
      cmd->HasSwitch(cc::switches::kEnableRightAlignedScheduling);
  settings.implSidePainting = cc::switches::IsImplSidePaintingEnabled();
  settings.useCheapnessEstimator =
      cmd->HasSwitch(cc::switches::kUseCheapnessEstimator);

  settings.calculateTopControlsPosition =
      cmd->HasSwitch(cc::switches::kEnableTopControlsPositionCalculation);
  if (cmd->HasSwitch(cc::switches::kTopControlsHeight)) {
    std::string controls_height_str =
        cmd->GetSwitchValueASCII(cc::switches::kTopControlsHeight);
    double controls_height;
    if (base::StringToDouble(controls_height_str, &controls_height) &&
        controls_height > 0)
      settings.topControlsHeight = controls_height;
  }

  settings.compositorFrameMessage =
      cmd->HasSwitch(cc::switches::kEnableCompositorFrameMessage);

  if (settings.calculateTopControlsPosition &&
      (settings.topControlsHeight <= 0 || !settings.compositorFrameMessage)) {
    DCHECK(false) << "Top controls repositioning enabled without valid height "
                     "or compositorFrameMessage set.";
    settings.calculateTopControlsPosition = false;
  }

  if (cmd->HasSwitch(cc::switches::kTopControlsShowThreshold)) {
      std::string top_threshold_str =
          cmd->GetSwitchValueASCII(cc::switches::kTopControlsShowThreshold);
      double show_threshold;
      if (base::StringToDouble(top_threshold_str, &show_threshold) &&
          show_threshold >= 0.f && show_threshold <= 1.f)
        settings.topControlsShowThreshold = show_threshold;
  }

  if (cmd->HasSwitch(cc::switches::kTopControlsHideThreshold)) {
      std::string top_threshold_str =
          cmd->GetSwitchValueASCII(cc::switches::kTopControlsHideThreshold);
      double hide_threshold;
      if (base::StringToDouble(top_threshold_str, &hide_threshold) &&
          hide_threshold >= 0.f && hide_threshold <= 1.f)
        settings.topControlsHideThreshold = hide_threshold;
  }

  settings.partialSwapEnabled =
      cmd->HasSwitch(cc::switches::kEnablePartialSwap);
  settings.backgroundColorInsteadOfCheckerboard =
      cmd->HasSwitch(cc::switches::kBackgroundColorInsteadOfCheckerboard);
  settings.showOverdrawInTracing =
      cmd->HasSwitch(cc::switches::kTraceOverdraw);

  settings.initialDebugState.showFPSCounter =
      cmd->HasSwitch(switches::kShowFPSCounter);
  settings.initialDebugState.showPaintRects =
      cmd->HasSwitch(switches::kShowPaintRects);
  settings.initialDebugState.showDebugBorders =
      cmd->HasSwitch(switches::kShowCompositedLayerBorders);
  settings.initialDebugState.showPlatformLayerTree =
      cmd->HasSwitch(switches::kShowCompositedLayerTree);

  settings.initialDebugState.showPropertyChangedRects =
      cmd->HasSwitch(cc::switches::kShowPropertyChangedRects);
  settings.initialDebugState.showSurfaceDamageRects =
      cmd->HasSwitch(cc::switches::kShowSurfaceDamageRects);
  settings.initialDebugState.showScreenSpaceRects =
      cmd->HasSwitch(cc::switches::kShowScreenSpaceRects);
  settings.initialDebugState.showReplicaScreenSpaceRects =
      cmd->HasSwitch(cc::switches::kShowReplicaScreenSpaceRects);
  settings.initialDebugState.showOccludingRects =
      cmd->HasSwitch(cc::switches::kShowOccludingRects);
  settings.initialDebugState.showNonOccludingRects =
      cmd->HasSwitch(cc::switches::kShowNonOccludingRects);
  settings.initialDebugState.setRecordRenderingStats(
      cmd->HasSwitch(switches::kEnableGpuBenchmarking));
  settings.initialDebugState.traceAllRenderedFrames =
      cmd->HasSwitch(cc::switches::kTraceAllRenderedFrames);

  if (cmd->HasSwitch(cc::switches::kSlowDownRasterScaleFactor)) {
    const int kMinSlowDownScaleFactor = 0;
    const int kMaxSlowDownScaleFactor = INT_MAX;
    GetSwitchValueAsInt(*cmd, cc::switches::kSlowDownRasterScaleFactor,
                        kMinSlowDownScaleFactor, kMaxSlowDownScaleFactor,
                        &settings.initialDebugState.slowDownRasterScaleFactor);
  }

  if (cmd->HasSwitch(cc::switches::kNumRasterThreads)) {
    const int kMinRasterThreads = 1;
    const int kMaxRasterThreads = 64;
    int num_raster_threads;
    if (GetSwitchValueAsInt(*cmd, cc::switches::kNumRasterThreads,
                            kMinRasterThreads, kMaxRasterThreads,
                            &num_raster_threads))
      settings.numRasterThreads = num_raster_threads;
  }

  if (cmd->HasSwitch(cc::switches::kLowResolutionContentsScaleFactor)) {
    const int kMinScaleFactor = settings.minimumContentsScale;
    const int kMaxScaleFactor = 1;
    GetSwitchValueAsFloat(*cmd,
                          cc::switches::kLowResolutionContentsScaleFactor,
                          kMinScaleFactor, kMaxScaleFactor,
                          &settings.lowResContentsScaleFactor);
  }

#if defined(OS_ANDROID)
  // TODO(danakj): Move these to the android code.
  settings.canUseLCDText = false;
  settings.maxPartialTextureUpdates = 0;
  settings.useLinearFadeScrollbarAnimator = true;
  settings.solidColorScrollbars = true;
  settings.solidColorScrollbarColor = SkColorSetARGB(128, 128, 128, 128);
  settings.solidColorScrollbarThicknessDIP = 3;
#endif

  if (!comp->initialize(settings))
    return scoped_ptr<RenderWidgetCompositor>();

  return comp.Pass();
}

RenderWidgetCompositor::RenderWidgetCompositor(
    RenderWidget* widget, WebKit::WebLayerTreeViewClient* client)
  : suppress_schedule_composite_(false),
    widget_(widget),
    client_(client) {
}

RenderWidgetCompositor::~RenderWidgetCompositor() {}

void RenderWidgetCompositor::SetSuppressScheduleComposite(bool suppress) {
  if (suppress_schedule_composite_ == suppress)
    return;

  if (suppress)
    TRACE_EVENT_ASYNC_BEGIN0("gpu",
        "RenderWidgetCompositor::SetSuppressScheduleComposite", this);
  else
    TRACE_EVENT_ASYNC_END0("gpu",
        "RenderWidgetCompositor::SetSuppressScheduleComposite", this);
  suppress_schedule_composite_ = suppress;
}

bool RenderWidgetCompositor::initialize(cc::LayerTreeSettings settings) {
  scoped_ptr<cc::Thread> impl_thread;
  CompositorThread* compositor_thread =
      RenderThreadImpl::current()->compositor_thread();
  threaded_ = !!compositor_thread;
  if (compositor_thread)
    impl_thread = cc::ThreadImpl::createForDifferentThread(
        compositor_thread->message_loop()->message_loop_proxy());
  layer_tree_host_ = cc::LayerTreeHost::create(this,
                                               settings,
                                               impl_thread.Pass());
  return layer_tree_host_;
}

void RenderWidgetCompositor::setSurfaceReady() {
  layer_tree_host_->setSurfaceReady();
}

void RenderWidgetCompositor::setRootLayer(const WebKit::WebLayer& layer) {
  layer_tree_host_->setRootLayer(
      static_cast<const WebKit::WebLayerImpl*>(&layer)->layer());
}

void RenderWidgetCompositor::clearRootLayer() {
  layer_tree_host_->setRootLayer(scoped_refptr<cc::Layer>());
}

void RenderWidgetCompositor::setViewportSize(
    const WebSize& layout_viewport_size,
    const WebSize& device_viewport_size) {
  layer_tree_host_->setViewportSize(layout_viewport_size, device_viewport_size);
}

WebSize RenderWidgetCompositor::layoutViewportSize() const {
  return layer_tree_host_->layoutViewportSize();
}

WebSize RenderWidgetCompositor::deviceViewportSize() const {
  return layer_tree_host_->deviceViewportSize();
}

WebFloatPoint RenderWidgetCompositor::adjustEventPointForPinchZoom(
    const WebFloatPoint& point) const {
  return point;
}

void RenderWidgetCompositor::setDeviceScaleFactor(float device_scale) {
  layer_tree_host_->setDeviceScaleFactor(device_scale);
}

float RenderWidgetCompositor::deviceScaleFactor() const {
  return layer_tree_host_->deviceScaleFactor();
}

void RenderWidgetCompositor::setBackgroundColor(WebKit::WebColor color) {
  layer_tree_host_->setBackgroundColor(color);
}

void RenderWidgetCompositor::setHasTransparentBackground(bool transparent) {
  layer_tree_host_->setHasTransparentBackground(transparent);
}

void RenderWidgetCompositor::setVisible(bool visible) {
  layer_tree_host_->setVisible(visible);
}

void RenderWidgetCompositor::setPageScaleFactorAndLimits(
    float page_scale_factor, float minimum, float maximum) {
  layer_tree_host_->setPageScaleFactorAndLimits(
      page_scale_factor, minimum, maximum);
}

void RenderWidgetCompositor::startPageScaleAnimation(
    const WebKit::WebPoint& destination,
    bool use_anchor,
    float new_page_scale,
    double duration_sec) {
  base::TimeDelta duration = base::TimeDelta::FromMicroseconds(
      duration_sec * base::Time::kMicrosecondsPerSecond);
  layer_tree_host_->startPageScaleAnimation(
      gfx::Vector2d(destination.x, destination.y),
      use_anchor,
      new_page_scale,
      duration);
}

void RenderWidgetCompositor::setNeedsAnimate() {
  layer_tree_host_->setNeedsAnimate();
}

void RenderWidgetCompositor::setNeedsRedraw() {
  if (threaded_)
    layer_tree_host_->setNeedsAnimate();
  else
    widget_->scheduleAnimation();
}

bool RenderWidgetCompositor::commitRequested() const {
  return layer_tree_host_->commitRequested();
}

void RenderWidgetCompositor::composite() {
  layer_tree_host_->composite();
}

void RenderWidgetCompositor::updateAnimations(double frame_begin_time_sec) {
  base::TimeTicks frame_begin_time =
    base::TimeTicks::FromInternalValue(frame_begin_time_sec *
                                       base::Time::kMicrosecondsPerSecond);
  layer_tree_host_->updateAnimations(frame_begin_time);
}

void RenderWidgetCompositor::didStopFlinging() {
  layer_tree_host_->didStopFlinging();
}

bool RenderWidgetCompositor::compositeAndReadback(void *pixels,
                                                  const WebRect& rect) {
  return layer_tree_host_->compositeAndReadback(pixels, rect);
}

void RenderWidgetCompositor::finishAllRendering() {
  layer_tree_host_->finishAllRendering();
}

void RenderWidgetCompositor::setDeferCommits(bool defer_commits) {
  layer_tree_host_->setDeferCommits(defer_commits);
}

void RenderWidgetCompositor::setShowFPSCounter(bool show) {
  cc::LayerTreeDebugState debug_state = layer_tree_host_->debugState();
  debug_state.showFPSCounter = show;
  layer_tree_host_->setDebugState(debug_state);
}

void RenderWidgetCompositor::setShowPaintRects(bool show) {
  cc::LayerTreeDebugState debug_state = layer_tree_host_->debugState();
  debug_state.showPaintRects = show;
  layer_tree_host_->setDebugState(debug_state);
}

void RenderWidgetCompositor::setShowDebugBorders(bool show) {
  cc::LayerTreeDebugState debug_state = layer_tree_host_->debugState();
  debug_state.showDebugBorders = show;
  layer_tree_host_->setDebugState(debug_state);
}

void RenderWidgetCompositor::setContinuousPaintingEnabled(bool enabled) {
  cc::LayerTreeDebugState debug_state = layer_tree_host_->debugState();
  debug_state.continuousPainting = enabled;
  layer_tree_host_->setDebugState(debug_state);
}

void RenderWidgetCompositor::willBeginFrame() {
  widget_->InstrumentWillBeginFrame();
  widget_->willBeginCompositorFrame();
}

void RenderWidgetCompositor::didBeginFrame() {
  widget_->InstrumentDidBeginFrame();
}

void RenderWidgetCompositor::animate(double monotonic_frame_begin_time) {
  widget_->webwidget()->animate(monotonic_frame_begin_time);
}

// Can delete from WebLayerTreeViewClient
void RenderWidgetCompositor::layout() {
  widget_->webwidget()->layout();
}

// TODO(jamesr): This should go through WebWidget
void RenderWidgetCompositor::applyScrollAndScale(gfx::Vector2d scroll_delta,
                                                 float page_scale) {
  client_->applyScrollAndScale(scroll_delta, page_scale);
}

scoped_ptr<cc::OutputSurface> RenderWidgetCompositor::createOutputSurface() {
  return widget_->CreateOutputSurface();
}

// TODO(jamesr): This should go through WebWidget
void RenderWidgetCompositor::didRecreateOutputSurface(bool success) {
  client_->didRecreateOutputSurface(success);
}

// TODO(jamesr): This should go through WebWidget
scoped_ptr<cc::InputHandler> RenderWidgetCompositor::createInputHandler() {
  scoped_ptr<cc::InputHandler> ret;
  scoped_ptr<WebKit::WebInputHandler> web_handler(
      client_->createInputHandler());
  if (web_handler)
     ret = WebKit::WebToCCInputHandlerAdapter::create(web_handler.Pass());
  return ret.Pass();
}

void RenderWidgetCompositor::willCommit() {
  widget_->InstrumentWillComposite();
}

void RenderWidgetCompositor::didCommit() {
  widget_->DidCommitCompositorFrame();
  widget_->didBecomeReadyForAdditionalInput();
}

void RenderWidgetCompositor::didCommitAndDrawFrame() {
  widget_->didCommitAndDrawCompositorFrame();
}

void RenderWidgetCompositor::didCompleteSwapBuffers() {
  widget_->didCompleteSwapBuffers();
}

void RenderWidgetCompositor::scheduleComposite() {
  if (!suppress_schedule_composite_)
    widget_->scheduleComposite();
}

scoped_refptr<cc::ContextProvider>
RenderWidgetCompositor::OffscreenContextProviderForMainThread() {
  return RenderThreadImpl::current()->OffscreenContextProviderForMainThread();
}

scoped_refptr<cc::ContextProvider>
RenderWidgetCompositor::OffscreenContextProviderForCompositorThread() {
  return RenderThreadImpl::current()->
      OffscreenContextProviderForCompositorThread();
}

}  // namespace content