chrome/browser/extensions: Remove use of MessageLoopProxy and deprecated MessageLoop...
[chromium-blink-merge.git] / content / browser / renderer_host / render_widget_host_view_android.cc
blobabdb9eba431b6d22f2f20412fe2d875069cc7470
1 // Copyright (c) 2012 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/browser/renderer_host/render_widget_host_view_android.h"
7 #include <android/bitmap.h>
9 #include "base/android/build_info.h"
10 #include "base/basictypes.h"
11 #include "base/bind.h"
12 #include "base/callback_helpers.h"
13 #include "base/command_line.h"
14 #include "base/logging.h"
15 #include "base/message_loop/message_loop.h"
16 #include "base/metrics/histogram.h"
17 #include "base/strings/utf_string_conversions.h"
18 #include "base/sys_info.h"
19 #include "base/threading/worker_pool.h"
20 #include "cc/layers/delegated_frame_provider.h"
21 #include "cc/layers/delegated_renderer_layer.h"
22 #include "cc/layers/layer.h"
23 #include "cc/layers/surface_layer.h"
24 #include "cc/output/compositor_frame.h"
25 #include "cc/output/compositor_frame_ack.h"
26 #include "cc/output/copy_output_request.h"
27 #include "cc/output/copy_output_result.h"
28 #include "cc/output/latency_info_swap_promise.h"
29 #include "cc/output/viewport_selection_bound.h"
30 #include "cc/resources/single_release_callback.h"
31 #include "cc/surfaces/surface.h"
32 #include "cc/surfaces/surface_factory.h"
33 #include "cc/surfaces/surface_id_allocator.h"
34 #include "cc/surfaces/surface_manager.h"
35 #include "cc/trees/layer_tree_host.h"
36 #include "content/browser/accessibility/browser_accessibility_manager_android.h"
37 #include "content/browser/android/composited_touch_handle_drawable.h"
38 #include "content/browser/android/content_view_core_impl.h"
39 #include "content/browser/android/edge_effect.h"
40 #include "content/browser/android/edge_effect_l.h"
41 #include "content/browser/android/in_process/synchronous_compositor_impl.h"
42 #include "content/browser/android/overscroll_controller_android.h"
43 #include "content/browser/devtools/render_frame_devtools_agent_host.h"
44 #include "content/browser/gpu/browser_gpu_channel_host_factory.h"
45 #include "content/browser/gpu/compositor_util.h"
46 #include "content/browser/gpu/gpu_data_manager_impl.h"
47 #include "content/browser/gpu/gpu_process_host_ui_shim.h"
48 #include "content/browser/gpu/gpu_surface_tracker.h"
49 #include "content/browser/media/media_web_contents_observer.h"
50 #include "content/browser/renderer_host/compositor_impl_android.h"
51 #include "content/browser/renderer_host/dip_util.h"
52 #include "content/browser/renderer_host/frame_metadata_util.h"
53 #include "content/browser/renderer_host/input/synthetic_gesture_target_android.h"
54 #include "content/browser/renderer_host/input/ui_touch_selection_helper.h"
55 #include "content/browser/renderer_host/input/web_input_event_builders_android.h"
56 #include "content/browser/renderer_host/input/web_input_event_util.h"
57 #include "content/browser/renderer_host/render_process_host_impl.h"
58 #include "content/browser/renderer_host/render_view_host_impl.h"
59 #include "content/browser/renderer_host/render_widget_host_impl.h"
60 #include "content/common/gpu/client/gl_helper.h"
61 #include "content/common/gpu/client/webgraphicscontext3d_command_buffer_impl.h"
62 #include "content/common/gpu/gpu_messages.h"
63 #include "content/common/gpu/gpu_process_launch_causes.h"
64 #include "content/common/input/did_overscroll_params.h"
65 #include "content/common/input_messages.h"
66 #include "content/common/view_messages.h"
67 #include "content/public/browser/android/compositor.h"
68 #include "content/public/browser/browser_thread.h"
69 #include "content/public/browser/devtools_agent_host.h"
70 #include "content/public/browser/render_view_host.h"
71 #include "content/public/browser/render_widget_host_iterator.h"
72 #include "content/public/common/content_switches.h"
73 #include "gpu/command_buffer/client/gles2_implementation.h"
74 #include "gpu/command_buffer/client/gles2_interface.h"
75 #include "gpu/config/gpu_driver_bug_workaround_type.h"
76 #include "skia/ext/image_operations.h"
77 #include "third_party/khronos/GLES2/gl2.h"
78 #include "third_party/khronos/GLES2/gl2ext.h"
79 #include "third_party/skia/include/core/SkCanvas.h"
80 #include "ui/android/window_android.h"
81 #include "ui/android/window_android_compositor.h"
82 #include "ui/events/blink/blink_event_util.h"
83 #include "ui/events/gesture_detection/gesture_provider_config_helper.h"
84 #include "ui/events/gesture_detection/motion_event.h"
85 #include "ui/gfx/android/device_display_info.h"
86 #include "ui/gfx/android/java_bitmap.h"
87 #include "ui/gfx/android/view_configuration.h"
88 #include "ui/gfx/display.h"
89 #include "ui/gfx/geometry/dip_util.h"
90 #include "ui/gfx/geometry/size_conversions.h"
91 #include "ui/gfx/screen.h"
92 #include "ui/touch_selection/touch_selection_controller.h"
94 namespace content {
96 namespace {
98 void SatisfyCallback(cc::SurfaceManager* manager,
99 cc::SurfaceSequence sequence) {
100 std::vector<uint32_t> sequences;
101 sequences.push_back(sequence.sequence);
102 manager->DidSatisfySequences(sequence.id_namespace, &sequences);
105 void RequireCallback(cc::SurfaceManager* manager,
106 cc::SurfaceId id,
107 cc::SurfaceSequence sequence) {
108 cc::Surface* surface = manager->GetSurfaceForId(id);
109 if (!surface) {
110 LOG(ERROR) << "Attempting to require callback on nonexistent surface";
111 return;
113 surface->AddDestructionDependency(sequence);
116 const int kUndefinedOutputSurfaceId = -1;
118 static const char kAsyncReadBackString[] = "Compositing.CopyFromSurfaceTime";
120 // Sends an acknowledgement to the renderer of a processed IME event.
121 void SendImeEventAck(RenderWidgetHostImpl* host) {
122 host->Send(new ViewMsg_ImeEventAck(host->GetRoutingID()));
125 class GLHelperHolder
126 : public blink::WebGraphicsContext3D::WebGraphicsContextLostCallback {
127 public:
128 static GLHelperHolder* Create();
129 ~GLHelperHolder() override;
131 void Initialize();
133 // WebGraphicsContextLostCallback implementation.
134 void onContextLost() override;
136 GLHelper* GetGLHelper() { return gl_helper_.get(); }
137 bool IsLost() { return !context_.get() || context_->isContextLost(); }
139 private:
140 GLHelperHolder();
141 static scoped_ptr<WebGraphicsContext3DCommandBufferImpl> CreateContext3D();
143 scoped_ptr<WebGraphicsContext3DCommandBufferImpl> context_;
144 scoped_ptr<GLHelper> gl_helper_;
146 DISALLOW_COPY_AND_ASSIGN(GLHelperHolder);
149 GLHelperHolder* GLHelperHolder::Create() {
150 GLHelperHolder* holder = new GLHelperHolder;
151 holder->Initialize();
153 return holder;
156 GLHelperHolder::GLHelperHolder() {
159 GLHelperHolder::~GLHelperHolder() {
162 void GLHelperHolder::Initialize() {
163 context_ = CreateContext3D();
164 if (context_) {
165 context_->setContextLostCallback(this);
166 gl_helper_.reset(new GLHelper(context_->GetImplementation(),
167 context_->GetContextSupport()));
171 void GLHelperHolder::onContextLost() {
172 // Need to post a task because the command buffer client cannot be deleted
173 // from within this callback.
174 LOG(ERROR) << "Context lost.";
175 base::MessageLoop::current()->PostTask(
176 FROM_HERE,
177 base::Bind(&RenderWidgetHostViewAndroid::OnContextLost));
180 scoped_ptr<WebGraphicsContext3DCommandBufferImpl>
181 GLHelperHolder::CreateContext3D() {
182 BrowserGpuChannelHostFactory* factory =
183 BrowserGpuChannelHostFactory::instance();
184 scoped_refptr<GpuChannelHost> gpu_channel_host(factory->GetGpuChannel());
185 // GLHelper can only be used in asynchronous APIs for postprocessing after
186 // Browser Compositor operations (i.e. readback).
187 if (!gpu_channel_host.get()) {
188 // The Browser Compositor is in charge of reestablishing the channel.
189 return scoped_ptr<WebGraphicsContext3DCommandBufferImpl>();
192 blink::WebGraphicsContext3D::Attributes attrs;
193 attrs.shareResources = true;
194 GURL url("chrome://gpu/RenderWidgetHostViewAndroid");
195 static const size_t kBytesPerPixel = 4;
196 gfx::DeviceDisplayInfo display_info;
197 size_t full_screen_texture_size_in_bytes = display_info.GetDisplayHeight() *
198 display_info.GetDisplayWidth() *
199 kBytesPerPixel;
200 WebGraphicsContext3DCommandBufferImpl::SharedMemoryLimits limits;
201 limits.command_buffer_size = 64 * 1024;
202 limits.start_transfer_buffer_size = 64 * 1024;
203 limits.min_transfer_buffer_size = 64 * 1024;
204 limits.max_transfer_buffer_size = std::min(
205 3 * full_screen_texture_size_in_bytes, kDefaultMaxTransferBufferSize);
206 limits.mapped_memory_reclaim_limit =
207 WebGraphicsContext3DCommandBufferImpl::kNoLimit;
208 bool lose_context_when_out_of_memory = false;
209 scoped_ptr<WebGraphicsContext3DCommandBufferImpl> context(
210 new WebGraphicsContext3DCommandBufferImpl(
211 0, // offscreen
212 url, gpu_channel_host.get(), attrs, lose_context_when_out_of_memory,
213 limits, nullptr));
214 context->SetContextType(BROWSER_OFFSCREEN_MAINTHREAD_CONTEXT);
215 if (context->InitializeOnCurrentThread()) {
216 context->traceBeginCHROMIUM(
217 "gpu_toplevel",
218 base::StringPrintf("CmdBufferImageTransportFactory-%p",
219 context.get()).c_str());
220 } else {
221 context.reset();
224 return context.Pass();
227 // This can only be used for readback postprocessing. It may return null if the
228 // channel was lost and not reestablished yet.
229 GLHelper* GetPostReadbackGLHelper() {
230 static GLHelperHolder* g_readback_helper_holder = nullptr;
232 if (g_readback_helper_holder && g_readback_helper_holder->IsLost()) {
233 delete g_readback_helper_holder;
234 g_readback_helper_holder = nullptr;
237 if (!g_readback_helper_holder)
238 g_readback_helper_holder = GLHelperHolder::Create();
240 return g_readback_helper_holder->GetGLHelper();
243 void CopyFromCompositingSurfaceFinished(
244 ReadbackRequestCallback& callback,
245 scoped_ptr<cc::SingleReleaseCallback> release_callback,
246 scoped_ptr<SkBitmap> bitmap,
247 const base::TimeTicks& start_time,
248 scoped_ptr<SkAutoLockPixels> bitmap_pixels_lock,
249 bool result) {
250 TRACE_EVENT0(
251 "cc", "RenderWidgetHostViewAndroid::CopyFromCompositingSurfaceFinished");
252 bitmap_pixels_lock.reset();
253 uint32 sync_point = 0;
254 if (result) {
255 GLHelper* gl_helper = GetPostReadbackGLHelper();
256 if (gl_helper)
257 sync_point = gl_helper->InsertSyncPoint();
259 bool lost_resource = sync_point == 0;
260 release_callback->Run(sync_point, lost_resource);
261 UMA_HISTOGRAM_TIMES(kAsyncReadBackString,
262 base::TimeTicks::Now() - start_time);
263 ReadbackResponse response = result ? READBACK_SUCCESS : READBACK_FAILED;
264 callback.Run(*bitmap, response);
267 scoped_ptr<ui::TouchSelectionController> CreateSelectionController(
268 ui::TouchSelectionControllerClient* client,
269 ContentViewCore* content_view_core) {
270 DCHECK(client);
271 DCHECK(content_view_core);
272 ui::TouchSelectionController::Config config;
273 config.tap_timeout = base::TimeDelta::FromMilliseconds(
274 gfx::ViewConfiguration::GetTapTimeoutInMs());
275 config.tap_slop = gfx::ViewConfiguration::GetTouchSlopInPixels() /
276 content_view_core->GetDpiScale();
277 config.show_on_tap_for_empty_editable = false;
278 config.enable_longpress_drag_selection =
279 base::CommandLine::ForCurrentProcess()->HasSwitch(
280 switches::kEnableLongpressDragSelection);
281 return make_scoped_ptr(new ui::TouchSelectionController(client, config));
284 scoped_ptr<OverscrollControllerAndroid> CreateOverscrollController(
285 ContentViewCoreImpl* content_view_core) {
286 return make_scoped_ptr(new OverscrollControllerAndroid(content_view_core));
289 ui::GestureProvider::Config CreateGestureProviderConfig() {
290 ui::GestureProvider::Config config = ui::GetGestureProviderConfig(
291 ui::GestureProviderConfigType::CURRENT_PLATFORM);
292 config.disable_click_delay =
293 base::CommandLine::ForCurrentProcess()->HasSwitch(
294 switches::kDisableClickDelay);
295 return config;
298 gfx::RectF GetSelectionRect(const ui::TouchSelectionController& controller) {
299 gfx::RectF rect = controller.GetRectBetweenBounds();
300 if (rect.IsEmpty())
301 return rect;
303 rect.Union(controller.GetStartHandleRect());
304 rect.Union(controller.GetEndHandleRect());
305 return rect;
308 } // anonymous namespace
310 RenderWidgetHostViewAndroid::LastFrameInfo::LastFrameInfo(
311 uint32 output_id,
312 scoped_ptr<cc::CompositorFrame> output_frame)
313 : output_surface_id(output_id), frame(output_frame.Pass()) {}
315 RenderWidgetHostViewAndroid::LastFrameInfo::~LastFrameInfo() {}
317 void RenderWidgetHostViewAndroid::OnContextLost() {
318 scoped_ptr<RenderWidgetHostIterator> widgets(
319 RenderWidgetHostImpl::GetAllRenderWidgetHosts());
320 while (RenderWidgetHost* widget = widgets->GetNextHost()) {
321 if (widget->GetView()) {
322 static_cast<RenderWidgetHostViewAndroid*>(widget->GetView())
323 ->OnLostResources();
328 RenderWidgetHostViewAndroid::RenderWidgetHostViewAndroid(
329 RenderWidgetHostImpl* widget_host,
330 ContentViewCoreImpl* content_view_core)
331 : host_(widget_host),
332 outstanding_vsync_requests_(0),
333 is_showing_(!widget_host->is_hidden()),
334 content_view_core_(nullptr),
335 content_view_core_window_android_(nullptr),
336 ime_adapter_android_(this),
337 cached_background_color_(SK_ColorWHITE),
338 last_output_surface_id_(kUndefinedOutputSurfaceId),
339 gesture_provider_(CreateGestureProviderConfig(), this),
340 stylus_text_selector_(this),
341 accelerated_surface_route_id_(0),
342 using_browser_compositor_(CompositorImpl::IsInitialized()),
343 frame_evictor_(new DelegatedFrameEvictor(this)),
344 locks_on_frame_count_(0),
345 observing_root_window_(false),
346 weak_ptr_factory_(this) {
347 if (CompositorImpl::GetSurfaceManager())
348 id_allocator_ = CompositorImpl::CreateSurfaceIdAllocator();
349 host_->SetView(this);
350 SetContentViewCore(content_view_core);
353 RenderWidgetHostViewAndroid::~RenderWidgetHostViewAndroid() {
354 SetContentViewCore(NULL);
355 DCHECK(ack_callbacks_.empty());
356 if (resource_collection_.get())
357 resource_collection_->SetClient(NULL);
358 DCHECK(!surface_factory_);
359 DCHECK(surface_id_.is_null());
362 void RenderWidgetHostViewAndroid::Blur() {
363 host_->SetInputMethodActive(false);
364 host_->Blur();
365 if (overscroll_controller_)
366 overscroll_controller_->Disable();
369 bool RenderWidgetHostViewAndroid::OnMessageReceived(
370 const IPC::Message& message) {
371 bool handled = true;
372 IPC_BEGIN_MESSAGE_MAP(RenderWidgetHostViewAndroid, message)
373 IPC_MESSAGE_HANDLER(ViewHostMsg_StartContentIntent, OnStartContentIntent)
374 IPC_MESSAGE_HANDLER(ViewHostMsg_DidChangeBodyBackgroundColor,
375 OnDidChangeBodyBackgroundColor)
376 IPC_MESSAGE_HANDLER(ViewHostMsg_SetNeedsBeginFrames,
377 OnSetNeedsBeginFrames)
378 IPC_MESSAGE_HANDLER(ViewHostMsg_TextInputStateChanged,
379 OnTextInputStateChanged)
380 IPC_MESSAGE_HANDLER(ViewHostMsg_SmartClipDataExtracted,
381 OnSmartClipDataExtracted)
382 IPC_MESSAGE_HANDLER(ViewHostMsg_ShowUnhandledTapUIIfNeeded,
383 OnShowUnhandledTapUIIfNeeded)
384 IPC_MESSAGE_UNHANDLED(handled = false)
385 IPC_END_MESSAGE_MAP()
386 return handled;
389 void RenderWidgetHostViewAndroid::InitAsChild(gfx::NativeView parent_view) {
390 NOTIMPLEMENTED();
393 void RenderWidgetHostViewAndroid::InitAsPopup(
394 RenderWidgetHostView* parent_host_view, const gfx::Rect& pos) {
395 NOTIMPLEMENTED();
398 void RenderWidgetHostViewAndroid::InitAsFullscreen(
399 RenderWidgetHostView* reference_host_view) {
400 NOTIMPLEMENTED();
403 RenderWidgetHost*
404 RenderWidgetHostViewAndroid::GetRenderWidgetHost() const {
405 return host_;
408 void RenderWidgetHostViewAndroid::WasResized() {
409 host_->WasResized();
412 void RenderWidgetHostViewAndroid::SetSize(const gfx::Size& size) {
413 // Ignore the given size as only the Java code has the power to
414 // resize the view on Android.
415 default_size_ = size;
418 void RenderWidgetHostViewAndroid::SetBounds(const gfx::Rect& rect) {
419 SetSize(rect.size());
422 void RenderWidgetHostViewAndroid::GetScaledContentBitmap(
423 float scale,
424 SkColorType preferred_color_type,
425 gfx::Rect src_subrect,
426 ReadbackRequestCallback& result_callback) {
427 if (!host_ || host_->is_hidden() || !IsSurfaceAvailableForCopy()) {
428 result_callback.Run(SkBitmap(), READBACK_SURFACE_UNAVAILABLE);
429 return;
431 gfx::Size bounds = layer_->bounds();
432 if (src_subrect.IsEmpty())
433 src_subrect = gfx::Rect(bounds);
434 DCHECK_LE(src_subrect.width() + src_subrect.x(), bounds.width());
435 DCHECK_LE(src_subrect.height() + src_subrect.y(), bounds.height());
436 const gfx::Display& display =
437 gfx::Screen::GetNativeScreen()->GetPrimaryDisplay();
438 float device_scale_factor = display.device_scale_factor();
439 DCHECK_GT(device_scale_factor, 0);
440 gfx::Size dst_size(
441 gfx::ToCeiledSize(gfx::ScaleSize(bounds, scale / device_scale_factor)));
442 CopyFromCompositingSurface(src_subrect, dst_size, result_callback,
443 preferred_color_type);
446 scoped_refptr<cc::Layer> RenderWidgetHostViewAndroid::CreateDelegatedLayer()
447 const {
448 scoped_refptr<cc::Layer> delegated_layer;
449 if (!surface_id_.is_null()) {
450 cc::SurfaceManager* manager = CompositorImpl::GetSurfaceManager();
451 DCHECK(manager);
452 // manager must outlive compositors using it.
453 scoped_refptr<cc::SurfaceLayer> surface_layer = cc::SurfaceLayer::Create(
454 Compositor::LayerSettings(),
455 base::Bind(&SatisfyCallback, base::Unretained(manager)),
456 base::Bind(&RequireCallback, base::Unretained(manager)));
457 surface_layer->SetSurfaceId(surface_id_, 1.f, texture_size_in_layer_);
458 delegated_layer = surface_layer;
459 } else {
460 DCHECK(frame_provider_.get());
461 delegated_layer = cc::DelegatedRendererLayer::Create(
462 Compositor::LayerSettings(), frame_provider_);
464 delegated_layer->SetBounds(content_size_in_layer_);
465 delegated_layer->SetIsDrawable(true);
466 delegated_layer->SetContentsOpaque(true);
468 return delegated_layer;
471 bool RenderWidgetHostViewAndroid::HasValidFrame() const {
472 if (!content_view_core_)
473 return false;
474 if (!layer_.get())
475 return false;
477 if (texture_size_in_layer_.IsEmpty())
478 return false;
479 // This tell us whether a valid frame has arrived or not.
480 if (!frame_evictor_->HasFrame())
481 return false;
483 return true;
486 gfx::Vector2dF RenderWidgetHostViewAndroid::GetLastScrollOffset() const {
487 return last_scroll_offset_;
490 gfx::NativeView RenderWidgetHostViewAndroid::GetNativeView() const {
491 return content_view_core_->GetViewAndroid();
494 gfx::NativeViewId RenderWidgetHostViewAndroid::GetNativeViewId() const {
495 return reinterpret_cast<gfx::NativeViewId>(
496 const_cast<RenderWidgetHostViewAndroid*>(this));
499 gfx::NativeViewAccessible
500 RenderWidgetHostViewAndroid::GetNativeViewAccessible() {
501 NOTIMPLEMENTED();
502 return NULL;
505 void RenderWidgetHostViewAndroid::MovePluginWindows(
506 const std::vector<WebPluginGeometry>& moves) {
507 // We don't have plugin windows on Android. Do nothing. Note: this is called
508 // from RenderWidgetHost::OnUpdateRect which is itself invoked while
509 // processing the corresponding message from Renderer.
512 void RenderWidgetHostViewAndroid::Focus() {
513 host_->Focus();
514 host_->SetInputMethodActive(true);
515 if (overscroll_controller_)
516 overscroll_controller_->Enable();
519 bool RenderWidgetHostViewAndroid::HasFocus() const {
520 if (!content_view_core_)
521 return false; // ContentViewCore not created yet.
523 return content_view_core_->HasFocus();
526 bool RenderWidgetHostViewAndroid::IsSurfaceAvailableForCopy() const {
527 return HasValidFrame();
530 void RenderWidgetHostViewAndroid::Show() {
531 if (is_showing_)
532 return;
534 is_showing_ = true;
535 ShowInternal();
538 void RenderWidgetHostViewAndroid::Hide() {
539 if (!is_showing_)
540 return;
542 is_showing_ = false;
544 bool hide_frontbuffer = true;
545 bool stop_observing_root_window = true;
546 HideInternal(hide_frontbuffer, stop_observing_root_window);
549 bool RenderWidgetHostViewAndroid::IsShowing() {
550 // ContentViewCoreImpl represents the native side of the Java
551 // ContentViewCore. It being NULL means that it is not attached
552 // to the View system yet, so we treat this RWHVA as hidden.
553 return is_showing_ && content_view_core_;
556 void RenderWidgetHostViewAndroid::LockCompositingSurface() {
557 DCHECK(HasValidFrame());
558 DCHECK(host_);
559 DCHECK(frame_evictor_->HasFrame());
560 frame_evictor_->LockFrame();
561 locks_on_frame_count_++;
564 void RenderWidgetHostViewAndroid::UnlockCompositingSurface() {
565 if (!frame_evictor_->HasFrame() || locks_on_frame_count_ == 0)
566 return;
568 DCHECK(HasValidFrame());
569 frame_evictor_->UnlockFrame();
570 locks_on_frame_count_--;
572 if (locks_on_frame_count_ == 0) {
573 if (last_frame_info_) {
574 InternalSwapCompositorFrame(last_frame_info_->output_surface_id,
575 last_frame_info_->frame.Pass());
576 last_frame_info_.reset();
579 if (!is_showing_ && layer_.get())
580 layer_->SetHideLayerAndSubtree(true);
584 void RenderWidgetHostViewAndroid::SetTextSurroundingSelectionCallback(
585 const TextSurroundingSelectionCallback& callback) {
586 // Only one outstanding request is allowed at any given time.
587 DCHECK(!callback.is_null());
588 text_surrounding_selection_callback_ = callback;
591 void RenderWidgetHostViewAndroid::OnTextSurroundingSelectionResponse(
592 const base::string16& content,
593 size_t start_offset,
594 size_t end_offset) {
595 if (text_surrounding_selection_callback_.is_null())
596 return;
597 text_surrounding_selection_callback_.Run(content, start_offset, end_offset);
598 text_surrounding_selection_callback_.Reset();
601 void RenderWidgetHostViewAndroid::OnShowUnhandledTapUIIfNeeded(int x_dip,
602 int y_dip) {
603 if (!content_view_core_)
604 return;
605 // Validate the coordinates are within the viewport.
606 gfx::Size viewport_size = content_view_core_->GetViewportSizeDip();
607 if (x_dip < 0 || x_dip > viewport_size.width() ||
608 y_dip < 0 || y_dip > viewport_size.height())
609 return;
610 content_view_core_->OnShowUnhandledTapUIIfNeeded(x_dip, y_dip);
613 void RenderWidgetHostViewAndroid::ReleaseLocksOnSurface() {
614 if (!frame_evictor_->HasFrame()) {
615 DCHECK_EQ(locks_on_frame_count_, 0u);
616 return;
618 while (locks_on_frame_count_ > 0) {
619 UnlockCompositingSurface();
621 RunAckCallbacks(cc::SurfaceDrawStatus::DRAW_SKIPPED);
624 gfx::Rect RenderWidgetHostViewAndroid::GetViewBounds() const {
625 if (!content_view_core_)
626 return gfx::Rect(default_size_);
628 return gfx::Rect(content_view_core_->GetViewSize());
631 gfx::Size RenderWidgetHostViewAndroid::GetPhysicalBackingSize() const {
632 if (!content_view_core_)
633 return gfx::Size();
635 return content_view_core_->GetPhysicalBackingSize();
638 bool RenderWidgetHostViewAndroid::DoTopControlsShrinkBlinkSize() const {
639 if (!content_view_core_)
640 return false;
642 // Whether or not Blink's viewport size should be shrunk by the height of the
643 // URL-bar.
644 return content_view_core_->DoTopControlsShrinkBlinkSize();
647 float RenderWidgetHostViewAndroid::GetTopControlsHeight() const {
648 if (!content_view_core_)
649 return 0.f;
651 // The height of the top controls.
652 return content_view_core_->GetTopControlsHeightDip();
655 void RenderWidgetHostViewAndroid::UpdateCursor(const WebCursor& cursor) {
656 // There are no cursors on Android.
659 void RenderWidgetHostViewAndroid::SetIsLoading(bool is_loading) {
660 // Do nothing. The UI notification is handled through ContentViewClient which
661 // is TabContentsDelegate.
664 void RenderWidgetHostViewAndroid::TextInputTypeChanged(
665 ui::TextInputType type,
666 ui::TextInputMode input_mode,
667 bool can_compose_inline,
668 int flags) {
669 // Unused on Android, which uses OnTextInputChanged instead.
672 long RenderWidgetHostViewAndroid::GetNativeImeAdapter() {
673 return reinterpret_cast<intptr_t>(&ime_adapter_android_);
676 void RenderWidgetHostViewAndroid::OnTextInputStateChanged(
677 const ViewHostMsg_TextInputState_Params& params) {
678 // If the change is not originated from IME (e.g. Javascript, autofill),
679 // send back the renderer an acknowledgement, regardless of how we exit from
680 // this method.
681 base::ScopedClosureRunner ack_caller;
682 if (params.is_non_ime_change)
683 ack_caller.Reset(base::Bind(&SendImeEventAck, host_));
685 if (!IsShowing())
686 return;
688 content_view_core_->UpdateImeAdapter(
689 GetNativeImeAdapter(),
690 static_cast<int>(params.type), params.flags,
691 params.value, params.selection_start, params.selection_end,
692 params.composition_start, params.composition_end,
693 params.show_ime_if_needed, params.is_non_ime_change);
696 void RenderWidgetHostViewAndroid::OnDidChangeBodyBackgroundColor(
697 SkColor color) {
698 if (cached_background_color_ == color)
699 return;
701 cached_background_color_ = color;
702 if (content_view_core_)
703 content_view_core_->OnBackgroundColorChanged(color);
706 void RenderWidgetHostViewAndroid::OnSetNeedsBeginFrames(bool enabled) {
707 TRACE_EVENT1("cc", "RenderWidgetHostViewAndroid::OnSetNeedsBeginFrames",
708 "enabled", enabled);
709 if (enabled)
710 RequestVSyncUpdate(PERSISTENT_BEGIN_FRAME);
711 else
712 outstanding_vsync_requests_ &= ~PERSISTENT_BEGIN_FRAME;
715 void RenderWidgetHostViewAndroid::OnStartContentIntent(
716 const GURL& content_url) {
717 if (content_view_core_)
718 content_view_core_->StartContentIntent(content_url);
721 void RenderWidgetHostViewAndroid::OnSmartClipDataExtracted(
722 const base::string16& text,
723 const base::string16& html,
724 const gfx::Rect rect) {
725 if (content_view_core_)
726 content_view_core_->OnSmartClipDataExtracted(text, html, rect);
729 bool RenderWidgetHostViewAndroid::OnTouchEvent(
730 const ui::MotionEvent& event) {
731 if (!host_)
732 return false;
734 // If a browser-based widget consumes the touch event, it's critical that
735 // touch event interception be disabled. This avoids issues with
736 // double-handling for embedder-detected gestures like side swipe.
737 if (selection_controller_ &&
738 selection_controller_->WillHandleTouchEvent(event)) {
739 RequestDisallowInterceptTouchEvent();
740 return true;
743 if (stylus_text_selector_.OnTouchEvent(event)) {
744 RequestDisallowInterceptTouchEvent();
745 return true;
748 ui::FilteredGestureProvider::TouchHandlingResult result =
749 gesture_provider_.OnTouchEvent(event);
750 if (!result.succeeded)
751 return false;
753 blink::WebTouchEvent web_event =
754 ui::CreateWebTouchEventFromMotionEvent(event, result.did_generate_scroll);
755 host_->ForwardTouchEventWithLatencyInfo(web_event, ui::LatencyInfo());
757 // Send a proactive BeginFrame for this vsync to reduce scroll latency for
758 // scroll-inducing touch events. Note that Android's Choreographer ensures
759 // that BeginFrame requests made during ACTION_MOVE dispatch will be honored
760 // in the same vsync phase.
761 if (observing_root_window_&& result.did_generate_scroll)
762 RequestVSyncUpdate(BEGIN_FRAME);
764 return true;
767 bool RenderWidgetHostViewAndroid::OnTouchHandleEvent(
768 const ui::MotionEvent& event) {
769 return selection_controller_ &&
770 selection_controller_->WillHandleTouchEvent(event);
773 void RenderWidgetHostViewAndroid::ResetGestureDetection() {
774 const ui::MotionEvent* current_down_event =
775 gesture_provider_.GetCurrentDownEvent();
776 if (!current_down_event) {
777 // A hard reset ensures prevention of any timer-based events that might fire
778 // after a touch sequence has ended.
779 gesture_provider_.ResetDetection();
780 return;
783 scoped_ptr<ui::MotionEvent> cancel_event = current_down_event->Cancel();
784 if (gesture_provider_.OnTouchEvent(*cancel_event).succeeded) {
785 bool causes_scrolling = false;
786 host_->ForwardTouchEventWithLatencyInfo(
787 ui::CreateWebTouchEventFromMotionEvent(*cancel_event, causes_scrolling),
788 ui::LatencyInfo());
792 void RenderWidgetHostViewAndroid::OnDidNavigateMainFrameToNewPage() {
793 ResetGestureDetection();
796 void RenderWidgetHostViewAndroid::SetDoubleTapSupportEnabled(bool enabled) {
797 gesture_provider_.SetDoubleTapSupportForPlatformEnabled(enabled);
800 void RenderWidgetHostViewAndroid::SetMultiTouchZoomSupportEnabled(
801 bool enabled) {
802 gesture_provider_.SetMultiTouchZoomSupportEnabled(enabled);
805 void RenderWidgetHostViewAndroid::ImeCancelComposition() {
806 ime_adapter_android_.CancelComposition();
809 void RenderWidgetHostViewAndroid::ImeCompositionRangeChanged(
810 const gfx::Range& range,
811 const std::vector<gfx::Rect>& character_bounds) {
812 // TODO(yukawa): Implement this.
815 void RenderWidgetHostViewAndroid::FocusedNodeChanged(bool is_editable_node) {
816 ime_adapter_android_.FocusedNodeChanged(is_editable_node);
819 void RenderWidgetHostViewAndroid::RenderProcessGone(
820 base::TerminationStatus status, int error_code) {
821 Destroy();
824 void RenderWidgetHostViewAndroid::Destroy() {
825 RemoveLayers();
826 SetContentViewCore(NULL);
828 if (!surface_id_.is_null()) {
829 DCHECK(surface_factory_.get());
830 surface_factory_->Destroy(surface_id_);
831 surface_id_ = cc::SurfaceId();
833 surface_factory_.reset();
835 // The RenderWidgetHost's destruction led here, so don't call it.
836 host_ = NULL;
838 delete this;
841 void RenderWidgetHostViewAndroid::SetTooltipText(
842 const base::string16& tooltip_text) {
843 // Tooltips don't makes sense on Android.
846 void RenderWidgetHostViewAndroid::SelectionChanged(const base::string16& text,
847 size_t offset,
848 const gfx::Range& range) {
849 RenderWidgetHostViewBase::SelectionChanged(text, offset, range);
851 if (!content_view_core_)
852 return;
853 if (range.is_empty()) {
854 content_view_core_->OnSelectionChanged("");
855 return;
858 DCHECK(!text.empty());
859 size_t pos = range.GetMin() - offset;
860 size_t n = range.length();
862 DCHECK(pos + n <= text.length()) << "The text can not fully cover range.";
863 if (pos >= text.length()) {
864 NOTREACHED() << "The text can not cover range.";
865 return;
868 std::string utf8_selection = base::UTF16ToUTF8(text.substr(pos, n));
870 content_view_core_->OnSelectionChanged(utf8_selection);
873 void RenderWidgetHostViewAndroid::SelectionBoundsChanged(
874 const ViewHostMsg_SelectionBounds_Params& params) {
875 NOTREACHED() << "Selection bounds should be routed through the compositor.";
878 void RenderWidgetHostViewAndroid::SetBackgroundColor(SkColor color) {
879 RenderWidgetHostViewBase::SetBackgroundColor(color);
880 host_->SetBackgroundOpaque(GetBackgroundOpaque());
881 OnDidChangeBodyBackgroundColor(color);
884 void RenderWidgetHostViewAndroid::CopyFromCompositingSurface(
885 const gfx::Rect& src_subrect,
886 const gfx::Size& dst_size,
887 ReadbackRequestCallback& callback,
888 const SkColorType preferred_color_type) {
889 TRACE_EVENT0("cc", "RenderWidgetHostViewAndroid::CopyFromCompositingSurface");
890 if (!host_ || host_->is_hidden()) {
891 callback.Run(SkBitmap(), READBACK_SURFACE_UNAVAILABLE);
892 return;
894 base::TimeTicks start_time = base::TimeTicks::Now();
895 if (using_browser_compositor_ && !IsSurfaceAvailableForCopy()) {
896 callback.Run(SkBitmap(), READBACK_SURFACE_UNAVAILABLE);
897 return;
899 const gfx::Display& display =
900 gfx::Screen::GetNativeScreen()->GetPrimaryDisplay();
901 float device_scale_factor = display.device_scale_factor();
902 gfx::Size dst_size_in_pixel =
903 gfx::ConvertRectToPixel(device_scale_factor, gfx::Rect(dst_size)).size();
904 gfx::Rect src_subrect_in_pixel =
905 gfx::ConvertRectToPixel(device_scale_factor, src_subrect);
907 if (!using_browser_compositor_) {
908 SynchronousCopyContents(src_subrect_in_pixel, dst_size_in_pixel, callback,
909 preferred_color_type);
910 UMA_HISTOGRAM_TIMES("Compositing.CopyFromSurfaceTimeSynchronous",
911 base::TimeTicks::Now() - start_time);
912 return;
915 scoped_ptr<cc::CopyOutputRequest> request;
916 scoped_refptr<cc::Layer> readback_layer;
917 DCHECK(content_view_core_window_android_);
918 ui::WindowAndroidCompositor* compositor =
919 content_view_core_window_android_->GetCompositor();
920 DCHECK(compositor);
921 DCHECK(frame_provider_.get() || !surface_id_.is_null());
922 scoped_refptr<cc::Layer> layer = CreateDelegatedLayer();
923 DCHECK(layer);
924 layer->SetHideLayerAndSubtree(true);
925 compositor->AttachLayerForReadback(layer);
927 readback_layer = layer;
928 request = cc::CopyOutputRequest::CreateRequest(
929 base::Bind(&RenderWidgetHostViewAndroid::
930 PrepareTextureCopyOutputResultForDelegatedReadback,
931 dst_size_in_pixel, preferred_color_type, start_time,
932 readback_layer, callback));
933 if (!src_subrect_in_pixel.IsEmpty())
934 request->set_area(src_subrect_in_pixel);
935 readback_layer->RequestCopyOfOutput(request.Pass());
938 void RenderWidgetHostViewAndroid::CopyFromCompositingSurfaceToVideoFrame(
939 const gfx::Rect& src_subrect,
940 const scoped_refptr<media::VideoFrame>& target,
941 const base::Callback<void(bool)>& callback) {
942 NOTIMPLEMENTED();
943 callback.Run(false);
946 bool RenderWidgetHostViewAndroid::CanCopyToVideoFrame() const {
947 return false;
950 void RenderWidgetHostViewAndroid::ShowDisambiguationPopup(
951 const gfx::Rect& rect_pixels, const SkBitmap& zoomed_bitmap) {
952 if (!content_view_core_)
953 return;
955 content_view_core_->ShowDisambiguationPopup(rect_pixels, zoomed_bitmap);
958 scoped_ptr<SyntheticGestureTarget>
959 RenderWidgetHostViewAndroid::CreateSyntheticGestureTarget() {
960 return scoped_ptr<SyntheticGestureTarget>(new SyntheticGestureTargetAndroid(
961 host_, content_view_core_->CreateMotionEventSynthesizer()));
964 void RenderWidgetHostViewAndroid::SendDelegatedFrameAck(
965 uint32 output_surface_id) {
966 DCHECK(host_);
967 cc::CompositorFrameAck ack;
968 if (!surface_returned_resources_.empty())
969 ack.resources.swap(surface_returned_resources_);
970 if (resource_collection_.get())
971 resource_collection_->TakeUnusedResourcesForChildCompositor(&ack.resources);
972 host_->Send(new ViewMsg_SwapCompositorFrameAck(host_->GetRoutingID(),
973 output_surface_id, ack));
976 void RenderWidgetHostViewAndroid::SendReturnedDelegatedResources(
977 uint32 output_surface_id) {
978 DCHECK(host_);
979 cc::CompositorFrameAck ack;
980 if (!surface_returned_resources_.empty()) {
981 ack.resources.swap(surface_returned_resources_);
982 } else {
983 DCHECK(resource_collection_.get());
984 resource_collection_->TakeUnusedResourcesForChildCompositor(&ack.resources);
987 host_->Send(new ViewMsg_ReclaimCompositorResources(host_->GetRoutingID(),
988 output_surface_id, ack));
991 void RenderWidgetHostViewAndroid::UnusedResourcesAreAvailable() {
992 DCHECK(surface_id_.is_null());
993 if (ack_callbacks_.size())
994 return;
995 SendReturnedDelegatedResources(last_output_surface_id_);
998 void RenderWidgetHostViewAndroid::ReturnResources(
999 const cc::ReturnedResourceArray& resources) {
1000 if (resources.empty())
1001 return;
1002 std::copy(resources.begin(), resources.end(),
1003 std::back_inserter(surface_returned_resources_));
1004 if (!ack_callbacks_.size())
1005 SendReturnedDelegatedResources(last_output_surface_id_);
1008 void RenderWidgetHostViewAndroid::DestroyDelegatedContent() {
1009 RemoveLayers();
1010 frame_provider_ = NULL;
1011 if (!surface_id_.is_null()) {
1012 DCHECK(surface_factory_.get());
1013 surface_factory_->Destroy(surface_id_);
1014 surface_id_ = cc::SurfaceId();
1016 layer_ = NULL;
1019 void RenderWidgetHostViewAndroid::CheckOutputSurfaceChanged(
1020 uint32 output_surface_id) {
1021 if (output_surface_id == last_output_surface_id_)
1022 return;
1023 // Drop the cc::DelegatedFrameResourceCollection so that we will not return
1024 // any resources from the old output surface with the new output surface id.
1025 if (resource_collection_.get()) {
1026 resource_collection_->SetClient(NULL);
1027 if (resource_collection_->LoseAllResources())
1028 SendReturnedDelegatedResources(last_output_surface_id_);
1029 resource_collection_ = NULL;
1031 DestroyDelegatedContent();
1032 surface_factory_.reset();
1033 if (!surface_returned_resources_.empty())
1034 SendReturnedDelegatedResources(last_output_surface_id_);
1036 last_output_surface_id_ = output_surface_id;
1039 void RenderWidgetHostViewAndroid::SubmitFrame(
1040 scoped_ptr<cc::DelegatedFrameData> frame_data) {
1041 cc::SurfaceManager* manager = CompositorImpl::GetSurfaceManager();
1042 if (manager) {
1043 if (!surface_factory_) {
1044 surface_factory_ = make_scoped_ptr(new cc::SurfaceFactory(manager, this));
1046 if (surface_id_.is_null() ||
1047 texture_size_in_layer_ != current_surface_size_) {
1048 RemoveLayers();
1049 if (!surface_id_.is_null())
1050 surface_factory_->Destroy(surface_id_);
1051 surface_id_ = id_allocator_->GenerateId();
1052 surface_factory_->Create(surface_id_);
1053 layer_ = CreateDelegatedLayer();
1055 DCHECK(layer_);
1057 current_surface_size_ = texture_size_in_layer_;
1058 AttachLayers();
1060 scoped_ptr<cc::CompositorFrame> compositor_frame =
1061 make_scoped_ptr(new cc::CompositorFrame());
1062 compositor_frame->delegated_frame_data = frame_data.Pass();
1064 cc::SurfaceFactory::DrawCallback ack_callback =
1065 base::Bind(&RenderWidgetHostViewAndroid::RunAckCallbacks,
1066 weak_ptr_factory_.GetWeakPtr());
1067 surface_factory_->SubmitFrame(surface_id_, compositor_frame.Pass(),
1068 ack_callback);
1069 } else {
1070 if (!resource_collection_.get()) {
1071 resource_collection_ = new cc::DelegatedFrameResourceCollection;
1072 resource_collection_->SetClient(this);
1074 if (!frame_provider_.get() ||
1075 texture_size_in_layer_ != frame_provider_->frame_size()) {
1076 RemoveLayers();
1077 frame_provider_ = new cc::DelegatedFrameProvider(
1078 resource_collection_.get(), frame_data.Pass());
1079 layer_ = cc::DelegatedRendererLayer::Create(Compositor::LayerSettings(),
1080 frame_provider_);
1081 AttachLayers();
1082 } else {
1083 frame_provider_->SetFrameData(frame_data.Pass());
1088 void RenderWidgetHostViewAndroid::SwapDelegatedFrame(
1089 uint32 output_surface_id,
1090 scoped_ptr<cc::DelegatedFrameData> frame_data) {
1091 CheckOutputSurfaceChanged(output_surface_id);
1092 bool has_content = !texture_size_in_layer_.IsEmpty();
1094 // DelegatedRendererLayerImpl applies the inverse device_scale_factor of the
1095 // renderer frame, assuming that the browser compositor will scale
1096 // it back up to device scale. But on Android we put our browser layers in
1097 // physical pixels and set our browser CC device_scale_factor to 1, so this
1098 // suppresses the transform. This line may need to be removed when fixing
1099 // http://crbug.com/384134 or http://crbug.com/310763
1100 frame_data->device_scale_factor = 1.0f;
1102 if (!has_content) {
1103 DestroyDelegatedContent();
1104 } else {
1105 SubmitFrame(frame_data.Pass());
1108 if (layer_.get()) {
1109 layer_->SetIsDrawable(true);
1110 layer_->SetContentsOpaque(true);
1111 layer_->SetBounds(content_size_in_layer_);
1114 base::Closure ack_callback =
1115 base::Bind(&RenderWidgetHostViewAndroid::SendDelegatedFrameAck,
1116 weak_ptr_factory_.GetWeakPtr(),
1117 output_surface_id);
1119 ack_callbacks_.push(ack_callback);
1120 if (host_->is_hidden())
1121 RunAckCallbacks(cc::SurfaceDrawStatus::DRAW_SKIPPED);
1124 void RenderWidgetHostViewAndroid::ComputeContentsSize(
1125 const cc::CompositorFrameMetadata& frame_metadata) {
1126 // Calculate the content size. This should be 0 if the texture_size is 0.
1127 gfx::Vector2dF offset;
1128 if (texture_size_in_layer_.IsEmpty())
1129 content_size_in_layer_ = gfx::Size();
1130 content_size_in_layer_ = gfx::ToCeiledSize(gfx::ScaleSize(
1131 frame_metadata.scrollable_viewport_size,
1132 frame_metadata.device_scale_factor * frame_metadata.page_scale_factor));
1136 void RenderWidgetHostViewAndroid::InternalSwapCompositorFrame(
1137 uint32 output_surface_id,
1138 scoped_ptr<cc::CompositorFrame> frame) {
1139 last_scroll_offset_ = frame->metadata.root_scroll_offset;
1140 if (!frame->delegated_frame_data) {
1141 LOG(ERROR) << "Non-delegated renderer path no longer supported";
1142 return;
1145 if (locks_on_frame_count_ > 0) {
1146 DCHECK(HasValidFrame());
1147 RetainFrame(output_surface_id, frame.Pass());
1148 return;
1151 if (layer_.get() && layer_->layer_tree_host()) {
1152 for (size_t i = 0; i < frame->metadata.latency_info.size(); i++) {
1153 scoped_ptr<cc::SwapPromise> swap_promise(
1154 new cc::LatencyInfoSwapPromise(frame->metadata.latency_info[i]));
1155 layer_->layer_tree_host()->QueueSwapPromise(swap_promise.Pass());
1159 DCHECK(!frame->delegated_frame_data->render_pass_list.empty());
1161 cc::RenderPass* root_pass =
1162 frame->delegated_frame_data->render_pass_list.back();
1163 texture_size_in_layer_ = root_pass->output_rect.size();
1164 ComputeContentsSize(frame->metadata);
1166 SwapDelegatedFrame(output_surface_id, frame->delegated_frame_data.Pass());
1167 frame_evictor_->SwappedFrame(!host_->is_hidden());
1169 // As the metadata update may trigger view invalidation, always call it after
1170 // any potential compositor scheduling.
1171 OnFrameMetadataUpdated(frame->metadata);
1174 void RenderWidgetHostViewAndroid::OnSwapCompositorFrame(
1175 uint32 output_surface_id,
1176 scoped_ptr<cc::CompositorFrame> frame) {
1177 InternalSwapCompositorFrame(output_surface_id, frame.Pass());
1180 void RenderWidgetHostViewAndroid::RetainFrame(
1181 uint32 output_surface_id,
1182 scoped_ptr<cc::CompositorFrame> frame) {
1183 DCHECK(locks_on_frame_count_);
1185 // Store the incoming frame so that it can be swapped when all the locks have
1186 // been released. If there is already a stored frame, then replace and skip
1187 // the previous one but make sure we still eventually send the ACK. Holding
1188 // the ACK also blocks the renderer when its max_frames_pending is reached.
1189 if (last_frame_info_) {
1190 base::Closure ack_callback =
1191 base::Bind(&RenderWidgetHostViewAndroid::SendDelegatedFrameAck,
1192 weak_ptr_factory_.GetWeakPtr(),
1193 last_frame_info_->output_surface_id);
1195 ack_callbacks_.push(ack_callback);
1198 last_frame_info_.reset(new LastFrameInfo(output_surface_id, frame.Pass()));
1201 void RenderWidgetHostViewAndroid::SynchronousFrameMetadata(
1202 const cc::CompositorFrameMetadata& frame_metadata) {
1203 if (!content_view_core_)
1204 return;
1206 // This is a subset of OnSwapCompositorFrame() used in the synchronous
1207 // compositor flow.
1208 OnFrameMetadataUpdated(frame_metadata);
1209 ComputeContentsSize(frame_metadata);
1211 // DevTools ScreenCast support for Android WebView.
1212 WebContents* web_contents = content_view_core_->GetWebContents();
1213 if (DevToolsAgentHost::HasFor(web_contents)) {
1214 scoped_refptr<DevToolsAgentHost> dtah =
1215 DevToolsAgentHost::GetOrCreateFor(web_contents);
1216 // Unblock the compositor.
1217 BrowserThread::PostTask(
1218 BrowserThread::UI, FROM_HERE,
1219 base::Bind(
1220 &RenderFrameDevToolsAgentHost::SynchronousSwapCompositorFrame,
1221 static_cast<RenderFrameDevToolsAgentHost*>(dtah.get()),
1222 frame_metadata));
1226 void RenderWidgetHostViewAndroid::SetOverlayVideoMode(bool enabled) {
1227 if (layer_.get())
1228 layer_->SetContentsOpaque(!enabled);
1231 bool RenderWidgetHostViewAndroid::SupportsAnimation() const {
1232 // The synchronous (WebView) compositor does not have a proper browser
1233 // compositor with which to drive animations.
1234 return using_browser_compositor_;
1237 void RenderWidgetHostViewAndroid::SetNeedsAnimate() {
1238 DCHECK(content_view_core_window_android_);
1239 DCHECK(using_browser_compositor_);
1240 content_view_core_window_android_->SetNeedsAnimate();
1243 void RenderWidgetHostViewAndroid::MoveCaret(const gfx::PointF& position) {
1244 MoveCaret(gfx::Point(position.x(), position.y()));
1247 void RenderWidgetHostViewAndroid::MoveRangeSelectionExtent(
1248 const gfx::PointF& extent) {
1249 DCHECK(content_view_core_);
1250 content_view_core_->MoveRangeSelectionExtent(extent);
1253 void RenderWidgetHostViewAndroid::SelectBetweenCoordinates(
1254 const gfx::PointF& base,
1255 const gfx::PointF& extent) {
1256 DCHECK(content_view_core_);
1257 content_view_core_->SelectBetweenCoordinates(base, extent);
1260 void RenderWidgetHostViewAndroid::OnSelectionEvent(
1261 ui::SelectionEventType event) {
1262 DCHECK(content_view_core_);
1263 DCHECK(selection_controller_);
1264 // If a selection drag has started, it has taken over the active touch
1265 // sequence. Immediately cancel gesture detection and any downstream touch
1266 // listeners (e.g., web content) to communicate this transfer.
1267 if (event == ui::SELECTION_SHOWN)
1268 ResetGestureDetection();
1269 content_view_core_->OnSelectionEvent(
1270 event, selection_controller_->GetStartPosition(),
1271 GetSelectionRect(*selection_controller_));
1274 scoped_ptr<ui::TouchHandleDrawable>
1275 RenderWidgetHostViewAndroid::CreateDrawable() {
1276 DCHECK(content_view_core_);
1277 if (!using_browser_compositor_)
1278 return content_view_core_->CreatePopupTouchHandleDrawable();
1280 return scoped_ptr<ui::TouchHandleDrawable>(new CompositedTouchHandleDrawable(
1281 content_view_core_->GetLayer().get(),
1282 content_view_core_->GetDpiScale(),
1283 // Use the activity context (instead of the application context) to ensure
1284 // proper handle theming.
1285 content_view_core_->GetContext().obj()));
1288 void RenderWidgetHostViewAndroid::SynchronousCopyContents(
1289 const gfx::Rect& src_subrect_in_pixel,
1290 const gfx::Size& dst_size_in_pixel,
1291 ReadbackRequestCallback& callback,
1292 const SkColorType color_type) {
1293 gfx::Size input_size_in_pixel;
1294 if (src_subrect_in_pixel.IsEmpty())
1295 input_size_in_pixel = content_size_in_layer_;
1296 else
1297 input_size_in_pixel = src_subrect_in_pixel.size();
1299 gfx::Size output_size_in_pixel;
1300 if (dst_size_in_pixel.IsEmpty())
1301 output_size_in_pixel = input_size_in_pixel;
1302 else
1303 output_size_in_pixel = dst_size_in_pixel;
1304 int output_width = output_size_in_pixel.width();
1305 int output_height = output_size_in_pixel.height();
1307 SynchronousCompositor* compositor =
1308 SynchronousCompositorImpl::FromID(host_->GetProcess()->GetID(),
1309 host_->GetRoutingID());
1310 if (!compositor) {
1311 callback.Run(SkBitmap(), READBACK_FAILED);
1312 return;
1315 SkBitmap bitmap;
1316 bitmap.allocPixels(SkImageInfo::Make(output_width,
1317 output_height,
1318 color_type,
1319 kPremul_SkAlphaType));
1320 SkCanvas canvas(bitmap);
1321 canvas.scale(
1322 (float)output_width / (float)input_size_in_pixel.width(),
1323 (float)output_height / (float)input_size_in_pixel.height());
1324 compositor->DemandDrawSw(&canvas);
1325 callback.Run(bitmap, READBACK_SUCCESS);
1328 void RenderWidgetHostViewAndroid::OnFrameMetadataUpdated(
1329 const cc::CompositorFrameMetadata& frame_metadata) {
1330 bool is_mobile_optimized = IsMobileOptimizedFrame(frame_metadata);
1331 gesture_provider_.SetDoubleTapSupportForPageEnabled(!is_mobile_optimized);
1333 if (!content_view_core_)
1334 return;
1336 if (overscroll_controller_)
1337 overscroll_controller_->OnFrameMetadataUpdated(frame_metadata);
1339 if (selection_controller_) {
1340 selection_controller_->OnSelectionEditable(
1341 frame_metadata.selection.is_editable);
1342 selection_controller_->OnSelectionEmpty(
1343 frame_metadata.selection.is_empty_text_form_control);
1344 selection_controller_->OnSelectionBoundsChanged(
1345 ConvertSelectionBound(frame_metadata.selection.start),
1346 ConvertSelectionBound(frame_metadata.selection.end));
1349 // All offsets and sizes are in CSS pixels.
1350 content_view_core_->UpdateFrameInfo(
1351 frame_metadata.root_scroll_offset,
1352 frame_metadata.page_scale_factor,
1353 gfx::Vector2dF(frame_metadata.min_page_scale_factor,
1354 frame_metadata.max_page_scale_factor),
1355 frame_metadata.root_layer_size,
1356 frame_metadata.scrollable_viewport_size,
1357 frame_metadata.location_bar_offset,
1358 frame_metadata.location_bar_content_translation,
1359 is_mobile_optimized);
1360 #if defined(VIDEO_HOLE)
1361 if (host_ && host_->IsRenderView()) {
1362 RenderViewHostImpl* rvhi = static_cast<RenderViewHostImpl*>(
1363 RenderViewHost::From(host_));
1364 WebContentsImpl* web_contents_impl =
1365 static_cast<WebContentsImpl*>(WebContents::FromRenderViewHost(rvhi));
1366 if (web_contents_impl)
1367 web_contents_impl->media_web_contents_observer()->OnFrameInfoUpdated();
1369 #endif // defined(VIDEO_HOLE)
1372 void RenderWidgetHostViewAndroid::AcceleratedSurfaceInitialized(int route_id) {
1373 // TODO: remove need for the surface id here
1374 accelerated_surface_route_id_ = route_id;
1377 void RenderWidgetHostViewAndroid::ShowInternal() {
1378 DCHECK(is_showing_);
1379 if (!host_ || !host_->is_hidden())
1380 return;
1382 if (layer_.get())
1383 layer_->SetHideLayerAndSubtree(false);
1385 frame_evictor_->SetVisible(true);
1387 if (overscroll_controller_)
1388 overscroll_controller_->Enable();
1390 host_->WasShown(ui::LatencyInfo());
1392 if (content_view_core_) {
1393 StartObservingRootWindow();
1394 RequestVSyncUpdate(BEGIN_FRAME);
1398 void RenderWidgetHostViewAndroid::HideInternal(
1399 bool hide_frontbuffer,
1400 bool stop_observing_root_window) {
1401 if (hide_frontbuffer) {
1402 if (layer_.get() && locks_on_frame_count_ == 0)
1403 layer_->SetHideLayerAndSubtree(true);
1405 frame_evictor_->SetVisible(false);
1408 if (stop_observing_root_window)
1409 StopObservingRootWindow();
1411 if (!host_ || host_->is_hidden())
1412 return;
1414 if (overscroll_controller_)
1415 overscroll_controller_->Disable();
1417 RunAckCallbacks(cc::SurfaceDrawStatus::DRAW_SKIPPED);
1419 // Inform the renderer that we are being hidden so it can reduce its resource
1420 // utilization.
1421 host_->WasHidden();
1424 void RenderWidgetHostViewAndroid::AttachLayers() {
1425 if (!content_view_core_)
1426 return;
1427 if (!layer_.get())
1428 return;
1430 content_view_core_->AttachLayer(layer_);
1431 if (overscroll_controller_)
1432 overscroll_controller_->Enable();
1433 layer_->SetHideLayerAndSubtree(!is_showing_);
1436 void RenderWidgetHostViewAndroid::RemoveLayers() {
1437 if (!content_view_core_)
1438 return;
1440 if (!layer_.get())
1441 return;
1443 content_view_core_->RemoveLayer(layer_);
1444 if (overscroll_controller_)
1445 overscroll_controller_->Disable();
1448 void RenderWidgetHostViewAndroid::RequestVSyncUpdate(uint32 requests) {
1449 bool should_request_vsync = !outstanding_vsync_requests_ && requests;
1450 outstanding_vsync_requests_ |= requests;
1452 // If the host has been hidden, defer vsync requests until it is shown
1453 // again via |Show()|.
1454 if (!host_ || host_->is_hidden())
1455 return;
1457 // Note that if we're not currently observing the root window, outstanding
1458 // vsync requests will be pushed if/when we resume observing in
1459 // |StartObservingRootWindow()|.
1460 if (observing_root_window_ && should_request_vsync)
1461 content_view_core_window_android_->RequestVSyncUpdate();
1464 void RenderWidgetHostViewAndroid::StartObservingRootWindow() {
1465 DCHECK(content_view_core_window_android_);
1466 DCHECK(is_showing_);
1467 if (observing_root_window_)
1468 return;
1470 observing_root_window_ = true;
1471 content_view_core_window_android_->AddObserver(this);
1473 // Clear existing vsync requests to allow a request to the new window.
1474 uint32 outstanding_vsync_requests = outstanding_vsync_requests_;
1475 outstanding_vsync_requests_ = 0;
1476 RequestVSyncUpdate(outstanding_vsync_requests);
1479 void RenderWidgetHostViewAndroid::StopObservingRootWindow() {
1480 if (!content_view_core_window_android_) {
1481 DCHECK(!observing_root_window_);
1482 return;
1485 if (!observing_root_window_)
1486 return;
1488 observing_root_window_ = false;
1489 content_view_core_window_android_->RemoveObserver(this);
1492 void RenderWidgetHostViewAndroid::SendBeginFrame(base::TimeTicks frame_time,
1493 base::TimeDelta vsync_period) {
1494 TRACE_EVENT1("cc", "RenderWidgetHostViewAndroid::SendBeginFrame",
1495 "frame_time_us", frame_time.ToInternalValue());
1497 if (using_browser_compositor_) {
1498 base::TimeTicks display_time = frame_time + vsync_period;
1500 base::TimeTicks deadline =
1501 display_time - host_->GetEstimatedBrowserCompositeTime();
1503 host_->Send(new ViewMsg_BeginFrame(
1504 host_->GetRoutingID(),
1505 cc::BeginFrameArgs::Create(BEGINFRAME_FROM_HERE, frame_time, deadline,
1506 vsync_period, cc::BeginFrameArgs::NORMAL)));
1507 } else {
1508 SynchronousCompositorImpl* compositor = SynchronousCompositorImpl::FromID(
1509 host_->GetProcess()->GetID(), host_->GetRoutingID());
1510 if (compositor) {
1511 // The synchronous compositor synchronously does it's work in this call.
1512 // It does not use a deadline.
1513 compositor->BeginFrame(cc::BeginFrameArgs::Create(
1514 BEGINFRAME_FROM_HERE, frame_time, base::TimeTicks(), vsync_period,
1515 cc::BeginFrameArgs::NORMAL));
1520 bool RenderWidgetHostViewAndroid::Animate(base::TimeTicks frame_time) {
1521 bool needs_animate = false;
1522 if (overscroll_controller_) {
1523 needs_animate |= overscroll_controller_->Animate(
1524 frame_time, content_view_core_->GetLayer().get());
1526 if (selection_controller_)
1527 needs_animate |= selection_controller_->Animate(frame_time);
1528 return needs_animate;
1531 void RenderWidgetHostViewAndroid::RequestDisallowInterceptTouchEvent() {
1532 if (content_view_core_)
1533 content_view_core_->RequestDisallowInterceptTouchEvent();
1536 void RenderWidgetHostViewAndroid::EvictDelegatedFrame() {
1537 if (layer_.get())
1538 DestroyDelegatedContent();
1539 frame_evictor_->DiscardedFrame();
1542 bool RenderWidgetHostViewAndroid::HasAcceleratedSurface(
1543 const gfx::Size& desired_size) {
1544 NOTREACHED();
1545 return false;
1548 void RenderWidgetHostViewAndroid::GetScreenInfo(blink::WebScreenInfo* result) {
1549 // ScreenInfo isn't tied to the widget on Android. Always return the default.
1550 RenderWidgetHostViewBase::GetDefaultScreenInfo(result);
1553 // TODO(jrg): Find out the implications and answer correctly here,
1554 // as we are returning the WebView and not root window bounds.
1555 gfx::Rect RenderWidgetHostViewAndroid::GetBoundsInRootWindow() {
1556 return GetViewBounds();
1559 gfx::GLSurfaceHandle RenderWidgetHostViewAndroid::GetCompositingSurface() {
1560 gfx::GLSurfaceHandle handle =
1561 gfx::GLSurfaceHandle(gfx::kNullPluginWindow, gfx::NULL_TRANSPORT);
1562 if (using_browser_compositor_) {
1563 handle.parent_client_id =
1564 BrowserGpuChannelHostFactory::instance()->GetGpuChannelId();
1566 return handle;
1569 void RenderWidgetHostViewAndroid::ProcessAckedTouchEvent(
1570 const TouchEventWithLatencyInfo& touch, InputEventAckState ack_result) {
1571 const bool event_consumed = ack_result == INPUT_EVENT_ACK_STATE_CONSUMED;
1572 gesture_provider_.OnTouchEventAck(touch.event.uniqueTouchEventId,
1573 event_consumed);
1576 void RenderWidgetHostViewAndroid::GestureEventAck(
1577 const blink::WebGestureEvent& event,
1578 InputEventAckState ack_result) {
1579 if (overscroll_controller_)
1580 overscroll_controller_->OnGestureEventAck(event, ack_result);
1582 if (content_view_core_)
1583 content_view_core_->OnGestureEventAck(event, ack_result);
1586 InputEventAckState RenderWidgetHostViewAndroid::FilterInputEvent(
1587 const blink::WebInputEvent& input_event) {
1588 if (selection_controller_ &&
1589 blink::WebInputEvent::isGestureEventType(input_event.type)) {
1590 const blink::WebGestureEvent& gesture_event =
1591 static_cast<const blink::WebGestureEvent&>(input_event);
1592 switch (gesture_event.type) {
1593 case blink::WebInputEvent::GestureLongPress:
1594 if (selection_controller_->WillHandleLongPressEvent(
1595 base::TimeTicks() +
1596 base::TimeDelta::FromSecondsD(input_event.timeStampSeconds),
1597 gfx::PointF(gesture_event.x, gesture_event.y))) {
1598 return INPUT_EVENT_ACK_STATE_CONSUMED;
1600 break;
1602 case blink::WebInputEvent::GestureTap:
1603 if (selection_controller_->WillHandleTapEvent(
1604 gfx::PointF(gesture_event.x, gesture_event.y))) {
1605 return INPUT_EVENT_ACK_STATE_CONSUMED;
1607 break;
1609 default:
1610 break;
1614 if (overscroll_controller_ &&
1615 blink::WebInputEvent::isGestureEventType(input_event.type) &&
1616 overscroll_controller_->WillHandleGestureEvent(
1617 static_cast<const blink::WebGestureEvent&>(input_event))) {
1618 return INPUT_EVENT_ACK_STATE_CONSUMED;
1621 if (content_view_core_ && content_view_core_->FilterInputEvent(input_event))
1622 return INPUT_EVENT_ACK_STATE_CONSUMED;
1624 if (!host_)
1625 return INPUT_EVENT_ACK_STATE_NOT_CONSUMED;
1627 if (input_event.type == blink::WebInputEvent::GestureTapDown ||
1628 input_event.type == blink::WebInputEvent::TouchStart) {
1629 GpuDataManagerImpl* gpu_data = GpuDataManagerImpl::GetInstance();
1630 GpuProcessHostUIShim* shim = GpuProcessHostUIShim::GetOneInstance();
1631 if (shim && gpu_data && accelerated_surface_route_id_ &&
1632 gpu_data->IsDriverBugWorkaroundActive(gpu::WAKE_UP_GPU_BEFORE_DRAWING))
1633 shim->Send(
1634 new AcceleratedSurfaceMsg_WakeUpGpu(accelerated_surface_route_id_));
1637 SynchronousCompositorImpl* compositor =
1638 SynchronousCompositorImpl::FromID(host_->GetProcess()->GetID(),
1639 host_->GetRoutingID());
1640 if (compositor)
1641 return compositor->HandleInputEvent(input_event);
1642 return INPUT_EVENT_ACK_STATE_NOT_CONSUMED;
1645 void RenderWidgetHostViewAndroid::OnSetNeedsFlushInput() {
1646 TRACE_EVENT0("input", "RenderWidgetHostViewAndroid::OnSetNeedsFlushInput");
1647 RequestVSyncUpdate(FLUSH_INPUT);
1650 BrowserAccessibilityManager*
1651 RenderWidgetHostViewAndroid::CreateBrowserAccessibilityManager(
1652 BrowserAccessibilityDelegate* delegate) {
1653 // TODO(dmazzoni): Currently there can only be one
1654 // BrowserAccessibilityManager per ContentViewCore, so return NULL
1655 // if there's already a BrowserAccessibilityManager for the main
1656 // frame. Eventually, in order to support cross-process iframes on
1657 // Android we'll need to add support for a
1658 // BrowserAccessibilityManager for a child frame.
1659 // http://crbug.com/423846
1660 if (!host_ || host_->GetRootBrowserAccessibilityManager())
1661 return NULL;
1663 base::android::ScopedJavaLocalRef<jobject> obj;
1664 if (content_view_core_)
1665 obj = content_view_core_->GetJavaObject();
1666 return new BrowserAccessibilityManagerAndroid(
1667 obj,
1668 BrowserAccessibilityManagerAndroid::GetEmptyDocument(),
1669 delegate);
1672 bool RenderWidgetHostViewAndroid::LockMouse() {
1673 NOTIMPLEMENTED();
1674 return false;
1677 void RenderWidgetHostViewAndroid::UnlockMouse() {
1678 NOTIMPLEMENTED();
1681 // Methods called from the host to the render
1683 void RenderWidgetHostViewAndroid::SendKeyEvent(
1684 const NativeWebKeyboardEvent& event) {
1685 if (host_)
1686 host_->ForwardKeyboardEvent(event);
1689 void RenderWidgetHostViewAndroid::SendMouseEvent(
1690 const blink::WebMouseEvent& event) {
1691 if (host_)
1692 host_->ForwardMouseEvent(event);
1695 void RenderWidgetHostViewAndroid::SendMouseWheelEvent(
1696 const blink::WebMouseWheelEvent& event) {
1697 if (host_)
1698 host_->ForwardWheelEvent(event);
1701 void RenderWidgetHostViewAndroid::SendGestureEvent(
1702 const blink::WebGestureEvent& event) {
1703 // Sending a gesture that may trigger overscroll should resume the effect.
1704 if (overscroll_controller_)
1705 overscroll_controller_->Enable();
1707 if (host_)
1708 host_->ForwardGestureEventWithLatencyInfo(event, ui::LatencyInfo());
1711 void RenderWidgetHostViewAndroid::MoveCaret(const gfx::Point& point) {
1712 if (host_)
1713 host_->MoveCaret(point);
1716 void RenderWidgetHostViewAndroid::DismissTextHandles() {
1717 if (selection_controller_)
1718 selection_controller_->HideAndDisallowShowingAutomatically();
1721 void RenderWidgetHostViewAndroid::SetTextHandlesTemporarilyHidden(bool hidden) {
1722 if (selection_controller_)
1723 selection_controller_->SetTemporarilyHidden(hidden);
1726 void RenderWidgetHostViewAndroid::OnShowingPastePopup(
1727 const gfx::PointF& point) {
1728 if (!selection_controller_)
1729 return;
1731 // As the paste popup may be triggered *before* the bounds and editability
1732 // of the region have been updated, explicitly set the properties now.
1733 // TODO(jdduke): Remove this workaround when auxiliary paste popup
1734 // notifications are no longer required, crbug.com/398170.
1735 ui::SelectionBound insertion_bound;
1736 insertion_bound.set_type(ui::SelectionBound::CENTER);
1737 insertion_bound.set_visible(true);
1738 insertion_bound.SetEdge(point, point);
1739 selection_controller_->HideAndDisallowShowingAutomatically();
1740 selection_controller_->OnSelectionEditable(true);
1741 selection_controller_->OnSelectionEmpty(true);
1742 selection_controller_->OnSelectionBoundsChanged(insertion_bound,
1743 insertion_bound);
1744 selection_controller_->AllowShowingFromCurrentSelection();
1747 SkColor RenderWidgetHostViewAndroid::GetCachedBackgroundColor() const {
1748 return cached_background_color_;
1751 void RenderWidgetHostViewAndroid::DidOverscroll(
1752 const DidOverscrollParams& params) {
1753 if (!content_view_core_ || !layer_.get() || !is_showing_)
1754 return;
1756 if (overscroll_controller_)
1757 overscroll_controller_->OnOverscrolled(params);
1760 void RenderWidgetHostViewAndroid::DidStopFlinging() {
1761 if (content_view_core_)
1762 content_view_core_->DidStopFlinging();
1765 uint32_t RenderWidgetHostViewAndroid::GetSurfaceIdNamespace() {
1766 if (id_allocator_)
1767 return id_allocator_->id_namespace();
1768 return 0;
1771 void RenderWidgetHostViewAndroid::SetContentViewCore(
1772 ContentViewCoreImpl* content_view_core) {
1773 RemoveLayers();
1774 StopObservingRootWindow();
1776 bool resize = false;
1777 if (content_view_core != content_view_core_) {
1778 overscroll_controller_.reset();
1779 selection_controller_.reset();
1780 ReleaseLocksOnSurface();
1781 resize = true;
1784 content_view_core_ = content_view_core;
1785 content_view_core_window_android_ =
1786 content_view_core_ ? content_view_core_->GetWindowAndroid() : nullptr;
1787 DCHECK_EQ(!!content_view_core_, !!content_view_core_window_android_);
1789 BrowserAccessibilityManager* manager = NULL;
1790 if (host_)
1791 manager = host_->GetRootBrowserAccessibilityManager();
1792 if (manager) {
1793 base::android::ScopedJavaLocalRef<jobject> obj;
1794 if (content_view_core_)
1795 obj = content_view_core_->GetJavaObject();
1796 manager->ToBrowserAccessibilityManagerAndroid()->SetContentViewCore(obj);
1799 AttachLayers();
1801 if (!content_view_core_)
1802 return;
1804 if (is_showing_)
1805 StartObservingRootWindow();
1807 if (resize)
1808 WasResized();
1810 if (!selection_controller_)
1811 selection_controller_ = CreateSelectionController(this, content_view_core_);
1813 if (!overscroll_controller_ &&
1814 content_view_core_window_android_->GetCompositor()) {
1815 overscroll_controller_ = CreateOverscrollController(content_view_core_);
1819 void RenderWidgetHostViewAndroid::RunAckCallbacks(
1820 cc::SurfaceDrawStatus status) {
1821 while (!ack_callbacks_.empty()) {
1822 ack_callbacks_.front().Run();
1823 ack_callbacks_.pop();
1827 void RenderWidgetHostViewAndroid::OnGestureEvent(
1828 const ui::GestureEventData& gesture) {
1829 blink::WebGestureEvent web_gesture =
1830 ui::CreateWebGestureEventFromGestureEventData(gesture);
1831 // TODO(jdduke): Remove this workaround after Android fixes UiAutomator to
1832 // stop providing shift meta values to synthetic MotionEvents. This prevents
1833 // unintended shift+click interpretation of all accessibility clicks.
1834 // See crbug.com/443247.
1835 if (web_gesture.type == blink::WebInputEvent::GestureTap &&
1836 web_gesture.modifiers == blink::WebInputEvent::ShiftKey) {
1837 web_gesture.modifiers = 0;
1839 SendGestureEvent(web_gesture);
1842 void RenderWidgetHostViewAndroid::OnCompositingDidCommit() {
1843 RunAckCallbacks(cc::SurfaceDrawStatus::DRAWN);
1846 void RenderWidgetHostViewAndroid::OnRootWindowVisibilityChanged(bool visible) {
1847 DCHECK(is_showing_);
1848 if (visible) {
1849 ShowInternal();
1850 } else {
1851 bool hide_frontbuffer = true;
1852 bool stop_observing_root_window = false;
1853 HideInternal(hide_frontbuffer, stop_observing_root_window);
1857 void RenderWidgetHostViewAndroid::OnAttachCompositor() {
1858 DCHECK(content_view_core_);
1859 if (!overscroll_controller_)
1860 overscroll_controller_ = CreateOverscrollController(content_view_core_);
1863 void RenderWidgetHostViewAndroid::OnDetachCompositor() {
1864 DCHECK(content_view_core_);
1865 DCHECK(using_browser_compositor_);
1866 RunAckCallbacks(cc::SurfaceDrawStatus::DRAW_SKIPPED);
1867 overscroll_controller_.reset();
1870 void RenderWidgetHostViewAndroid::OnVSync(base::TimeTicks frame_time,
1871 base::TimeDelta vsync_period) {
1872 TRACE_EVENT0("cc,benchmark", "RenderWidgetHostViewAndroid::OnVSync");
1873 if (!host_ || host_->is_hidden())
1874 return;
1876 if (outstanding_vsync_requests_ & FLUSH_INPUT) {
1877 outstanding_vsync_requests_ &= ~FLUSH_INPUT;
1878 host_->FlushInput();
1881 if (outstanding_vsync_requests_ & BEGIN_FRAME ||
1882 outstanding_vsync_requests_ & PERSISTENT_BEGIN_FRAME) {
1883 outstanding_vsync_requests_ &= ~BEGIN_FRAME;
1884 SendBeginFrame(frame_time, vsync_period);
1887 // This allows for SendBeginFrame and FlushInput to modify
1888 // outstanding_vsync_requests.
1889 uint32 outstanding_vsync_requests = outstanding_vsync_requests_;
1890 outstanding_vsync_requests_ = 0;
1891 RequestVSyncUpdate(outstanding_vsync_requests);
1894 void RenderWidgetHostViewAndroid::OnAnimate(base::TimeTicks begin_frame_time) {
1895 if (Animate(begin_frame_time))
1896 SetNeedsAnimate();
1899 void RenderWidgetHostViewAndroid::OnActivityPaused() {
1900 TRACE_EVENT0("browser", "RenderWidgetHostViewAndroid::OnActivityPaused");
1901 DCHECK(is_showing_);
1902 bool hide_frontbuffer = false;
1903 bool stop_observing_root_window = false;
1904 HideInternal(hide_frontbuffer, stop_observing_root_window);
1907 void RenderWidgetHostViewAndroid::OnActivityResumed() {
1908 TRACE_EVENT0("browser", "RenderWidgetHostViewAndroid::OnActivityResumed");
1909 DCHECK(is_showing_);
1910 ShowInternal();
1913 void RenderWidgetHostViewAndroid::OnLostResources() {
1914 ReleaseLocksOnSurface();
1915 if (layer_.get())
1916 DestroyDelegatedContent();
1917 DCHECK(ack_callbacks_.empty());
1920 // static
1921 void RenderWidgetHostViewAndroid::
1922 PrepareTextureCopyOutputResultForDelegatedReadback(
1923 const gfx::Size& dst_size_in_pixel,
1924 SkColorType color_type,
1925 const base::TimeTicks& start_time,
1926 scoped_refptr<cc::Layer> readback_layer,
1927 ReadbackRequestCallback& callback,
1928 scoped_ptr<cc::CopyOutputResult> result) {
1929 readback_layer->RemoveFromParent();
1930 PrepareTextureCopyOutputResult(
1931 dst_size_in_pixel, color_type, start_time, callback, result.Pass());
1934 // static
1935 void RenderWidgetHostViewAndroid::PrepareTextureCopyOutputResult(
1936 const gfx::Size& dst_size_in_pixel,
1937 SkColorType color_type,
1938 const base::TimeTicks& start_time,
1939 ReadbackRequestCallback& callback,
1940 scoped_ptr<cc::CopyOutputResult> result) {
1941 base::ScopedClosureRunner scoped_callback_runner(
1942 base::Bind(callback, SkBitmap(), READBACK_FAILED));
1943 TRACE_EVENT0("cc",
1944 "RenderWidgetHostViewAndroid::PrepareTextureCopyOutputResult");
1946 if (!result->HasTexture() || result->IsEmpty() || result->size().IsEmpty())
1947 return;
1949 gfx::Size output_size_in_pixel;
1950 if (dst_size_in_pixel.IsEmpty())
1951 output_size_in_pixel = result->size();
1952 else
1953 output_size_in_pixel = dst_size_in_pixel;
1955 GLHelper* gl_helper = GetPostReadbackGLHelper();
1956 if (!gl_helper)
1957 return;
1958 if (!gl_helper->IsReadbackConfigSupported(color_type))
1959 color_type = kRGBA_8888_SkColorType;
1960 scoped_ptr<SkBitmap> bitmap(new SkBitmap);
1961 if (!bitmap->tryAllocPixels(SkImageInfo::Make(output_size_in_pixel.width(),
1962 output_size_in_pixel.height(),
1963 color_type,
1964 kOpaque_SkAlphaType))) {
1965 scoped_callback_runner.Reset(
1966 base::Bind(callback, SkBitmap(), READBACK_BITMAP_ALLOCATION_FAILURE));
1967 return;
1971 scoped_ptr<SkAutoLockPixels> bitmap_pixels_lock(
1972 new SkAutoLockPixels(*bitmap));
1973 uint8* pixels = static_cast<uint8*>(bitmap->getPixels());
1975 cc::TextureMailbox texture_mailbox;
1976 scoped_ptr<cc::SingleReleaseCallback> release_callback;
1977 result->TakeTexture(&texture_mailbox, &release_callback);
1978 DCHECK(texture_mailbox.IsTexture());
1979 if (!texture_mailbox.IsTexture())
1980 return;
1982 ignore_result(scoped_callback_runner.Release());
1984 gl_helper->CropScaleReadbackAndCleanMailbox(
1985 texture_mailbox.mailbox(),
1986 texture_mailbox.sync_point(),
1987 result->size(),
1988 gfx::Rect(result->size()),
1989 output_size_in_pixel,
1990 pixels,
1991 color_type,
1992 base::Bind(&CopyFromCompositingSurfaceFinished,
1993 callback,
1994 base::Passed(&release_callback),
1995 base::Passed(&bitmap),
1996 start_time,
1997 base::Passed(&bitmap_pixels_lock)),
1998 GLHelper::SCALER_QUALITY_GOOD);
2001 void RenderWidgetHostViewAndroid::OnStylusSelectBegin(float x0,
2002 float y0,
2003 float x1,
2004 float y1) {
2005 SelectBetweenCoordinates(gfx::PointF(x0, y0), gfx::PointF(x1, y1));
2008 void RenderWidgetHostViewAndroid::OnStylusSelectUpdate(float x, float y) {
2009 MoveRangeSelectionExtent(gfx::PointF(x, y));
2012 void RenderWidgetHostViewAndroid::OnStylusSelectEnd() {
2013 if (selection_controller_)
2014 selection_controller_->AllowShowingFromCurrentSelection();
2017 void RenderWidgetHostViewAndroid::OnStylusSelectTap(base::TimeTicks time,
2018 float x,
2019 float y) {
2020 // Treat the stylus tap as a long press, activating either a word selection or
2021 // context menu depending on the targetted content.
2022 blink::WebGestureEvent long_press = WebGestureEventBuilder::Build(
2023 blink::WebInputEvent::GestureLongPress,
2024 (time - base::TimeTicks()).InSecondsF(), x, y);
2025 SendGestureEvent(long_press);
2028 // static
2029 void RenderWidgetHostViewBase::GetDefaultScreenInfo(
2030 blink::WebScreenInfo* results) {
2031 const gfx::Display& display =
2032 gfx::Screen::GetNativeScreen()->GetPrimaryDisplay();
2033 results->rect = display.bounds();
2034 // TODO(husky): Remove any system controls from availableRect.
2035 results->availableRect = display.work_area();
2036 results->deviceScaleFactor = display.device_scale_factor();
2037 results->orientationAngle = display.RotationAsDegree();
2038 results->orientationType =
2039 RenderWidgetHostViewBase::GetOrientationTypeForMobile(display);
2040 gfx::DeviceDisplayInfo info;
2041 results->depth = info.GetBitsPerPixel();
2042 results->depthPerComponent = info.GetBitsPerComponent();
2043 results->isMonochrome = (results->depthPerComponent == 0);
2046 } // namespace content