Add ICU message format support
[chromium-blink-merge.git] / content / browser / renderer_host / render_widget_host_view_android.cc
blob12d71da78b6af6ee7170d3ad7424347b4a4322d2
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::GetTouchSlopInDips();
276 config.show_on_tap_for_empty_editable = false;
277 config.enable_longpress_drag_selection =
278 base::CommandLine::ForCurrentProcess()->HasSwitch(
279 switches::kEnableLongpressDragSelection);
280 return make_scoped_ptr(new ui::TouchSelectionController(client, config));
283 scoped_ptr<OverscrollControllerAndroid> CreateOverscrollController(
284 ContentViewCoreImpl* content_view_core) {
285 return make_scoped_ptr(new OverscrollControllerAndroid(content_view_core));
288 ui::GestureProvider::Config CreateGestureProviderConfig() {
289 ui::GestureProvider::Config config = ui::GetGestureProviderConfig(
290 ui::GestureProviderConfigType::CURRENT_PLATFORM);
291 config.disable_click_delay =
292 base::CommandLine::ForCurrentProcess()->HasSwitch(
293 switches::kDisableClickDelay);
294 return config;
297 gfx::RectF GetSelectionRect(const ui::TouchSelectionController& controller) {
298 gfx::RectF rect = controller.GetRectBetweenBounds();
299 if (rect.IsEmpty())
300 return rect;
302 rect.Union(controller.GetStartHandleRect());
303 rect.Union(controller.GetEndHandleRect());
304 return rect;
307 } // anonymous namespace
309 RenderWidgetHostViewAndroid::LastFrameInfo::LastFrameInfo(
310 uint32 output_id,
311 scoped_ptr<cc::CompositorFrame> output_frame)
312 : output_surface_id(output_id), frame(output_frame.Pass()) {}
314 RenderWidgetHostViewAndroid::LastFrameInfo::~LastFrameInfo() {}
316 void RenderWidgetHostViewAndroid::OnContextLost() {
317 scoped_ptr<RenderWidgetHostIterator> widgets(
318 RenderWidgetHostImpl::GetAllRenderWidgetHosts());
319 while (RenderWidgetHost* widget = widgets->GetNextHost()) {
320 if (widget->GetView()) {
321 static_cast<RenderWidgetHostViewAndroid*>(widget->GetView())
322 ->OnLostResources();
327 RenderWidgetHostViewAndroid::RenderWidgetHostViewAndroid(
328 RenderWidgetHostImpl* widget_host,
329 ContentViewCoreImpl* content_view_core)
330 : host_(widget_host),
331 outstanding_vsync_requests_(0),
332 is_showing_(!widget_host->is_hidden()),
333 content_view_core_(nullptr),
334 content_view_core_window_android_(nullptr),
335 ime_adapter_android_(this),
336 cached_background_color_(SK_ColorWHITE),
337 last_output_surface_id_(kUndefinedOutputSurfaceId),
338 gesture_provider_(CreateGestureProviderConfig(), this),
339 stylus_text_selector_(this),
340 accelerated_surface_route_id_(0),
341 using_browser_compositor_(CompositorImpl::IsInitialized()),
342 frame_evictor_(new DelegatedFrameEvictor(this)),
343 locks_on_frame_count_(0),
344 observing_root_window_(false),
345 weak_ptr_factory_(this) {
346 if (CompositorImpl::GetSurfaceManager())
347 id_allocator_ = CompositorImpl::CreateSurfaceIdAllocator();
348 host_->SetView(this);
349 SetContentViewCore(content_view_core);
352 RenderWidgetHostViewAndroid::~RenderWidgetHostViewAndroid() {
353 SetContentViewCore(NULL);
354 DCHECK(ack_callbacks_.empty());
355 if (resource_collection_.get())
356 resource_collection_->SetClient(NULL);
357 DCHECK(!surface_factory_);
358 DCHECK(surface_id_.is_null());
361 void RenderWidgetHostViewAndroid::Blur() {
362 host_->Blur();
363 if (overscroll_controller_)
364 overscroll_controller_->Disable();
367 bool RenderWidgetHostViewAndroid::OnMessageReceived(
368 const IPC::Message& message) {
369 bool handled = true;
370 IPC_BEGIN_MESSAGE_MAP(RenderWidgetHostViewAndroid, message)
371 IPC_MESSAGE_HANDLER(ViewHostMsg_StartContentIntent, OnStartContentIntent)
372 IPC_MESSAGE_HANDLER(ViewHostMsg_DidChangeBodyBackgroundColor,
373 OnDidChangeBodyBackgroundColor)
374 IPC_MESSAGE_HANDLER(ViewHostMsg_SetNeedsBeginFrames,
375 OnSetNeedsBeginFrames)
376 IPC_MESSAGE_HANDLER(ViewHostMsg_SmartClipDataExtracted,
377 OnSmartClipDataExtracted)
378 IPC_MESSAGE_HANDLER(ViewHostMsg_ShowUnhandledTapUIIfNeeded,
379 OnShowUnhandledTapUIIfNeeded)
380 IPC_MESSAGE_UNHANDLED(handled = false)
381 IPC_END_MESSAGE_MAP()
382 return handled;
385 void RenderWidgetHostViewAndroid::InitAsChild(gfx::NativeView parent_view) {
386 NOTIMPLEMENTED();
389 void RenderWidgetHostViewAndroid::InitAsPopup(
390 RenderWidgetHostView* parent_host_view, const gfx::Rect& pos) {
391 NOTIMPLEMENTED();
394 void RenderWidgetHostViewAndroid::InitAsFullscreen(
395 RenderWidgetHostView* reference_host_view) {
396 NOTIMPLEMENTED();
399 RenderWidgetHost*
400 RenderWidgetHostViewAndroid::GetRenderWidgetHost() const {
401 return host_;
404 void RenderWidgetHostViewAndroid::WasResized() {
405 host_->WasResized();
408 void RenderWidgetHostViewAndroid::SetSize(const gfx::Size& size) {
409 // Ignore the given size as only the Java code has the power to
410 // resize the view on Android.
411 default_size_ = size;
414 void RenderWidgetHostViewAndroid::SetBounds(const gfx::Rect& rect) {
415 SetSize(rect.size());
418 void RenderWidgetHostViewAndroid::GetScaledContentBitmap(
419 float scale,
420 SkColorType preferred_color_type,
421 gfx::Rect src_subrect,
422 ReadbackRequestCallback& result_callback) {
423 if (!host_ || host_->is_hidden() || !IsSurfaceAvailableForCopy()) {
424 result_callback.Run(SkBitmap(), READBACK_SURFACE_UNAVAILABLE);
425 return;
427 gfx::Size bounds = layer_->bounds();
428 if (src_subrect.IsEmpty())
429 src_subrect = gfx::Rect(bounds);
430 DCHECK_LE(src_subrect.width() + src_subrect.x(), bounds.width());
431 DCHECK_LE(src_subrect.height() + src_subrect.y(), bounds.height());
432 const gfx::Display& display =
433 gfx::Screen::GetNativeScreen()->GetPrimaryDisplay();
434 float device_scale_factor = display.device_scale_factor();
435 DCHECK_GT(device_scale_factor, 0);
436 gfx::Size dst_size(gfx::ToCeiledSize(
437 gfx::ScaleSize(src_subrect.size(), scale / device_scale_factor)));
438 src_subrect = gfx::ConvertRectToDIP(device_scale_factor, src_subrect);
440 CopyFromCompositingSurface(src_subrect, dst_size, result_callback,
441 preferred_color_type);
444 scoped_refptr<cc::Layer> RenderWidgetHostViewAndroid::CreateDelegatedLayer()
445 const {
446 scoped_refptr<cc::Layer> delegated_layer;
447 if (!surface_id_.is_null()) {
448 cc::SurfaceManager* manager = CompositorImpl::GetSurfaceManager();
449 DCHECK(manager);
450 // manager must outlive compositors using it.
451 scoped_refptr<cc::SurfaceLayer> surface_layer = cc::SurfaceLayer::Create(
452 Compositor::LayerSettings(),
453 base::Bind(&SatisfyCallback, base::Unretained(manager)),
454 base::Bind(&RequireCallback, base::Unretained(manager)));
455 surface_layer->SetSurfaceId(surface_id_, 1.f, texture_size_in_layer_);
456 delegated_layer = surface_layer;
457 } else {
458 DCHECK(frame_provider_.get());
459 delegated_layer = cc::DelegatedRendererLayer::Create(
460 Compositor::LayerSettings(), frame_provider_);
462 delegated_layer->SetBounds(content_size_in_layer_);
463 delegated_layer->SetIsDrawable(true);
464 delegated_layer->SetContentsOpaque(true);
466 return delegated_layer;
469 bool RenderWidgetHostViewAndroid::HasValidFrame() const {
470 if (!content_view_core_)
471 return false;
472 if (!layer_.get())
473 return false;
475 if (texture_size_in_layer_.IsEmpty())
476 return false;
477 // This tell us whether a valid frame has arrived or not.
478 if (!frame_evictor_->HasFrame())
479 return false;
481 return true;
484 gfx::Vector2dF RenderWidgetHostViewAndroid::GetLastScrollOffset() const {
485 return last_scroll_offset_;
488 gfx::NativeView RenderWidgetHostViewAndroid::GetNativeView() const {
489 return content_view_core_->GetViewAndroid();
492 gfx::NativeViewId RenderWidgetHostViewAndroid::GetNativeViewId() const {
493 return reinterpret_cast<gfx::NativeViewId>(
494 const_cast<RenderWidgetHostViewAndroid*>(this));
497 gfx::NativeViewAccessible
498 RenderWidgetHostViewAndroid::GetNativeViewAccessible() {
499 NOTIMPLEMENTED();
500 return NULL;
503 void RenderWidgetHostViewAndroid::MovePluginWindows(
504 const std::vector<WebPluginGeometry>& moves) {
505 // We don't have plugin windows on Android. Do nothing. Note: this is called
506 // from RenderWidgetHost::OnUpdateRect which is itself invoked while
507 // processing the corresponding message from Renderer.
510 void RenderWidgetHostViewAndroid::Focus() {
511 host_->Focus();
512 if (overscroll_controller_)
513 overscroll_controller_->Enable();
514 if (content_view_core_) {
515 WebContentsImpl* web_contents_impl =
516 static_cast<WebContentsImpl*>(content_view_core_->GetWebContents());
517 if (web_contents_impl->ShowingInterstitialPage())
518 content_view_core_->ForceUpdateImeAdapter(GetNativeImeAdapter());
522 bool RenderWidgetHostViewAndroid::HasFocus() const {
523 if (!content_view_core_)
524 return false; // ContentViewCore not created yet.
526 return content_view_core_->HasFocus();
529 bool RenderWidgetHostViewAndroid::IsSurfaceAvailableForCopy() const {
530 return HasValidFrame();
533 void RenderWidgetHostViewAndroid::Show() {
534 if (is_showing_)
535 return;
537 is_showing_ = true;
538 ShowInternal();
541 void RenderWidgetHostViewAndroid::Hide() {
542 if (!is_showing_)
543 return;
545 is_showing_ = false;
547 bool hide_frontbuffer = true;
548 bool stop_observing_root_window = true;
549 HideInternal(hide_frontbuffer, stop_observing_root_window);
552 bool RenderWidgetHostViewAndroid::IsShowing() {
553 // ContentViewCoreImpl represents the native side of the Java
554 // ContentViewCore. It being NULL means that it is not attached
555 // to the View system yet, so we treat this RWHVA as hidden.
556 return is_showing_ && content_view_core_;
559 void RenderWidgetHostViewAndroid::LockCompositingSurface() {
560 DCHECK(HasValidFrame());
561 DCHECK(host_);
562 DCHECK(frame_evictor_->HasFrame());
563 frame_evictor_->LockFrame();
564 locks_on_frame_count_++;
567 void RenderWidgetHostViewAndroid::UnlockCompositingSurface() {
568 if (!frame_evictor_->HasFrame() || locks_on_frame_count_ == 0)
569 return;
571 DCHECK(HasValidFrame());
572 frame_evictor_->UnlockFrame();
573 locks_on_frame_count_--;
575 if (locks_on_frame_count_ == 0) {
576 if (last_frame_info_) {
577 InternalSwapCompositorFrame(last_frame_info_->output_surface_id,
578 last_frame_info_->frame.Pass());
579 last_frame_info_.reset();
582 if (!is_showing_ && layer_.get())
583 layer_->SetHideLayerAndSubtree(true);
587 void RenderWidgetHostViewAndroid::SetTextSurroundingSelectionCallback(
588 const TextSurroundingSelectionCallback& callback) {
589 // Only one outstanding request is allowed at any given time.
590 DCHECK(!callback.is_null());
591 text_surrounding_selection_callback_ = callback;
594 void RenderWidgetHostViewAndroid::OnTextSurroundingSelectionResponse(
595 const base::string16& content,
596 size_t start_offset,
597 size_t end_offset) {
598 if (text_surrounding_selection_callback_.is_null())
599 return;
600 text_surrounding_selection_callback_.Run(content, start_offset, end_offset);
601 text_surrounding_selection_callback_.Reset();
604 void RenderWidgetHostViewAndroid::OnShowUnhandledTapUIIfNeeded(int x_dip,
605 int y_dip) {
606 if (!content_view_core_)
607 return;
608 // Validate the coordinates are within the viewport.
609 gfx::Size viewport_size = content_view_core_->GetViewportSizeDip();
610 if (x_dip < 0 || x_dip > viewport_size.width() ||
611 y_dip < 0 || y_dip > viewport_size.height())
612 return;
613 content_view_core_->OnShowUnhandledTapUIIfNeeded(x_dip, y_dip);
616 void RenderWidgetHostViewAndroid::ReleaseLocksOnSurface() {
617 if (!frame_evictor_->HasFrame()) {
618 DCHECK_EQ(locks_on_frame_count_, 0u);
619 return;
621 while (locks_on_frame_count_ > 0) {
622 UnlockCompositingSurface();
624 RunAckCallbacks(cc::SurfaceDrawStatus::DRAW_SKIPPED);
627 gfx::Rect RenderWidgetHostViewAndroid::GetViewBounds() const {
628 if (!content_view_core_)
629 return gfx::Rect(default_size_);
631 return gfx::Rect(content_view_core_->GetViewSize());
634 gfx::Size RenderWidgetHostViewAndroid::GetPhysicalBackingSize() const {
635 if (!content_view_core_)
636 return gfx::Size();
638 return content_view_core_->GetPhysicalBackingSize();
641 bool RenderWidgetHostViewAndroid::DoTopControlsShrinkBlinkSize() const {
642 if (!content_view_core_)
643 return false;
645 // Whether or not Blink's viewport size should be shrunk by the height of the
646 // URL-bar.
647 return content_view_core_->DoTopControlsShrinkBlinkSize();
650 float RenderWidgetHostViewAndroid::GetTopControlsHeight() const {
651 if (!content_view_core_)
652 return 0.f;
654 // The height of the top controls.
655 return content_view_core_->GetTopControlsHeightDip();
658 void RenderWidgetHostViewAndroid::UpdateCursor(const WebCursor& cursor) {
659 // There are no cursors on Android.
662 void RenderWidgetHostViewAndroid::SetIsLoading(bool is_loading) {
663 // Do nothing. The UI notification is handled through ContentViewClient which
664 // is TabContentsDelegate.
667 long RenderWidgetHostViewAndroid::GetNativeImeAdapter() {
668 return reinterpret_cast<intptr_t>(&ime_adapter_android_);
671 void RenderWidgetHostViewAndroid::TextInputStateChanged(
672 const ViewHostMsg_TextInputState_Params& params) {
673 // If the change is not originated from IME (e.g. Javascript, autofill),
674 // send back the renderer an acknowledgement, regardless of how we exit from
675 // this method.
676 base::ScopedClosureRunner ack_caller;
677 if (params.is_non_ime_change)
678 ack_caller.Reset(base::Bind(&SendImeEventAck, host_));
680 if (!IsShowing())
681 return;
683 content_view_core_->UpdateImeAdapter(
684 GetNativeImeAdapter(),
685 static_cast<int>(params.type), params.flags,
686 params.value, params.selection_start, params.selection_end,
687 params.composition_start, params.composition_end,
688 params.show_ime_if_needed, params.is_non_ime_change);
691 void RenderWidgetHostViewAndroid::OnDidChangeBodyBackgroundColor(
692 SkColor color) {
693 if (cached_background_color_ == color)
694 return;
696 cached_background_color_ = color;
697 if (content_view_core_)
698 content_view_core_->OnBackgroundColorChanged(color);
701 void RenderWidgetHostViewAndroid::OnSetNeedsBeginFrames(bool enabled) {
702 TRACE_EVENT1("cc", "RenderWidgetHostViewAndroid::OnSetNeedsBeginFrames",
703 "enabled", enabled);
704 if (enabled)
705 RequestVSyncUpdate(PERSISTENT_BEGIN_FRAME);
706 else
707 outstanding_vsync_requests_ &= ~PERSISTENT_BEGIN_FRAME;
710 void RenderWidgetHostViewAndroid::OnStartContentIntent(
711 const GURL& content_url) {
712 if (content_view_core_)
713 content_view_core_->StartContentIntent(content_url);
716 void RenderWidgetHostViewAndroid::OnSmartClipDataExtracted(
717 const base::string16& text,
718 const base::string16& html,
719 const gfx::Rect rect) {
720 if (content_view_core_)
721 content_view_core_->OnSmartClipDataExtracted(text, html, rect);
724 bool RenderWidgetHostViewAndroid::OnTouchEvent(
725 const ui::MotionEvent& event) {
726 if (!host_)
727 return false;
729 // If a browser-based widget consumes the touch event, it's critical that
730 // touch event interception be disabled. This avoids issues with
731 // double-handling for embedder-detected gestures like side swipe.
732 if (selection_controller_ &&
733 selection_controller_->WillHandleTouchEvent(event)) {
734 RequestDisallowInterceptTouchEvent();
735 return true;
738 if (stylus_text_selector_.OnTouchEvent(event)) {
739 RequestDisallowInterceptTouchEvent();
740 return true;
743 ui::FilteredGestureProvider::TouchHandlingResult result =
744 gesture_provider_.OnTouchEvent(event);
745 if (!result.succeeded)
746 return false;
748 blink::WebTouchEvent web_event =
749 ui::CreateWebTouchEventFromMotionEvent(event, result.did_generate_scroll);
750 host_->ForwardTouchEventWithLatencyInfo(web_event, ui::LatencyInfo());
752 // Send a proactive BeginFrame for this vsync to reduce scroll latency for
753 // scroll-inducing touch events. Note that Android's Choreographer ensures
754 // that BeginFrame requests made during ACTION_MOVE dispatch will be honored
755 // in the same vsync phase.
756 if (observing_root_window_&& result.did_generate_scroll)
757 RequestVSyncUpdate(BEGIN_FRAME);
759 return true;
762 bool RenderWidgetHostViewAndroid::OnTouchHandleEvent(
763 const ui::MotionEvent& event) {
764 return selection_controller_ &&
765 selection_controller_->WillHandleTouchEvent(event);
768 void RenderWidgetHostViewAndroid::ResetGestureDetection() {
769 const ui::MotionEvent* current_down_event =
770 gesture_provider_.GetCurrentDownEvent();
771 if (!current_down_event) {
772 // A hard reset ensures prevention of any timer-based events that might fire
773 // after a touch sequence has ended.
774 gesture_provider_.ResetDetection();
775 return;
778 scoped_ptr<ui::MotionEvent> cancel_event = current_down_event->Cancel();
779 if (gesture_provider_.OnTouchEvent(*cancel_event).succeeded) {
780 bool causes_scrolling = false;
781 host_->ForwardTouchEventWithLatencyInfo(
782 ui::CreateWebTouchEventFromMotionEvent(*cancel_event, causes_scrolling),
783 ui::LatencyInfo());
787 void RenderWidgetHostViewAndroid::OnDidNavigateMainFrameToNewPage() {
788 ResetGestureDetection();
791 void RenderWidgetHostViewAndroid::SetDoubleTapSupportEnabled(bool enabled) {
792 gesture_provider_.SetDoubleTapSupportForPlatformEnabled(enabled);
795 void RenderWidgetHostViewAndroid::SetMultiTouchZoomSupportEnabled(
796 bool enabled) {
797 gesture_provider_.SetMultiTouchZoomSupportEnabled(enabled);
800 void RenderWidgetHostViewAndroid::ImeCancelComposition() {
801 ime_adapter_android_.CancelComposition();
804 void RenderWidgetHostViewAndroid::ImeCompositionRangeChanged(
805 const gfx::Range& range,
806 const std::vector<gfx::Rect>& character_bounds) {
807 // TODO(yukawa): Implement this.
810 void RenderWidgetHostViewAndroid::FocusedNodeChanged(bool is_editable_node) {
811 ime_adapter_android_.FocusedNodeChanged(is_editable_node);
814 void RenderWidgetHostViewAndroid::RenderProcessGone(
815 base::TerminationStatus status, int error_code) {
816 Destroy();
819 void RenderWidgetHostViewAndroid::Destroy() {
820 RemoveLayers();
821 SetContentViewCore(NULL);
823 if (!surface_id_.is_null()) {
824 DCHECK(surface_factory_.get());
825 surface_factory_->Destroy(surface_id_);
826 surface_id_ = cc::SurfaceId();
828 surface_factory_.reset();
830 // The RenderWidgetHost's destruction led here, so don't call it.
831 host_ = NULL;
833 delete this;
836 void RenderWidgetHostViewAndroid::SetTooltipText(
837 const base::string16& tooltip_text) {
838 // Tooltips don't makes sense on Android.
841 void RenderWidgetHostViewAndroid::SelectionChanged(const base::string16& text,
842 size_t offset,
843 const gfx::Range& range) {
844 RenderWidgetHostViewBase::SelectionChanged(text, offset, range);
846 if (!content_view_core_)
847 return;
848 if (range.is_empty()) {
849 content_view_core_->OnSelectionChanged("");
850 return;
853 DCHECK(!text.empty());
854 size_t pos = range.GetMin() - offset;
855 size_t n = range.length();
857 DCHECK(pos + n <= text.length()) << "The text can not fully cover range.";
858 if (pos >= text.length()) {
859 NOTREACHED() << "The text can not cover range.";
860 return;
863 std::string utf8_selection = base::UTF16ToUTF8(text.substr(pos, n));
865 content_view_core_->OnSelectionChanged(utf8_selection);
868 void RenderWidgetHostViewAndroid::SelectionBoundsChanged(
869 const ViewHostMsg_SelectionBounds_Params& params) {
870 NOTREACHED() << "Selection bounds should be routed through the compositor.";
873 void RenderWidgetHostViewAndroid::SetBackgroundColor(SkColor color) {
874 RenderWidgetHostViewBase::SetBackgroundColor(color);
875 host_->SetBackgroundOpaque(GetBackgroundOpaque());
876 OnDidChangeBodyBackgroundColor(color);
879 void RenderWidgetHostViewAndroid::CopyFromCompositingSurface(
880 const gfx::Rect& src_subrect,
881 const gfx::Size& dst_size,
882 ReadbackRequestCallback& callback,
883 const SkColorType preferred_color_type) {
884 TRACE_EVENT0("cc", "RenderWidgetHostViewAndroid::CopyFromCompositingSurface");
885 if (!host_ || host_->is_hidden()) {
886 callback.Run(SkBitmap(), READBACK_SURFACE_UNAVAILABLE);
887 return;
889 base::TimeTicks start_time = base::TimeTicks::Now();
890 if (using_browser_compositor_ && !IsSurfaceAvailableForCopy()) {
891 callback.Run(SkBitmap(), READBACK_SURFACE_UNAVAILABLE);
892 return;
894 const gfx::Display& display =
895 gfx::Screen::GetNativeScreen()->GetPrimaryDisplay();
896 float device_scale_factor = display.device_scale_factor();
897 gfx::Size dst_size_in_pixel =
898 gfx::ConvertRectToPixel(device_scale_factor, gfx::Rect(dst_size)).size();
899 gfx::Rect src_subrect_in_pixel =
900 gfx::ConvertRectToPixel(device_scale_factor, src_subrect);
902 if (!using_browser_compositor_) {
903 SynchronousCopyContents(src_subrect_in_pixel, dst_size_in_pixel, callback,
904 preferred_color_type);
905 UMA_HISTOGRAM_TIMES("Compositing.CopyFromSurfaceTimeSynchronous",
906 base::TimeTicks::Now() - start_time);
907 return;
910 scoped_ptr<cc::CopyOutputRequest> request;
911 scoped_refptr<cc::Layer> readback_layer;
912 DCHECK(content_view_core_window_android_);
913 ui::WindowAndroidCompositor* compositor =
914 content_view_core_window_android_->GetCompositor();
915 DCHECK(compositor);
916 DCHECK(frame_provider_.get() || !surface_id_.is_null());
917 scoped_refptr<cc::Layer> layer = CreateDelegatedLayer();
918 DCHECK(layer);
919 layer->SetHideLayerAndSubtree(true);
920 compositor->AttachLayerForReadback(layer);
922 readback_layer = layer;
923 request = cc::CopyOutputRequest::CreateRequest(
924 base::Bind(&RenderWidgetHostViewAndroid::
925 PrepareTextureCopyOutputResultForDelegatedReadback,
926 dst_size_in_pixel, preferred_color_type, start_time,
927 readback_layer, callback));
928 if (!src_subrect_in_pixel.IsEmpty())
929 request->set_area(src_subrect_in_pixel);
930 readback_layer->RequestCopyOfOutput(request.Pass());
933 void RenderWidgetHostViewAndroid::CopyFromCompositingSurfaceToVideoFrame(
934 const gfx::Rect& src_subrect,
935 const scoped_refptr<media::VideoFrame>& target,
936 const base::Callback<void(bool)>& callback) {
937 NOTIMPLEMENTED();
938 callback.Run(false);
941 bool RenderWidgetHostViewAndroid::CanCopyToVideoFrame() const {
942 return false;
945 void RenderWidgetHostViewAndroid::ShowDisambiguationPopup(
946 const gfx::Rect& rect_pixels, const SkBitmap& zoomed_bitmap) {
947 if (!content_view_core_)
948 return;
950 content_view_core_->ShowDisambiguationPopup(rect_pixels, zoomed_bitmap);
953 scoped_ptr<SyntheticGestureTarget>
954 RenderWidgetHostViewAndroid::CreateSyntheticGestureTarget() {
955 return scoped_ptr<SyntheticGestureTarget>(new SyntheticGestureTargetAndroid(
956 host_, content_view_core_->CreateMotionEventSynthesizer()));
959 void RenderWidgetHostViewAndroid::SendDelegatedFrameAck(
960 uint32 output_surface_id) {
961 DCHECK(host_);
962 cc::CompositorFrameAck ack;
963 if (!surface_returned_resources_.empty())
964 ack.resources.swap(surface_returned_resources_);
965 if (resource_collection_.get())
966 resource_collection_->TakeUnusedResourcesForChildCompositor(&ack.resources);
967 host_->Send(new ViewMsg_SwapCompositorFrameAck(host_->GetRoutingID(),
968 output_surface_id, ack));
971 void RenderWidgetHostViewAndroid::SendReturnedDelegatedResources(
972 uint32 output_surface_id) {
973 DCHECK(host_);
974 cc::CompositorFrameAck ack;
975 if (!surface_returned_resources_.empty()) {
976 ack.resources.swap(surface_returned_resources_);
977 } else {
978 DCHECK(resource_collection_.get());
979 resource_collection_->TakeUnusedResourcesForChildCompositor(&ack.resources);
982 host_->Send(new ViewMsg_ReclaimCompositorResources(host_->GetRoutingID(),
983 output_surface_id, ack));
986 void RenderWidgetHostViewAndroid::UnusedResourcesAreAvailable() {
987 DCHECK(surface_id_.is_null());
988 if (ack_callbacks_.size())
989 return;
990 SendReturnedDelegatedResources(last_output_surface_id_);
993 void RenderWidgetHostViewAndroid::ReturnResources(
994 const cc::ReturnedResourceArray& resources) {
995 if (resources.empty())
996 return;
997 std::copy(resources.begin(), resources.end(),
998 std::back_inserter(surface_returned_resources_));
999 if (!ack_callbacks_.size())
1000 SendReturnedDelegatedResources(last_output_surface_id_);
1003 void RenderWidgetHostViewAndroid::DestroyDelegatedContent() {
1004 RemoveLayers();
1005 frame_provider_ = NULL;
1006 if (!surface_id_.is_null()) {
1007 DCHECK(surface_factory_.get());
1008 surface_factory_->Destroy(surface_id_);
1009 surface_id_ = cc::SurfaceId();
1011 layer_ = NULL;
1014 void RenderWidgetHostViewAndroid::CheckOutputSurfaceChanged(
1015 uint32 output_surface_id) {
1016 if (output_surface_id == last_output_surface_id_)
1017 return;
1018 // Drop the cc::DelegatedFrameResourceCollection so that we will not return
1019 // any resources from the old output surface with the new output surface id.
1020 if (resource_collection_.get()) {
1021 resource_collection_->SetClient(NULL);
1022 if (resource_collection_->LoseAllResources())
1023 SendReturnedDelegatedResources(last_output_surface_id_);
1024 resource_collection_ = NULL;
1026 DestroyDelegatedContent();
1027 surface_factory_.reset();
1028 if (!surface_returned_resources_.empty())
1029 SendReturnedDelegatedResources(last_output_surface_id_);
1031 last_output_surface_id_ = output_surface_id;
1034 void RenderWidgetHostViewAndroid::SubmitFrame(
1035 scoped_ptr<cc::CompositorFrame> frame) {
1036 cc::SurfaceManager* manager = CompositorImpl::GetSurfaceManager();
1037 if (manager) {
1038 if (!surface_factory_) {
1039 surface_factory_ = make_scoped_ptr(new cc::SurfaceFactory(manager, this));
1041 if (surface_id_.is_null() ||
1042 texture_size_in_layer_ != current_surface_size_) {
1043 RemoveLayers();
1044 if (!surface_id_.is_null())
1045 surface_factory_->Destroy(surface_id_);
1046 surface_id_ = id_allocator_->GenerateId();
1047 surface_factory_->Create(surface_id_);
1048 layer_ = CreateDelegatedLayer();
1050 DCHECK(layer_);
1052 current_surface_size_ = texture_size_in_layer_;
1053 AttachLayers();
1056 cc::SurfaceFactory::DrawCallback ack_callback =
1057 base::Bind(&RenderWidgetHostViewAndroid::RunAckCallbacks,
1058 weak_ptr_factory_.GetWeakPtr());
1059 surface_factory_->SubmitFrame(surface_id_, frame.Pass(), ack_callback);
1060 } else {
1061 if (!resource_collection_.get()) {
1062 resource_collection_ = new cc::DelegatedFrameResourceCollection;
1063 resource_collection_->SetClient(this);
1065 if (!frame_provider_.get() ||
1066 texture_size_in_layer_ != frame_provider_->frame_size()) {
1067 RemoveLayers();
1068 frame_provider_ = new cc::DelegatedFrameProvider(
1069 resource_collection_.get(), frame->delegated_frame_data.Pass());
1070 layer_ = cc::DelegatedRendererLayer::Create(Compositor::LayerSettings(),
1071 frame_provider_);
1072 AttachLayers();
1073 } else {
1074 frame_provider_->SetFrameData(frame->delegated_frame_data.Pass());
1079 void RenderWidgetHostViewAndroid::SwapDelegatedFrame(
1080 uint32 output_surface_id,
1081 scoped_ptr<cc::CompositorFrame> frame) {
1082 CheckOutputSurfaceChanged(output_surface_id);
1083 bool has_content = !texture_size_in_layer_.IsEmpty();
1085 // DelegatedRendererLayerImpl applies the inverse device_scale_factor of the
1086 // renderer frame, assuming that the browser compositor will scale
1087 // it back up to device scale. But on Android we put our browser layers in
1088 // physical pixels and set our browser CC device_scale_factor to 1, so this
1089 // suppresses the transform. This line may need to be removed when fixing
1090 // http://crbug.com/384134 or http://crbug.com/310763
1091 frame->delegated_frame_data->device_scale_factor = 1.0f;
1093 base::Closure ack_callback =
1094 base::Bind(&RenderWidgetHostViewAndroid::SendDelegatedFrameAck,
1095 weak_ptr_factory_.GetWeakPtr(),
1096 output_surface_id);
1098 ack_callbacks_.push(ack_callback);
1100 if (!has_content) {
1101 DestroyDelegatedContent();
1102 } else {
1103 SubmitFrame(frame.Pass());
1106 if (layer_.get()) {
1107 layer_->SetIsDrawable(true);
1108 layer_->SetContentsOpaque(true);
1109 layer_->SetBounds(content_size_in_layer_);
1112 if (host_->is_hidden())
1113 RunAckCallbacks(cc::SurfaceDrawStatus::DRAW_SKIPPED);
1116 void RenderWidgetHostViewAndroid::ComputeContentsSize(
1117 const cc::CompositorFrameMetadata& frame_metadata) {
1118 // Calculate the content size. This should be 0 if the texture_size is 0.
1119 gfx::Vector2dF offset;
1120 if (texture_size_in_layer_.IsEmpty())
1121 content_size_in_layer_ = gfx::Size();
1122 content_size_in_layer_ = gfx::ToCeiledSize(gfx::ScaleSize(
1123 frame_metadata.scrollable_viewport_size,
1124 frame_metadata.device_scale_factor * frame_metadata.page_scale_factor));
1128 void RenderWidgetHostViewAndroid::InternalSwapCompositorFrame(
1129 uint32 output_surface_id,
1130 scoped_ptr<cc::CompositorFrame> frame) {
1131 last_scroll_offset_ = frame->metadata.root_scroll_offset;
1132 if (!frame->delegated_frame_data) {
1133 LOG(ERROR) << "Non-delegated renderer path no longer supported";
1134 return;
1137 if (locks_on_frame_count_ > 0) {
1138 DCHECK(HasValidFrame());
1139 RetainFrame(output_surface_id, frame.Pass());
1140 return;
1143 if (!CompositorImpl::GetSurfaceManager() && layer_.get() &&
1144 layer_->layer_tree_host()) {
1145 for (size_t i = 0; i < frame->metadata.latency_info.size(); i++) {
1146 scoped_ptr<cc::SwapPromise> swap_promise(
1147 new cc::LatencyInfoSwapPromise(frame->metadata.latency_info[i]));
1148 layer_->layer_tree_host()->QueueSwapPromise(swap_promise.Pass());
1152 DCHECK(!frame->delegated_frame_data->render_pass_list.empty());
1154 cc::RenderPass* root_pass =
1155 frame->delegated_frame_data->render_pass_list.back();
1156 texture_size_in_layer_ = root_pass->output_rect.size();
1157 ComputeContentsSize(frame->metadata);
1159 cc::CompositorFrameMetadata metadata = frame->metadata;
1161 SwapDelegatedFrame(output_surface_id, frame.Pass());
1162 frame_evictor_->SwappedFrame(!host_->is_hidden());
1164 // As the metadata update may trigger view invalidation, always call it after
1165 // any potential compositor scheduling.
1166 OnFrameMetadataUpdated(metadata);
1169 void RenderWidgetHostViewAndroid::OnSwapCompositorFrame(
1170 uint32 output_surface_id,
1171 scoped_ptr<cc::CompositorFrame> frame) {
1172 InternalSwapCompositorFrame(output_surface_id, frame.Pass());
1175 void RenderWidgetHostViewAndroid::RetainFrame(
1176 uint32 output_surface_id,
1177 scoped_ptr<cc::CompositorFrame> frame) {
1178 DCHECK(locks_on_frame_count_);
1180 // Store the incoming frame so that it can be swapped when all the locks have
1181 // been released. If there is already a stored frame, then replace and skip
1182 // the previous one but make sure we still eventually send the ACK. Holding
1183 // the ACK also blocks the renderer when its max_frames_pending is reached.
1184 if (last_frame_info_) {
1185 base::Closure ack_callback =
1186 base::Bind(&RenderWidgetHostViewAndroid::SendDelegatedFrameAck,
1187 weak_ptr_factory_.GetWeakPtr(),
1188 last_frame_info_->output_surface_id);
1190 ack_callbacks_.push(ack_callback);
1193 last_frame_info_.reset(new LastFrameInfo(output_surface_id, frame.Pass()));
1196 void RenderWidgetHostViewAndroid::SynchronousFrameMetadata(
1197 const cc::CompositorFrameMetadata& frame_metadata) {
1198 if (!content_view_core_)
1199 return;
1201 // This is a subset of OnSwapCompositorFrame() used in the synchronous
1202 // compositor flow.
1203 OnFrameMetadataUpdated(frame_metadata);
1204 ComputeContentsSize(frame_metadata);
1206 // DevTools ScreenCast support for Android WebView.
1207 WebContents* web_contents = content_view_core_->GetWebContents();
1208 if (DevToolsAgentHost::HasFor(web_contents)) {
1209 scoped_refptr<DevToolsAgentHost> dtah =
1210 DevToolsAgentHost::GetOrCreateFor(web_contents);
1211 // Unblock the compositor.
1212 BrowserThread::PostTask(
1213 BrowserThread::UI, FROM_HERE,
1214 base::Bind(
1215 &RenderFrameDevToolsAgentHost::SynchronousSwapCompositorFrame,
1216 static_cast<RenderFrameDevToolsAgentHost*>(dtah.get()),
1217 frame_metadata));
1221 void RenderWidgetHostViewAndroid::SetOverlayVideoMode(bool enabled) {
1222 if (layer_.get())
1223 layer_->SetContentsOpaque(!enabled);
1226 bool RenderWidgetHostViewAndroid::SupportsAnimation() const {
1227 // The synchronous (WebView) compositor does not have a proper browser
1228 // compositor with which to drive animations.
1229 return using_browser_compositor_;
1232 void RenderWidgetHostViewAndroid::SetNeedsAnimate() {
1233 DCHECK(content_view_core_window_android_);
1234 DCHECK(using_browser_compositor_);
1235 content_view_core_window_android_->SetNeedsAnimate();
1238 void RenderWidgetHostViewAndroid::MoveCaret(const gfx::PointF& position) {
1239 MoveCaret(gfx::Point(position.x(), position.y()));
1242 void RenderWidgetHostViewAndroid::MoveRangeSelectionExtent(
1243 const gfx::PointF& extent) {
1244 DCHECK(content_view_core_);
1245 content_view_core_->MoveRangeSelectionExtent(extent);
1248 void RenderWidgetHostViewAndroid::SelectBetweenCoordinates(
1249 const gfx::PointF& base,
1250 const gfx::PointF& extent) {
1251 DCHECK(content_view_core_);
1252 content_view_core_->SelectBetweenCoordinates(base, extent);
1255 void RenderWidgetHostViewAndroid::OnSelectionEvent(
1256 ui::SelectionEventType event) {
1257 DCHECK(content_view_core_);
1258 DCHECK(selection_controller_);
1259 // If a selection drag has started, it has taken over the active touch
1260 // sequence. Immediately cancel gesture detection and any downstream touch
1261 // listeners (e.g., web content) to communicate this transfer.
1262 if (event == ui::SELECTION_HANDLES_SHOWN)
1263 ResetGestureDetection();
1264 content_view_core_->OnSelectionEvent(
1265 event, selection_controller_->GetStartPosition(),
1266 GetSelectionRect(*selection_controller_));
1269 scoped_ptr<ui::TouchHandleDrawable>
1270 RenderWidgetHostViewAndroid::CreateDrawable() {
1271 DCHECK(content_view_core_);
1272 if (!using_browser_compositor_)
1273 return content_view_core_->CreatePopupTouchHandleDrawable();
1275 return scoped_ptr<ui::TouchHandleDrawable>(new CompositedTouchHandleDrawable(
1276 content_view_core_->GetLayer().get(),
1277 content_view_core_->GetDpiScale(),
1278 // Use the activity context (instead of the application context) to ensure
1279 // proper handle theming.
1280 content_view_core_->GetContext().obj()));
1283 void RenderWidgetHostViewAndroid::SynchronousCopyContents(
1284 const gfx::Rect& src_subrect_in_pixel,
1285 const gfx::Size& dst_size_in_pixel,
1286 ReadbackRequestCallback& callback,
1287 const SkColorType color_type) {
1288 gfx::Size input_size_in_pixel;
1289 if (src_subrect_in_pixel.IsEmpty())
1290 input_size_in_pixel = content_size_in_layer_;
1291 else
1292 input_size_in_pixel = src_subrect_in_pixel.size();
1294 gfx::Size output_size_in_pixel;
1295 if (dst_size_in_pixel.IsEmpty())
1296 output_size_in_pixel = input_size_in_pixel;
1297 else
1298 output_size_in_pixel = dst_size_in_pixel;
1299 int output_width = output_size_in_pixel.width();
1300 int output_height = output_size_in_pixel.height();
1302 SynchronousCompositor* compositor =
1303 SynchronousCompositorImpl::FromID(host_->GetProcess()->GetID(),
1304 host_->GetRoutingID());
1305 if (!compositor) {
1306 callback.Run(SkBitmap(), READBACK_FAILED);
1307 return;
1310 SkBitmap bitmap;
1311 bitmap.allocPixels(SkImageInfo::Make(output_width,
1312 output_height,
1313 color_type,
1314 kPremul_SkAlphaType));
1315 SkCanvas canvas(bitmap);
1316 canvas.scale(
1317 (float)output_width / (float)input_size_in_pixel.width(),
1318 (float)output_height / (float)input_size_in_pixel.height());
1319 compositor->DemandDrawSw(&canvas);
1320 callback.Run(bitmap, READBACK_SUCCESS);
1323 void RenderWidgetHostViewAndroid::OnFrameMetadataUpdated(
1324 const cc::CompositorFrameMetadata& frame_metadata) {
1325 bool is_mobile_optimized = IsMobileOptimizedFrame(frame_metadata);
1326 gesture_provider_.SetDoubleTapSupportForPageEnabled(!is_mobile_optimized);
1328 if (!content_view_core_)
1329 return;
1331 if (overscroll_controller_)
1332 overscroll_controller_->OnFrameMetadataUpdated(frame_metadata);
1334 if (selection_controller_) {
1335 selection_controller_->OnSelectionEditable(
1336 frame_metadata.selection.is_editable);
1337 selection_controller_->OnSelectionEmpty(
1338 frame_metadata.selection.is_empty_text_form_control);
1339 selection_controller_->OnSelectionBoundsChanged(
1340 ConvertSelectionBound(frame_metadata.selection.start),
1341 ConvertSelectionBound(frame_metadata.selection.end));
1344 // All offsets and sizes are in CSS pixels.
1345 content_view_core_->UpdateFrameInfo(
1346 frame_metadata.root_scroll_offset,
1347 frame_metadata.page_scale_factor,
1348 gfx::Vector2dF(frame_metadata.min_page_scale_factor,
1349 frame_metadata.max_page_scale_factor),
1350 frame_metadata.root_layer_size,
1351 frame_metadata.scrollable_viewport_size,
1352 frame_metadata.location_bar_offset,
1353 frame_metadata.location_bar_content_translation,
1354 is_mobile_optimized);
1355 #if defined(VIDEO_HOLE)
1356 if (host_ && host_->IsRenderView()) {
1357 RenderViewHostImpl* rvhi = static_cast<RenderViewHostImpl*>(
1358 RenderViewHost::From(host_));
1359 WebContentsImpl* web_contents_impl =
1360 static_cast<WebContentsImpl*>(WebContents::FromRenderViewHost(rvhi));
1361 if (web_contents_impl)
1362 web_contents_impl->media_web_contents_observer()->OnFrameInfoUpdated();
1364 #endif // defined(VIDEO_HOLE)
1367 void RenderWidgetHostViewAndroid::AcceleratedSurfaceInitialized(int route_id) {
1368 // TODO: remove need for the surface id here
1369 accelerated_surface_route_id_ = route_id;
1372 void RenderWidgetHostViewAndroid::ShowInternal() {
1373 DCHECK(is_showing_);
1374 if (!host_ || !host_->is_hidden())
1375 return;
1377 if (layer_.get())
1378 layer_->SetHideLayerAndSubtree(false);
1380 frame_evictor_->SetVisible(true);
1382 if (overscroll_controller_)
1383 overscroll_controller_->Enable();
1385 host_->WasShown(ui::LatencyInfo());
1387 if (content_view_core_) {
1388 StartObservingRootWindow();
1389 RequestVSyncUpdate(BEGIN_FRAME);
1393 void RenderWidgetHostViewAndroid::HideInternal(
1394 bool hide_frontbuffer,
1395 bool stop_observing_root_window) {
1396 if (hide_frontbuffer) {
1397 if (layer_.get() && locks_on_frame_count_ == 0)
1398 layer_->SetHideLayerAndSubtree(true);
1400 frame_evictor_->SetVisible(false);
1403 if (stop_observing_root_window)
1404 StopObservingRootWindow();
1406 if (!host_ || host_->is_hidden())
1407 return;
1409 if (overscroll_controller_)
1410 overscroll_controller_->Disable();
1412 RunAckCallbacks(cc::SurfaceDrawStatus::DRAW_SKIPPED);
1414 // Inform the renderer that we are being hidden so it can reduce its resource
1415 // utilization.
1416 host_->WasHidden();
1419 void RenderWidgetHostViewAndroid::AttachLayers() {
1420 if (!content_view_core_)
1421 return;
1422 if (!layer_.get())
1423 return;
1425 content_view_core_->AttachLayer(layer_);
1426 if (overscroll_controller_)
1427 overscroll_controller_->Enable();
1428 layer_->SetHideLayerAndSubtree(!is_showing_);
1431 void RenderWidgetHostViewAndroid::RemoveLayers() {
1432 if (!content_view_core_)
1433 return;
1435 if (!layer_.get())
1436 return;
1438 content_view_core_->RemoveLayer(layer_);
1439 if (overscroll_controller_)
1440 overscroll_controller_->Disable();
1443 void RenderWidgetHostViewAndroid::RequestVSyncUpdate(uint32 requests) {
1444 bool should_request_vsync = !outstanding_vsync_requests_ && requests;
1445 outstanding_vsync_requests_ |= requests;
1447 // If the host has been hidden, defer vsync requests until it is shown
1448 // again via |Show()|.
1449 if (!host_ || host_->is_hidden())
1450 return;
1452 // Note that if we're not currently observing the root window, outstanding
1453 // vsync requests will be pushed if/when we resume observing in
1454 // |StartObservingRootWindow()|.
1455 if (observing_root_window_ && should_request_vsync)
1456 content_view_core_window_android_->RequestVSyncUpdate();
1459 void RenderWidgetHostViewAndroid::StartObservingRootWindow() {
1460 DCHECK(content_view_core_window_android_);
1461 DCHECK(is_showing_);
1462 if (observing_root_window_)
1463 return;
1465 observing_root_window_ = true;
1466 content_view_core_window_android_->AddObserver(this);
1468 // Clear existing vsync requests to allow a request to the new window.
1469 uint32 outstanding_vsync_requests = outstanding_vsync_requests_;
1470 outstanding_vsync_requests_ = 0;
1471 RequestVSyncUpdate(outstanding_vsync_requests);
1474 void RenderWidgetHostViewAndroid::StopObservingRootWindow() {
1475 if (!content_view_core_window_android_) {
1476 DCHECK(!observing_root_window_);
1477 return;
1480 if (!observing_root_window_)
1481 return;
1483 observing_root_window_ = false;
1484 content_view_core_window_android_->RemoveObserver(this);
1487 void RenderWidgetHostViewAndroid::SendBeginFrame(base::TimeTicks frame_time,
1488 base::TimeDelta vsync_period) {
1489 TRACE_EVENT1("cc", "RenderWidgetHostViewAndroid::SendBeginFrame",
1490 "frame_time_us", frame_time.ToInternalValue());
1492 if (using_browser_compositor_) {
1493 // TODO(brianderson): Replace this hardcoded deadline after Android
1494 // switches to Surfaces and the Browser's commit isn't in the critcal path.
1495 base::TimeTicks deadline = frame_time + (vsync_period * 0.6);
1497 host_->Send(new ViewMsg_BeginFrame(
1498 host_->GetRoutingID(),
1499 cc::BeginFrameArgs::Create(BEGINFRAME_FROM_HERE, frame_time, deadline,
1500 vsync_period, cc::BeginFrameArgs::NORMAL)));
1501 } else {
1502 SynchronousCompositorImpl* compositor = SynchronousCompositorImpl::FromID(
1503 host_->GetProcess()->GetID(), host_->GetRoutingID());
1504 if (compositor) {
1505 // The synchronous compositor synchronously does it's work in this call.
1506 // It does not use a deadline.
1507 compositor->BeginFrame(cc::BeginFrameArgs::Create(
1508 BEGINFRAME_FROM_HERE, frame_time, base::TimeTicks(), vsync_period,
1509 cc::BeginFrameArgs::NORMAL));
1514 bool RenderWidgetHostViewAndroid::Animate(base::TimeTicks frame_time) {
1515 bool needs_animate = false;
1516 if (overscroll_controller_) {
1517 needs_animate |= overscroll_controller_->Animate(
1518 frame_time, content_view_core_->GetLayer().get());
1520 if (selection_controller_)
1521 needs_animate |= selection_controller_->Animate(frame_time);
1522 return needs_animate;
1525 void RenderWidgetHostViewAndroid::RequestDisallowInterceptTouchEvent() {
1526 if (content_view_core_)
1527 content_view_core_->RequestDisallowInterceptTouchEvent();
1530 void RenderWidgetHostViewAndroid::EvictDelegatedFrame() {
1531 if (layer_.get())
1532 DestroyDelegatedContent();
1533 frame_evictor_->DiscardedFrame();
1536 bool RenderWidgetHostViewAndroid::HasAcceleratedSurface(
1537 const gfx::Size& desired_size) {
1538 NOTREACHED();
1539 return false;
1542 void RenderWidgetHostViewAndroid::GetScreenInfo(blink::WebScreenInfo* result) {
1543 // ScreenInfo isn't tied to the widget on Android. Always return the default.
1544 RenderWidgetHostViewBase::GetDefaultScreenInfo(result);
1547 // TODO(jrg): Find out the implications and answer correctly here,
1548 // as we are returning the WebView and not root window bounds.
1549 gfx::Rect RenderWidgetHostViewAndroid::GetBoundsInRootWindow() {
1550 return GetViewBounds();
1553 gfx::GLSurfaceHandle RenderWidgetHostViewAndroid::GetCompositingSurface() {
1554 gfx::GLSurfaceHandle handle =
1555 gfx::GLSurfaceHandle(gfx::kNullPluginWindow, gfx::NULL_TRANSPORT);
1556 if (using_browser_compositor_) {
1557 handle.parent_client_id =
1558 BrowserGpuChannelHostFactory::instance()->GetGpuChannelId();
1560 return handle;
1563 void RenderWidgetHostViewAndroid::ProcessAckedTouchEvent(
1564 const TouchEventWithLatencyInfo& touch, InputEventAckState ack_result) {
1565 const bool event_consumed = ack_result == INPUT_EVENT_ACK_STATE_CONSUMED;
1566 gesture_provider_.OnTouchEventAck(touch.event.uniqueTouchEventId,
1567 event_consumed);
1570 void RenderWidgetHostViewAndroid::GestureEventAck(
1571 const blink::WebGestureEvent& event,
1572 InputEventAckState ack_result) {
1573 if (overscroll_controller_)
1574 overscroll_controller_->OnGestureEventAck(event, ack_result);
1576 if (content_view_core_)
1577 content_view_core_->OnGestureEventAck(event, ack_result);
1580 InputEventAckState RenderWidgetHostViewAndroid::FilterInputEvent(
1581 const blink::WebInputEvent& input_event) {
1582 if (selection_controller_ &&
1583 blink::WebInputEvent::isGestureEventType(input_event.type)) {
1584 const blink::WebGestureEvent& gesture_event =
1585 static_cast<const blink::WebGestureEvent&>(input_event);
1586 switch (gesture_event.type) {
1587 case blink::WebInputEvent::GestureLongPress:
1588 if (selection_controller_->WillHandleLongPressEvent(
1589 base::TimeTicks() +
1590 base::TimeDelta::FromSecondsD(input_event.timeStampSeconds),
1591 gfx::PointF(gesture_event.x, gesture_event.y))) {
1592 return INPUT_EVENT_ACK_STATE_CONSUMED;
1594 break;
1596 case blink::WebInputEvent::GestureTap:
1597 if (selection_controller_->WillHandleTapEvent(
1598 gfx::PointF(gesture_event.x, gesture_event.y))) {
1599 return INPUT_EVENT_ACK_STATE_CONSUMED;
1601 break;
1603 default:
1604 break;
1608 if (overscroll_controller_ &&
1609 blink::WebInputEvent::isGestureEventType(input_event.type) &&
1610 overscroll_controller_->WillHandleGestureEvent(
1611 static_cast<const blink::WebGestureEvent&>(input_event))) {
1612 return INPUT_EVENT_ACK_STATE_CONSUMED;
1615 if (content_view_core_ && content_view_core_->FilterInputEvent(input_event))
1616 return INPUT_EVENT_ACK_STATE_CONSUMED;
1618 if (!host_)
1619 return INPUT_EVENT_ACK_STATE_NOT_CONSUMED;
1621 if (input_event.type == blink::WebInputEvent::GestureTapDown ||
1622 input_event.type == blink::WebInputEvent::TouchStart) {
1623 GpuDataManagerImpl* gpu_data = GpuDataManagerImpl::GetInstance();
1624 GpuProcessHostUIShim* shim = GpuProcessHostUIShim::GetOneInstance();
1625 if (shim && gpu_data && accelerated_surface_route_id_ &&
1626 gpu_data->IsDriverBugWorkaroundActive(gpu::WAKE_UP_GPU_BEFORE_DRAWING))
1627 shim->Send(
1628 new AcceleratedSurfaceMsg_WakeUpGpu(accelerated_surface_route_id_));
1631 SynchronousCompositorImpl* compositor =
1632 SynchronousCompositorImpl::FromID(host_->GetProcess()->GetID(),
1633 host_->GetRoutingID());
1634 if (compositor)
1635 return compositor->HandleInputEvent(input_event);
1636 return INPUT_EVENT_ACK_STATE_NOT_CONSUMED;
1639 void RenderWidgetHostViewAndroid::OnSetNeedsFlushInput() {
1640 TRACE_EVENT0("input", "RenderWidgetHostViewAndroid::OnSetNeedsFlushInput");
1641 RequestVSyncUpdate(FLUSH_INPUT);
1644 BrowserAccessibilityManager*
1645 RenderWidgetHostViewAndroid::CreateBrowserAccessibilityManager(
1646 BrowserAccessibilityDelegate* delegate) {
1647 // TODO(dmazzoni): Currently there can only be one
1648 // BrowserAccessibilityManager per ContentViewCore, so return NULL
1649 // if there's already a BrowserAccessibilityManager for the main
1650 // frame. Eventually, in order to support cross-process iframes on
1651 // Android we'll need to add support for a
1652 // BrowserAccessibilityManager for a child frame.
1653 // http://crbug.com/423846
1654 if (!host_ || host_->GetRootBrowserAccessibilityManager())
1655 return NULL;
1657 base::android::ScopedJavaLocalRef<jobject> obj;
1658 if (content_view_core_)
1659 obj = content_view_core_->GetJavaObject();
1660 return new BrowserAccessibilityManagerAndroid(
1661 obj,
1662 BrowserAccessibilityManagerAndroid::GetEmptyDocument(),
1663 delegate);
1666 bool RenderWidgetHostViewAndroid::LockMouse() {
1667 NOTIMPLEMENTED();
1668 return false;
1671 void RenderWidgetHostViewAndroid::UnlockMouse() {
1672 NOTIMPLEMENTED();
1675 // Methods called from the host to the render
1677 void RenderWidgetHostViewAndroid::SendKeyEvent(
1678 const NativeWebKeyboardEvent& event) {
1679 if (host_)
1680 host_->ForwardKeyboardEvent(event);
1683 void RenderWidgetHostViewAndroid::SendMouseEvent(
1684 const blink::WebMouseEvent& event) {
1685 if (host_)
1686 host_->ForwardMouseEvent(event);
1689 void RenderWidgetHostViewAndroid::SendMouseWheelEvent(
1690 const blink::WebMouseWheelEvent& event) {
1691 if (host_)
1692 host_->ForwardWheelEvent(event);
1695 void RenderWidgetHostViewAndroid::SendGestureEvent(
1696 const blink::WebGestureEvent& event) {
1697 // Sending a gesture that may trigger overscroll should resume the effect.
1698 if (overscroll_controller_)
1699 overscroll_controller_->Enable();
1701 if (host_)
1702 host_->ForwardGestureEventWithLatencyInfo(event, ui::LatencyInfo());
1705 void RenderWidgetHostViewAndroid::MoveCaret(const gfx::Point& point) {
1706 if (host_)
1707 host_->MoveCaret(point);
1710 void RenderWidgetHostViewAndroid::DismissTextHandles() {
1711 if (selection_controller_)
1712 selection_controller_->HideAndDisallowShowingAutomatically();
1715 void RenderWidgetHostViewAndroid::SetTextHandlesTemporarilyHidden(bool hidden) {
1716 if (selection_controller_)
1717 selection_controller_->SetTemporarilyHidden(hidden);
1720 void RenderWidgetHostViewAndroid::OnShowingPastePopup(
1721 const gfx::PointF& point) {
1722 if (!selection_controller_)
1723 return;
1725 // As the paste popup may be triggered *before* the bounds and editability
1726 // of the region have been updated, explicitly set the properties now.
1727 // TODO(jdduke): Remove this workaround when auxiliary paste popup
1728 // notifications are no longer required, crbug.com/398170.
1729 ui::SelectionBound insertion_bound;
1730 insertion_bound.set_type(ui::SelectionBound::CENTER);
1731 insertion_bound.set_visible(true);
1732 insertion_bound.SetEdge(point, point);
1733 selection_controller_->HideAndDisallowShowingAutomatically();
1734 selection_controller_->OnSelectionEditable(true);
1735 selection_controller_->OnSelectionEmpty(true);
1736 selection_controller_->OnSelectionBoundsChanged(insertion_bound,
1737 insertion_bound);
1738 selection_controller_->AllowShowingFromCurrentSelection();
1741 SkColor RenderWidgetHostViewAndroid::GetCachedBackgroundColor() const {
1742 return cached_background_color_;
1745 void RenderWidgetHostViewAndroid::DidOverscroll(
1746 const DidOverscrollParams& params) {
1747 if (!content_view_core_ || !layer_.get() || !is_showing_)
1748 return;
1750 if (overscroll_controller_)
1751 overscroll_controller_->OnOverscrolled(params);
1754 void RenderWidgetHostViewAndroid::DidStopFlinging() {
1755 if (content_view_core_)
1756 content_view_core_->DidStopFlinging();
1759 uint32_t RenderWidgetHostViewAndroid::GetSurfaceIdNamespace() {
1760 if (id_allocator_)
1761 return id_allocator_->id_namespace();
1762 return 0;
1765 void RenderWidgetHostViewAndroid::SetContentViewCore(
1766 ContentViewCoreImpl* content_view_core) {
1767 RemoveLayers();
1768 StopObservingRootWindow();
1770 bool resize = false;
1771 if (content_view_core != content_view_core_) {
1772 overscroll_controller_.reset();
1773 selection_controller_.reset();
1774 ReleaseLocksOnSurface();
1775 resize = true;
1778 content_view_core_ = content_view_core;
1779 content_view_core_window_android_ =
1780 content_view_core_ ? content_view_core_->GetWindowAndroid() : nullptr;
1781 DCHECK_EQ(!!content_view_core_, !!content_view_core_window_android_);
1783 BrowserAccessibilityManager* manager = NULL;
1784 if (host_)
1785 manager = host_->GetRootBrowserAccessibilityManager();
1786 if (manager) {
1787 base::android::ScopedJavaLocalRef<jobject> obj;
1788 if (content_view_core_)
1789 obj = content_view_core_->GetJavaObject();
1790 manager->ToBrowserAccessibilityManagerAndroid()->SetContentViewCore(obj);
1793 AttachLayers();
1795 if (!content_view_core_)
1796 return;
1798 if (is_showing_)
1799 StartObservingRootWindow();
1801 if (resize)
1802 WasResized();
1804 if (!selection_controller_)
1805 selection_controller_ = CreateSelectionController(this, content_view_core_);
1807 if (!overscroll_controller_ &&
1808 content_view_core_window_android_->GetCompositor()) {
1809 overscroll_controller_ = CreateOverscrollController(content_view_core_);
1813 void RenderWidgetHostViewAndroid::RunAckCallbacks(
1814 cc::SurfaceDrawStatus status) {
1815 while (!ack_callbacks_.empty()) {
1816 ack_callbacks_.front().Run();
1817 ack_callbacks_.pop();
1821 void RenderWidgetHostViewAndroid::OnGestureEvent(
1822 const ui::GestureEventData& gesture) {
1823 blink::WebGestureEvent web_gesture =
1824 ui::CreateWebGestureEventFromGestureEventData(gesture);
1825 // TODO(jdduke): Remove this workaround after Android fixes UiAutomator to
1826 // stop providing shift meta values to synthetic MotionEvents. This prevents
1827 // unintended shift+click interpretation of all accessibility clicks.
1828 // See crbug.com/443247.
1829 if (web_gesture.type == blink::WebInputEvent::GestureTap &&
1830 web_gesture.modifiers == blink::WebInputEvent::ShiftKey) {
1831 web_gesture.modifiers = 0;
1833 SendGestureEvent(web_gesture);
1836 void RenderWidgetHostViewAndroid::OnCompositingDidCommit() {
1837 RunAckCallbacks(cc::SurfaceDrawStatus::DRAWN);
1840 void RenderWidgetHostViewAndroid::OnRootWindowVisibilityChanged(bool visible) {
1841 DCHECK(is_showing_);
1842 if (visible) {
1843 ShowInternal();
1844 } else {
1845 bool hide_frontbuffer = true;
1846 bool stop_observing_root_window = false;
1847 HideInternal(hide_frontbuffer, stop_observing_root_window);
1851 void RenderWidgetHostViewAndroid::OnAttachCompositor() {
1852 DCHECK(content_view_core_);
1853 if (!overscroll_controller_)
1854 overscroll_controller_ = CreateOverscrollController(content_view_core_);
1857 void RenderWidgetHostViewAndroid::OnDetachCompositor() {
1858 DCHECK(content_view_core_);
1859 DCHECK(using_browser_compositor_);
1860 RunAckCallbacks(cc::SurfaceDrawStatus::DRAW_SKIPPED);
1861 overscroll_controller_.reset();
1864 void RenderWidgetHostViewAndroid::OnVSync(base::TimeTicks frame_time,
1865 base::TimeDelta vsync_period) {
1866 TRACE_EVENT0("cc,benchmark", "RenderWidgetHostViewAndroid::OnVSync");
1867 if (!host_ || host_->is_hidden())
1868 return;
1870 if (outstanding_vsync_requests_ & FLUSH_INPUT) {
1871 outstanding_vsync_requests_ &= ~FLUSH_INPUT;
1872 host_->FlushInput();
1875 if (outstanding_vsync_requests_ & BEGIN_FRAME ||
1876 outstanding_vsync_requests_ & PERSISTENT_BEGIN_FRAME) {
1877 outstanding_vsync_requests_ &= ~BEGIN_FRAME;
1878 SendBeginFrame(frame_time, vsync_period);
1881 // This allows for SendBeginFrame and FlushInput to modify
1882 // outstanding_vsync_requests.
1883 uint32 outstanding_vsync_requests = outstanding_vsync_requests_;
1884 outstanding_vsync_requests_ = 0;
1885 RequestVSyncUpdate(outstanding_vsync_requests);
1888 void RenderWidgetHostViewAndroid::OnAnimate(base::TimeTicks begin_frame_time) {
1889 if (Animate(begin_frame_time))
1890 SetNeedsAnimate();
1893 void RenderWidgetHostViewAndroid::OnActivityStopped() {
1894 TRACE_EVENT0("browser", "RenderWidgetHostViewAndroid::OnActivityStopped");
1895 DCHECK(is_showing_);
1896 bool hide_frontbuffer = false;
1897 bool stop_observing_root_window = false;
1898 HideInternal(hide_frontbuffer, stop_observing_root_window);
1901 void RenderWidgetHostViewAndroid::OnActivityStarted() {
1902 TRACE_EVENT0("browser", "RenderWidgetHostViewAndroid::OnActivityStarted");
1903 DCHECK(is_showing_);
1904 ShowInternal();
1907 void RenderWidgetHostViewAndroid::OnLostResources() {
1908 ReleaseLocksOnSurface();
1909 if (layer_.get())
1910 DestroyDelegatedContent();
1911 DCHECK(ack_callbacks_.empty());
1914 // static
1915 void RenderWidgetHostViewAndroid::
1916 PrepareTextureCopyOutputResultForDelegatedReadback(
1917 const gfx::Size& dst_size_in_pixel,
1918 SkColorType color_type,
1919 const base::TimeTicks& start_time,
1920 scoped_refptr<cc::Layer> readback_layer,
1921 ReadbackRequestCallback& callback,
1922 scoped_ptr<cc::CopyOutputResult> result) {
1923 readback_layer->RemoveFromParent();
1924 PrepareTextureCopyOutputResult(
1925 dst_size_in_pixel, color_type, start_time, callback, result.Pass());
1928 // static
1929 void RenderWidgetHostViewAndroid::PrepareTextureCopyOutputResult(
1930 const gfx::Size& dst_size_in_pixel,
1931 SkColorType color_type,
1932 const base::TimeTicks& start_time,
1933 ReadbackRequestCallback& callback,
1934 scoped_ptr<cc::CopyOutputResult> result) {
1935 base::ScopedClosureRunner scoped_callback_runner(
1936 base::Bind(callback, SkBitmap(), READBACK_FAILED));
1937 TRACE_EVENT0("cc",
1938 "RenderWidgetHostViewAndroid::PrepareTextureCopyOutputResult");
1940 if (!result->HasTexture() || result->IsEmpty() || result->size().IsEmpty())
1941 return;
1943 gfx::Size output_size_in_pixel;
1944 if (dst_size_in_pixel.IsEmpty())
1945 output_size_in_pixel = result->size();
1946 else
1947 output_size_in_pixel = dst_size_in_pixel;
1949 GLHelper* gl_helper = GetPostReadbackGLHelper();
1950 if (!gl_helper)
1951 return;
1952 if (!gl_helper->IsReadbackConfigSupported(color_type))
1953 color_type = kRGBA_8888_SkColorType;
1954 scoped_ptr<SkBitmap> bitmap(new SkBitmap);
1955 if (!bitmap->tryAllocPixels(SkImageInfo::Make(output_size_in_pixel.width(),
1956 output_size_in_pixel.height(),
1957 color_type,
1958 kOpaque_SkAlphaType))) {
1959 scoped_callback_runner.Reset(
1960 base::Bind(callback, SkBitmap(), READBACK_BITMAP_ALLOCATION_FAILURE));
1961 return;
1965 scoped_ptr<SkAutoLockPixels> bitmap_pixels_lock(
1966 new SkAutoLockPixels(*bitmap));
1967 uint8* pixels = static_cast<uint8*>(bitmap->getPixels());
1969 cc::TextureMailbox texture_mailbox;
1970 scoped_ptr<cc::SingleReleaseCallback> release_callback;
1971 result->TakeTexture(&texture_mailbox, &release_callback);
1972 DCHECK(texture_mailbox.IsTexture());
1973 if (!texture_mailbox.IsTexture())
1974 return;
1976 ignore_result(scoped_callback_runner.Release());
1978 gl_helper->CropScaleReadbackAndCleanMailbox(
1979 texture_mailbox.mailbox(),
1980 texture_mailbox.sync_point(),
1981 result->size(),
1982 gfx::Rect(result->size()),
1983 output_size_in_pixel,
1984 pixels,
1985 color_type,
1986 base::Bind(&CopyFromCompositingSurfaceFinished,
1987 callback,
1988 base::Passed(&release_callback),
1989 base::Passed(&bitmap),
1990 start_time,
1991 base::Passed(&bitmap_pixels_lock)),
1992 GLHelper::SCALER_QUALITY_GOOD);
1995 void RenderWidgetHostViewAndroid::OnStylusSelectBegin(float x0,
1996 float y0,
1997 float x1,
1998 float y1) {
1999 SelectBetweenCoordinates(gfx::PointF(x0, y0), gfx::PointF(x1, y1));
2002 void RenderWidgetHostViewAndroid::OnStylusSelectUpdate(float x, float y) {
2003 MoveRangeSelectionExtent(gfx::PointF(x, y));
2006 void RenderWidgetHostViewAndroid::OnStylusSelectEnd() {
2007 if (selection_controller_)
2008 selection_controller_->AllowShowingFromCurrentSelection();
2011 void RenderWidgetHostViewAndroid::OnStylusSelectTap(base::TimeTicks time,
2012 float x,
2013 float y) {
2014 // Treat the stylus tap as a long press, activating either a word selection or
2015 // context menu depending on the targetted content.
2016 blink::WebGestureEvent long_press = WebGestureEventBuilder::Build(
2017 blink::WebInputEvent::GestureLongPress,
2018 (time - base::TimeTicks()).InSecondsF(), x, y);
2019 SendGestureEvent(long_press);
2022 // static
2023 void RenderWidgetHostViewBase::GetDefaultScreenInfo(
2024 blink::WebScreenInfo* results) {
2025 const gfx::Display& display =
2026 gfx::Screen::GetNativeScreen()->GetPrimaryDisplay();
2027 results->rect = display.bounds();
2028 // TODO(husky): Remove any system controls from availableRect.
2029 results->availableRect = display.work_area();
2030 results->deviceScaleFactor = display.device_scale_factor();
2031 results->orientationAngle = display.RotationAsDegree();
2032 results->orientationType =
2033 RenderWidgetHostViewBase::GetOrientationTypeForMobile(display);
2034 gfx::DeviceDisplayInfo info;
2035 results->depth = info.GetBitsPerPixel();
2036 results->depthPerComponent = info.GetBitsPerComponent();
2037 results->isMonochrome = (results->depthPerComponent == 0);
2040 } // namespace content