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_impl.h"
11 #include "base/auto_reset.h"
12 #include "base/bind.h"
13 #include "base/command_line.h"
14 #include "base/containers/hash_tables.h"
15 #include "base/debug/trace_event.h"
16 #include "base/i18n/rtl.h"
17 #include "base/lazy_instance.h"
18 #include "base/message_loop/message_loop.h"
19 #include "base/metrics/field_trial.h"
20 #include "base/metrics/histogram.h"
21 #include "base/strings/string_number_conversions.h"
22 #include "base/strings/utf_string_conversions.h"
23 #include "base/thread_task_runner_handle.h"
24 #include "cc/base/switches.h"
25 #include "cc/output/compositor_frame.h"
26 #include "cc/output/compositor_frame_ack.h"
27 #include "content/browser/accessibility/accessibility_mode_helper.h"
28 #include "content/browser/accessibility/browser_accessibility_state_impl.h"
29 #include "content/browser/browser_plugin/browser_plugin_guest.h"
30 #include "content/browser/gpu/compositor_util.h"
31 #include "content/browser/gpu/gpu_process_host.h"
32 #include "content/browser/gpu/gpu_process_host_ui_shim.h"
33 #include "content/browser/gpu/gpu_surface_tracker.h"
34 #include "content/browser/renderer_host/dip_util.h"
35 #include "content/browser/renderer_host/input/input_router_config_helper.h"
36 #include "content/browser/renderer_host/input/input_router_impl.h"
37 #include "content/browser/renderer_host/input/synthetic_gesture.h"
38 #include "content/browser/renderer_host/input/synthetic_gesture_controller.h"
39 #include "content/browser/renderer_host/input/synthetic_gesture_target.h"
40 #include "content/browser/renderer_host/input/timeout_monitor.h"
41 #include "content/browser/renderer_host/input/touch_emulator.h"
42 #include "content/browser/renderer_host/render_process_host_impl.h"
43 #include "content/browser/renderer_host/render_view_host_impl.h"
44 #include "content/browser/renderer_host/render_widget_helper.h"
45 #include "content/browser/renderer_host/render_widget_host_delegate.h"
46 #include "content/browser/renderer_host/render_widget_host_view_base.h"
47 #include "content/browser/renderer_host/render_widget_resize_helper.h"
48 #include "content/common/content_constants_internal.h"
49 #include "content/common/cursors/webcursor.h"
50 #include "content/common/gpu/gpu_messages.h"
51 #include "content/common/host_shared_bitmap_manager.h"
52 #include "content/common/input_messages.h"
53 #include "content/common/view_messages.h"
54 #include "content/public/browser/native_web_keyboard_event.h"
55 #include "content/public/browser/notification_service.h"
56 #include "content/public/browser/notification_types.h"
57 #include "content/public/browser/render_widget_host_iterator.h"
58 #include "content/public/browser/user_metrics.h"
59 #include "content/public/common/content_constants.h"
60 #include "content/public/common/content_switches.h"
61 #include "content/public/common/result_codes.h"
62 #include "content/public/common/web_preferences.h"
63 #include "skia/ext/image_operations.h"
64 #include "skia/ext/platform_canvas.h"
65 #include "third_party/WebKit/public/web/WebCompositionUnderline.h"
66 #include "ui/events/event.h"
67 #include "ui/events/keycodes/keyboard_codes.h"
68 #include "ui/gfx/size_conversions.h"
69 #include "ui/gfx/skbitmap_operations.h"
70 #include "ui/gfx/vector2d_conversions.h"
71 #include "ui/snapshot/snapshot.h"
74 #include "content/common/plugin_constants_win.h"
78 using base::TimeDelta;
79 using base::TimeTicks;
80 using blink::WebGestureEvent;
81 using blink::WebInputEvent;
82 using blink::WebKeyboardEvent;
83 using blink::WebMouseEvent;
84 using blink::WebMouseWheelEvent;
85 using blink::WebTextDirection;
90 bool g_check_for_pending_resize_ack = true;
92 typedef std::pair<int32, int32> RenderWidgetHostID;
93 typedef base::hash_map<RenderWidgetHostID, RenderWidgetHostImpl*>
95 base::LazyInstance<RoutingIDWidgetMap> g_routing_id_widget_map =
96 LAZY_INSTANCE_INITIALIZER;
98 int GetInputRouterViewFlagsFromCompositorFrameMetadata(
99 const cc::CompositorFrameMetadata metadata) {
100 int view_flags = InputRouter::VIEW_FLAGS_NONE;
102 if (metadata.min_page_scale_factor == metadata.max_page_scale_factor)
103 view_flags |= InputRouter::FIXED_PAGE_SCALE;
105 const float window_width_dip = std::ceil(
106 metadata.page_scale_factor * metadata.scrollable_viewport_size.width());
107 const float content_width_css = metadata.root_layer_size.width();
108 if (content_width_css <= window_width_dip)
109 view_flags |= InputRouter::MOBILE_VIEWPORT;
114 // Implements the RenderWidgetHostIterator interface. It keeps a list of
115 // RenderWidgetHosts, and makes sure it returns a live RenderWidgetHost at each
116 // iteration (or NULL if there isn't any left).
117 class RenderWidgetHostIteratorImpl : public RenderWidgetHostIterator {
119 RenderWidgetHostIteratorImpl()
120 : current_index_(0) {
123 virtual ~RenderWidgetHostIteratorImpl() {
126 void Add(RenderWidgetHost* host) {
127 hosts_.push_back(RenderWidgetHostID(host->GetProcess()->GetID(),
128 host->GetRoutingID()));
131 // RenderWidgetHostIterator:
132 virtual RenderWidgetHost* GetNextHost() OVERRIDE {
133 RenderWidgetHost* host = NULL;
134 while (current_index_ < hosts_.size() && !host) {
135 RenderWidgetHostID id = hosts_[current_index_];
136 host = RenderWidgetHost::FromID(id.first, id.second);
143 std::vector<RenderWidgetHostID> hosts_;
144 size_t current_index_;
146 DISALLOW_COPY_AND_ASSIGN(RenderWidgetHostIteratorImpl);
151 ///////////////////////////////////////////////////////////////////////////////
152 // RenderWidgetHostImpl
154 RenderWidgetHostImpl::RenderWidgetHostImpl(RenderWidgetHostDelegate* delegate,
155 RenderProcessHost* process,
159 renderer_initialized_(false),
160 hung_renderer_delay_ms_(kHungRendererDelayMs),
163 routing_id_(routing_id),
167 is_fullscreen_(false),
168 repaint_ack_pending_(false),
169 resize_ack_pending_(false),
170 screen_info_out_of_date_(false),
171 overdraw_bottom_height_(0.f),
172 should_auto_resize_(false),
173 waiting_for_screen_rects_ack_(false),
174 needs_repainting_on_restore_(false),
175 is_unresponsive_(false),
176 in_flight_event_count_(0),
177 in_get_backing_store_(false),
178 ignore_input_events_(false),
179 input_method_active_(false),
180 text_direction_updated_(false),
181 text_direction_(blink::WebTextDirectionLeftToRight),
182 text_direction_canceled_(false),
183 suppress_next_char_events_(false),
184 pending_mouse_lock_request_(false),
185 allow_privileged_mouse_lock_(false),
186 has_touch_handler_(false),
188 last_input_number_(static_cast<int64>(GetProcess()->GetID()) << 32),
189 next_browser_snapshot_id_(1) {
191 if (routing_id_ == MSG_ROUTING_NONE) {
192 routing_id_ = process_->GetNextRoutingID();
193 surface_id_ = GpuSurfaceTracker::Get()->AddSurfaceForRenderer(
197 // TODO(piman): This is a O(N) lookup, where we could forward the
198 // information from the RenderWidgetHelper. The problem is that doing so
199 // currently leaks outside of content all the way to chrome classes, and
200 // would be a layering violation. Since we don't expect more than a few
201 // hundreds of RWH, this seems acceptable. Revisit if performance become a
202 // problem, for example by tracking in the RenderWidgetHelper the routing id
203 // (and surface id) that have been created, but whose RWH haven't yet.
204 surface_id_ = GpuSurfaceTracker::Get()->LookupSurfaceForRenderer(
210 std::pair<RoutingIDWidgetMap::iterator, bool> result =
211 g_routing_id_widget_map.Get().insert(std::make_pair(
212 RenderWidgetHostID(process->GetID(), routing_id_), this));
213 CHECK(result.second) << "Inserting a duplicate item!";
214 process_->AddRoute(routing_id_, this);
216 // If we're initially visible, tell the process host that we're alive.
217 // Otherwise we'll notify the process host when we are first shown.
219 process_->WidgetRestored();
221 input_router_.reset(new InputRouterImpl(
222 process_, this, this, routing_id_, GetInputRouterConfigForPlatform()));
224 touch_emulator_.reset();
226 RenderViewHostImpl* rvh = static_cast<RenderViewHostImpl*>(
227 IsRenderView() ? RenderViewHost::From(this) : NULL);
228 if (BrowserPluginGuest::IsGuest(rvh) ||
229 !base::CommandLine::ForCurrentProcess()->HasSwitch(
230 switches::kDisableHangMonitor)) {
231 hang_monitor_timeout_.reset(new TimeoutMonitor(
232 base::Bind(&RenderWidgetHostImpl::RendererIsUnresponsive,
233 weak_factory_.GetWeakPtr())));
237 RenderWidgetHostImpl::~RenderWidgetHostImpl() {
240 GpuSurfaceTracker::Get()->RemoveSurface(surface_id_);
243 process_->RemoveRoute(routing_id_);
244 g_routing_id_widget_map.Get().erase(
245 RenderWidgetHostID(process_->GetID(), routing_id_));
248 delegate_->RenderWidgetDeleted(this);
252 RenderWidgetHost* RenderWidgetHost::FromID(
255 return RenderWidgetHostImpl::FromID(process_id, routing_id);
259 RenderWidgetHostImpl* RenderWidgetHostImpl::FromID(
262 DCHECK_CURRENTLY_ON(BrowserThread::UI);
263 RoutingIDWidgetMap* widgets = g_routing_id_widget_map.Pointer();
264 RoutingIDWidgetMap::iterator it = widgets->find(
265 RenderWidgetHostID(process_id, routing_id));
266 return it == widgets->end() ? NULL : it->second;
270 scoped_ptr<RenderWidgetHostIterator> RenderWidgetHost::GetRenderWidgetHosts() {
271 RenderWidgetHostIteratorImpl* hosts = new RenderWidgetHostIteratorImpl();
272 RoutingIDWidgetMap* widgets = g_routing_id_widget_map.Pointer();
273 for (RoutingIDWidgetMap::const_iterator it = widgets->begin();
274 it != widgets->end();
276 RenderWidgetHost* widget = it->second;
278 if (!widget->IsRenderView()) {
283 // Add only active RenderViewHosts.
284 RenderViewHost* rvh = RenderViewHost::From(widget);
285 if (RenderViewHostImpl::IsRVHStateActive(
286 static_cast<RenderViewHostImpl*>(rvh)->rvh_state()))
290 return scoped_ptr<RenderWidgetHostIterator>(hosts);
294 scoped_ptr<RenderWidgetHostIterator>
295 RenderWidgetHostImpl::GetAllRenderWidgetHosts() {
296 RenderWidgetHostIteratorImpl* hosts = new RenderWidgetHostIteratorImpl();
297 RoutingIDWidgetMap* widgets = g_routing_id_widget_map.Pointer();
298 for (RoutingIDWidgetMap::const_iterator it = widgets->begin();
299 it != widgets->end();
301 hosts->Add(it->second);
304 return scoped_ptr<RenderWidgetHostIterator>(hosts);
308 RenderWidgetHostImpl* RenderWidgetHostImpl::From(RenderWidgetHost* rwh) {
309 return rwh->AsRenderWidgetHostImpl();
312 void RenderWidgetHostImpl::SetView(RenderWidgetHostViewBase* view) {
315 GpuSurfaceTracker::Get()->SetSurfaceHandle(
316 surface_id_, GetCompositingSurface());
318 synthetic_gesture_controller_.reset();
321 RenderProcessHost* RenderWidgetHostImpl::GetProcess() const {
325 int RenderWidgetHostImpl::GetRoutingID() const {
329 RenderWidgetHostView* RenderWidgetHostImpl::GetView() const {
333 RenderWidgetHostImpl* RenderWidgetHostImpl::AsRenderWidgetHostImpl() {
337 gfx::NativeViewId RenderWidgetHostImpl::GetNativeViewId() const {
339 return view_->GetNativeViewId();
343 gfx::GLSurfaceHandle RenderWidgetHostImpl::GetCompositingSurface() {
345 return view_->GetCompositingSurface();
346 return gfx::GLSurfaceHandle();
349 void RenderWidgetHostImpl::ResetSizeAndRepaintPendingFlags() {
350 resize_ack_pending_ = false;
351 if (repaint_ack_pending_) {
352 TRACE_EVENT_ASYNC_END0(
353 "renderer_host", "RenderWidgetHostImpl::repaint_ack_pending_", this);
355 repaint_ack_pending_ = false;
356 last_requested_size_.SetSize(0, 0);
359 void RenderWidgetHostImpl::SendScreenRects() {
360 if (!renderer_initialized_ || waiting_for_screen_rects_ack_)
364 // On GTK, this comes in for backgrounded tabs. Ignore, to match what
365 // happens on Win & Mac, and when the view is shown it'll call this again.
372 last_view_screen_rect_ = view_->GetViewBounds();
373 last_window_screen_rect_ = view_->GetBoundsInRootWindow();
374 Send(new ViewMsg_UpdateScreenRects(
375 GetRoutingID(), last_view_screen_rect_, last_window_screen_rect_));
377 delegate_->DidSendScreenRects(this);
378 waiting_for_screen_rects_ack_ = true;
381 void RenderWidgetHostImpl::SuppressNextCharEvents() {
382 suppress_next_char_events_ = true;
385 void RenderWidgetHostImpl::FlushInput() {
386 input_router_->Flush();
387 if (synthetic_gesture_controller_)
388 synthetic_gesture_controller_->Flush(base::TimeTicks::Now());
391 void RenderWidgetHostImpl::SetNeedsFlush() {
393 view_->OnSetNeedsFlushInput();
396 void RenderWidgetHostImpl::Init() {
397 DCHECK(process_->HasConnection());
399 renderer_initialized_ = true;
401 GpuSurfaceTracker::Get()->SetSurfaceHandle(
402 surface_id_, GetCompositingSurface());
404 // Send the ack along with the information on placement.
405 Send(new ViewMsg_CreatingNew_ACK(routing_id_));
406 GetProcess()->ResumeRequestsForView(routing_id_);
411 void RenderWidgetHostImpl::Shutdown() {
412 RejectMouseLockOrUnlockIfNecessary();
414 if (process_->HasConnection()) {
415 // Tell the renderer object to close.
416 bool rv = Send(new ViewMsg_Close(routing_id_));
423 bool RenderWidgetHostImpl::IsLoading() const {
427 bool RenderWidgetHostImpl::IsRenderView() const {
431 bool RenderWidgetHostImpl::OnMessageReceived(const IPC::Message &msg) {
433 IPC_BEGIN_MESSAGE_MAP(RenderWidgetHostImpl, msg)
434 IPC_MESSAGE_HANDLER(InputHostMsg_QueueSyntheticGesture,
435 OnQueueSyntheticGesture)
436 IPC_MESSAGE_HANDLER(InputHostMsg_ImeCancelComposition,
437 OnImeCancelComposition)
438 IPC_MESSAGE_HANDLER(ViewHostMsg_RenderViewReady, OnRenderViewReady)
439 IPC_MESSAGE_HANDLER(ViewHostMsg_RenderProcessGone, OnRenderProcessGone)
440 IPC_MESSAGE_HANDLER(ViewHostMsg_Close, OnClose)
441 IPC_MESSAGE_HANDLER(ViewHostMsg_UpdateScreenRects_ACK,
442 OnUpdateScreenRectsAck)
443 IPC_MESSAGE_HANDLER(ViewHostMsg_RequestMove, OnRequestMove)
444 IPC_MESSAGE_HANDLER(ViewHostMsg_SetTooltipText, OnSetTooltipText)
445 IPC_MESSAGE_HANDLER_GENERIC(ViewHostMsg_SwapCompositorFrame,
446 OnSwapCompositorFrame(msg))
447 IPC_MESSAGE_HANDLER(ViewHostMsg_DidStopFlinging, OnFlingingStopped)
448 IPC_MESSAGE_HANDLER(ViewHostMsg_UpdateRect, OnUpdateRect)
449 IPC_MESSAGE_HANDLER(ViewHostMsg_Focus, OnFocus)
450 IPC_MESSAGE_HANDLER(ViewHostMsg_Blur, OnBlur)
451 IPC_MESSAGE_HANDLER(ViewHostMsg_SetCursor, OnSetCursor)
452 IPC_MESSAGE_HANDLER(ViewHostMsg_SetTouchEventEmulationEnabled,
453 OnSetTouchEventEmulationEnabled)
454 IPC_MESSAGE_HANDLER(ViewHostMsg_TextInputStateChanged,
455 OnTextInputStateChanged)
456 IPC_MESSAGE_HANDLER(ViewHostMsg_LockMouse, OnLockMouse)
457 IPC_MESSAGE_HANDLER(ViewHostMsg_UnlockMouse, OnUnlockMouse)
458 IPC_MESSAGE_HANDLER(ViewHostMsg_ShowDisambiguationPopup,
459 OnShowDisambiguationPopup)
460 IPC_MESSAGE_HANDLER(ViewHostMsg_SelectionChanged, OnSelectionChanged)
461 IPC_MESSAGE_HANDLER(ViewHostMsg_SelectionBoundsChanged,
462 OnSelectionBoundsChanged)
464 IPC_MESSAGE_HANDLER(ViewHostMsg_WindowlessPluginDummyWindowCreated,
465 OnWindowlessPluginDummyWindowCreated)
466 IPC_MESSAGE_HANDLER(ViewHostMsg_WindowlessPluginDummyWindowDestroyed,
467 OnWindowlessPluginDummyWindowDestroyed)
469 #if defined(OS_MACOSX) || defined(USE_AURA)
470 IPC_MESSAGE_HANDLER(InputHostMsg_ImeCompositionRangeChanged,
471 OnImeCompositionRangeChanged)
473 IPC_MESSAGE_UNHANDLED(handled = false)
474 IPC_END_MESSAGE_MAP()
476 if (!handled && input_router_ && input_router_->OnMessageReceived(msg))
479 if (!handled && view_ && view_->OnMessageReceived(msg))
485 bool RenderWidgetHostImpl::Send(IPC::Message* msg) {
486 if (IPC_MESSAGE_ID_CLASS(msg->type()) == InputMsgStart)
487 return input_router_->SendInput(make_scoped_ptr(msg));
489 return process_->Send(msg);
492 void RenderWidgetHostImpl::WasHidden() {
498 // Don't bother reporting hung state when we aren't active.
499 StopHangMonitorTimeout();
501 // If we have a renderer, then inform it that we are being hidden so it can
502 // reduce its resource utilization.
503 Send(new ViewMsg_WasHidden(routing_id_));
505 // Tell the RenderProcessHost we were hidden.
506 process_->WidgetHidden();
508 bool is_visible = false;
509 NotificationService::current()->Notify(
510 NOTIFICATION_RENDER_WIDGET_VISIBILITY_CHANGED,
511 Source<RenderWidgetHost>(this),
512 Details<bool>(&is_visible));
515 void RenderWidgetHostImpl::WasShown(const ui::LatencyInfo& latency_info) {
522 // Always repaint on restore.
523 bool needs_repainting = true;
524 needs_repainting_on_restore_ = false;
525 Send(new ViewMsg_WasShown(routing_id_, needs_repainting, latency_info));
527 process_->WidgetRestored();
529 bool is_visible = true;
530 NotificationService::current()->Notify(
531 NOTIFICATION_RENDER_WIDGET_VISIBILITY_CHANGED,
532 Source<RenderWidgetHost>(this),
533 Details<bool>(&is_visible));
535 // It's possible for our size to be out of sync with the renderer. The
536 // following is one case that leads to this:
537 // 1. WasResized -> Send ViewMsg_Resize to render
538 // 2. WasResized -> do nothing as resize_ack_pending_ is true
540 // 4. OnUpdateRect from (1) processed. Does NOT invoke WasResized as view
541 // is hidden. Now renderer/browser out of sync with what they think size
543 // By invoking WasResized the renderer is updated as necessary. WasResized
544 // does nothing if the sizes are already in sync.
546 // TODO: ideally ViewMsg_WasShown would take a size. This way, the renderer
547 // could handle both the restore and resize at once. This isn't that big a
548 // deal as RenderWidget::WasShown delays updating, so that the resize from
549 // WasResized is usually processed before the renderer is painted.
553 void RenderWidgetHostImpl::WasResized() {
554 // Skip if the |delegate_| has already been detached because
555 // it's web contents is being deleted.
556 if (resize_ack_pending_ || !process_->HasConnection() || !view_ ||
557 !renderer_initialized_ || should_auto_resize_ || !delegate_) {
561 gfx::Size new_size(view_->GetRequestedRendererSize());
563 gfx::Size old_physical_backing_size = physical_backing_size_;
564 physical_backing_size_ = view_->GetPhysicalBackingSize();
565 bool was_fullscreen = is_fullscreen_;
566 is_fullscreen_ = IsFullscreen();
567 float old_overdraw_bottom_height = overdraw_bottom_height_;
568 overdraw_bottom_height_ = view_->GetOverdrawBottomHeight();
569 gfx::Size old_visible_viewport_size = visible_viewport_size_;
570 visible_viewport_size_ = view_->GetVisibleViewportSize();
572 bool size_changed = new_size != last_requested_size_;
573 bool side_payload_changed =
574 screen_info_out_of_date_ ||
575 old_physical_backing_size != physical_backing_size_ ||
576 was_fullscreen != is_fullscreen_ ||
577 old_overdraw_bottom_height != overdraw_bottom_height_ ||
578 old_visible_viewport_size != visible_viewport_size_;
580 if (!size_changed && !side_payload_changed)
584 screen_info_.reset(new blink::WebScreenInfo);
585 GetWebScreenInfo(screen_info_.get());
588 // We don't expect to receive an ACK when the requested size or the physical
589 // backing size is empty, or when the main viewport size didn't change.
590 if (!new_size.IsEmpty() && !physical_backing_size_.IsEmpty() && size_changed)
591 resize_ack_pending_ = g_check_for_pending_resize_ack;
593 ViewMsg_Resize_Params params;
594 params.screen_info = *screen_info_;
595 params.new_size = new_size;
596 params.physical_backing_size = physical_backing_size_;
597 params.overdraw_bottom_height = overdraw_bottom_height_;
598 params.visible_viewport_size = visible_viewport_size_;
599 params.resizer_rect = GetRootWindowResizerRect();
600 params.is_fullscreen = is_fullscreen_;
601 if (!Send(new ViewMsg_Resize(routing_id_, params))) {
602 resize_ack_pending_ = false;
604 last_requested_size_ = new_size;
608 void RenderWidgetHostImpl::ResizeRectChanged(const gfx::Rect& new_rect) {
609 Send(new ViewMsg_ChangeResizeRect(routing_id_, new_rect));
612 void RenderWidgetHostImpl::GotFocus() {
616 void RenderWidgetHostImpl::Focus() {
617 Send(new InputMsg_SetFocus(routing_id_, true));
620 void RenderWidgetHostImpl::Blur() {
621 // If there is a pending mouse lock request, we don't want to reject it at
622 // this point. The user can switch focus back to this view and approve the
625 view_->UnlockMouse();
628 touch_emulator_->CancelTouch();
630 Send(new InputMsg_SetFocus(routing_id_, false));
633 void RenderWidgetHostImpl::LostCapture() {
635 touch_emulator_->CancelTouch();
637 Send(new InputMsg_MouseCaptureLost(routing_id_));
640 void RenderWidgetHostImpl::SetActive(bool active) {
641 Send(new ViewMsg_SetActive(routing_id_, active));
644 void RenderWidgetHostImpl::LostMouseLock() {
645 Send(new ViewMsg_MouseLockLost(routing_id_));
648 void RenderWidgetHostImpl::ViewDestroyed() {
649 RejectMouseLockOrUnlockIfNecessary();
651 // TODO(evanm): tracking this may no longer be necessary;
652 // eliminate this function if so.
656 void RenderWidgetHostImpl::SetIsLoading(bool is_loading) {
657 is_loading_ = is_loading;
660 view_->SetIsLoading(is_loading);
663 void RenderWidgetHostImpl::CopyFromBackingStore(
664 const gfx::Rect& src_subrect,
665 const gfx::Size& accelerated_dst_size,
666 const base::Callback<void(bool, const SkBitmap&)>& callback,
667 const SkColorType color_type) {
669 TRACE_EVENT0("browser",
670 "RenderWidgetHostImpl::CopyFromBackingStore::FromCompositingSurface");
671 gfx::Rect accelerated_copy_rect = src_subrect.IsEmpty() ?
672 gfx::Rect(view_->GetViewBounds().size()) : src_subrect;
673 view_->CopyFromCompositingSurface(
674 accelerated_copy_rect, accelerated_dst_size, callback, color_type);
678 callback.Run(false, SkBitmap());
681 bool RenderWidgetHostImpl::CanCopyFromBackingStore() {
683 return view_->IsSurfaceAvailableForCopy();
687 #if defined(OS_ANDROID)
688 void RenderWidgetHostImpl::LockBackingStore() {
690 view_->LockCompositingSurface();
693 void RenderWidgetHostImpl::UnlockBackingStore() {
695 view_->UnlockCompositingSurface();
699 #if defined(OS_MACOSX)
700 void RenderWidgetHostImpl::PauseForPendingResizeOrRepaints() {
701 TRACE_EVENT0("browser",
702 "RenderWidgetHostImpl::PauseForPendingResizeOrRepaints");
704 if (!CanPauseForPendingResizeOrRepaints())
710 bool RenderWidgetHostImpl::CanPauseForPendingResizeOrRepaints() {
711 // Do not pause if the view is hidden.
715 // Do not pause if there is not a paint or resize already coming.
716 if (!repaint_ack_pending_ && !resize_ack_pending_)
722 void RenderWidgetHostImpl::WaitForSurface() {
723 TRACE_EVENT0("browser", "RenderWidgetHostImpl::WaitForSurface");
725 // How long to (synchronously) wait for the renderer to respond with a
726 // new frame when our current frame doesn't exist or is the wrong size.
727 // This timeout impacts the "choppiness" of our window resize.
728 const int kPaintMsgTimeoutMS = 50;
733 // The view_size will be current_size_ for auto-sized views and otherwise the
734 // size of the view_. (For auto-sized views, current_size_ is updated during
735 // UpdateRect messages.)
736 gfx::Size view_size = current_size_;
737 if (!should_auto_resize_) {
738 // Get the desired size from the current view bounds.
739 gfx::Rect view_rect = view_->GetViewBounds();
740 if (view_rect.IsEmpty())
742 view_size = view_rect.size();
745 TRACE_EVENT2("renderer_host",
746 "RenderWidgetHostImpl::WaitForBackingStore",
748 base::IntToString(view_size.width()),
750 base::IntToString(view_size.height()));
752 // We should not be asked to paint while we are hidden. If we are hidden,
753 // then it means that our consumer failed to call WasShown. If we're not
754 // force creating the backing store, it's OK since we can feel free to give
755 // out our cached one if we have it.
756 DCHECK(!is_hidden_) << "WaitForSurface called while hidden!";
758 // We should never be called recursively; this can theoretically lead to
759 // infinite recursion and almost certainly leads to lower performance.
760 DCHECK(!in_get_backing_store_) << "WaitForSurface called recursively!";
761 base::AutoReset<bool> auto_reset_in_get_backing_store(
762 &in_get_backing_store_, true);
764 // We might have a surface that we can use!
765 if (view_->HasAcceleratedSurface(view_size))
768 // We do not have a suitable backing store in the cache, so send out a
769 // request to the renderer to paint the view if required.
770 if (!repaint_ack_pending_ && !resize_ack_pending_) {
771 repaint_start_time_ = TimeTicks::Now();
772 repaint_ack_pending_ = true;
773 TRACE_EVENT_ASYNC_BEGIN0(
774 "renderer_host", "RenderWidgetHostImpl::repaint_ack_pending_", this);
775 Send(new ViewMsg_Repaint(routing_id_, view_size));
778 TimeDelta max_delay = TimeDelta::FromMilliseconds(kPaintMsgTimeoutMS);
779 TimeTicks end_time = TimeTicks::Now() + max_delay;
781 TRACE_EVENT0("renderer_host", "WaitForSurface::WaitForUpdate");
783 // When we have asked the RenderWidget to resize, and we are still waiting
784 // on a response, block for a little while to see if we can't get a response
785 // before returning the old (incorrectly sized) backing store.
787 if (RenderWidgetResizeHelper::Get()->WaitForSingleTaskToRun(max_delay)) {
789 // For auto-resized views, current_size_ determines the view_size and it
790 // may have changed during the handling of an UpdateRect message.
791 if (should_auto_resize_)
792 view_size = current_size_;
794 // Break now if we got a backing store or accelerated surface of the
796 if (view_->HasAcceleratedSurface(view_size))
799 TRACE_EVENT0("renderer_host", "WaitForSurface::Timeout");
803 // Loop if we still have time left and haven't gotten a properly sized
804 // BackingStore yet. This is necessary to support the GPU path which
805 // typically has multiple frames pipelined -- we may need to skip one or two
806 // BackingStore messages to get to the latest.
807 max_delay = end_time - TimeTicks::Now();
808 } while (max_delay > TimeDelta::FromSeconds(0));
812 bool RenderWidgetHostImpl::ScheduleComposite() {
813 if (is_hidden_ || current_size_.IsEmpty() || repaint_ack_pending_ ||
814 resize_ack_pending_) {
818 // Send out a request to the renderer to paint the view if required.
819 repaint_start_time_ = TimeTicks::Now();
820 repaint_ack_pending_ = true;
821 TRACE_EVENT_ASYNC_BEGIN0(
822 "renderer_host", "RenderWidgetHostImpl::repaint_ack_pending_", this);
823 Send(new ViewMsg_Repaint(routing_id_, current_size_));
827 void RenderWidgetHostImpl::StartHangMonitorTimeout(base::TimeDelta delay) {
828 if (hang_monitor_timeout_)
829 hang_monitor_timeout_->Start(delay);
832 void RenderWidgetHostImpl::RestartHangMonitorTimeout() {
833 if (hang_monitor_timeout_)
834 hang_monitor_timeout_->Restart(
835 base::TimeDelta::FromMilliseconds(hung_renderer_delay_ms_));
838 void RenderWidgetHostImpl::StopHangMonitorTimeout() {
839 if (hang_monitor_timeout_)
840 hang_monitor_timeout_->Stop();
841 RendererIsResponsive();
844 void RenderWidgetHostImpl::ForwardMouseEvent(const WebMouseEvent& mouse_event) {
845 ForwardMouseEventWithLatencyInfo(mouse_event, ui::LatencyInfo());
848 void RenderWidgetHostImpl::ForwardMouseEventWithLatencyInfo(
849 const blink::WebMouseEvent& mouse_event,
850 const ui::LatencyInfo& ui_latency) {
851 TRACE_EVENT2("input", "RenderWidgetHostImpl::ForwardMouseEvent",
852 "x", mouse_event.x, "y", mouse_event.y);
854 ui::LatencyInfo latency_info =
855 CreateRWHLatencyInfoIfNotExist(&ui_latency, mouse_event.type);
857 for (size_t i = 0; i < mouse_event_callbacks_.size(); ++i) {
858 if (mouse_event_callbacks_[i].Run(mouse_event))
862 if (IgnoreInputEvents())
865 if (touch_emulator_ && touch_emulator_->HandleMouseEvent(mouse_event))
868 input_router_->SendMouseEvent(MouseEventWithLatencyInfo(mouse_event,
872 void RenderWidgetHostImpl::OnPointerEventActivate() {
875 void RenderWidgetHostImpl::ForwardWheelEvent(
876 const WebMouseWheelEvent& wheel_event) {
877 ForwardWheelEventWithLatencyInfo(wheel_event, ui::LatencyInfo());
880 void RenderWidgetHostImpl::ForwardWheelEventWithLatencyInfo(
881 const blink::WebMouseWheelEvent& wheel_event,
882 const ui::LatencyInfo& ui_latency) {
883 TRACE_EVENT0("input", "RenderWidgetHostImpl::ForwardWheelEvent");
885 ui::LatencyInfo latency_info =
886 CreateRWHLatencyInfoIfNotExist(&ui_latency, wheel_event.type);
888 if (IgnoreInputEvents())
891 if (touch_emulator_ && touch_emulator_->HandleMouseWheelEvent(wheel_event))
894 input_router_->SendWheelEvent(MouseWheelEventWithLatencyInfo(wheel_event,
898 void RenderWidgetHostImpl::ForwardGestureEvent(
899 const blink::WebGestureEvent& gesture_event) {
900 ForwardGestureEventWithLatencyInfo(gesture_event, ui::LatencyInfo());
903 void RenderWidgetHostImpl::ForwardGestureEventWithLatencyInfo(
904 const blink::WebGestureEvent& gesture_event,
905 const ui::LatencyInfo& ui_latency) {
906 TRACE_EVENT0("input", "RenderWidgetHostImpl::ForwardGestureEvent");
907 // Early out if necessary, prior to performing latency logic.
908 if (IgnoreInputEvents())
911 if (delegate_->PreHandleGestureEvent(gesture_event))
914 ui::LatencyInfo latency_info =
915 CreateRWHLatencyInfoIfNotExist(&ui_latency, gesture_event.type);
917 if (gesture_event.type == blink::WebInputEvent::GestureScrollUpdate) {
918 latency_info.AddLatencyNumber(
919 ui::INPUT_EVENT_LATENCY_SCROLL_UPDATE_RWH_COMPONENT,
920 GetLatencyComponentId(),
921 ++last_input_number_);
923 // Make a copy of the INPUT_EVENT_LATENCY_ORIGINAL_COMPONENT with a
924 // different name INPUT_EVENT_LATENCY_SCROLL_UPDATE_ORIGINAL_COMPONENT.
925 // So we can track the latency specifically for scroll update events.
926 ui::LatencyInfo::LatencyComponent original_component;
927 if (latency_info.FindLatency(ui::INPUT_EVENT_LATENCY_ORIGINAL_COMPONENT,
929 &original_component)) {
930 latency_info.AddLatencyNumberWithTimestamp(
931 ui::INPUT_EVENT_LATENCY_SCROLL_UPDATE_ORIGINAL_COMPONENT,
932 GetLatencyComponentId(),
933 original_component.sequence_number,
934 original_component.event_time,
935 original_component.event_count);
939 GestureEventWithLatencyInfo gesture_with_latency(gesture_event, latency_info);
940 input_router_->SendGestureEvent(gesture_with_latency);
943 void RenderWidgetHostImpl::ForwardEmulatedTouchEvent(
944 const blink::WebTouchEvent& touch_event) {
945 TRACE_EVENT0("input", "RenderWidgetHostImpl::ForwardEmulatedTouchEvent");
946 ui::LatencyInfo latency_info =
947 CreateRWHLatencyInfoIfNotExist(NULL, touch_event.type);
948 TouchEventWithLatencyInfo touch_with_latency(touch_event, latency_info);
949 input_router_->SendTouchEvent(touch_with_latency);
952 void RenderWidgetHostImpl::ForwardTouchEventWithLatencyInfo(
953 const blink::WebTouchEvent& touch_event,
954 const ui::LatencyInfo& ui_latency) {
955 TRACE_EVENT0("input", "RenderWidgetHostImpl::ForwardTouchEvent");
957 // Always forward TouchEvents for touch stream consistency. They will be
958 // ignored if appropriate in FilterInputEvent().
960 ui::LatencyInfo latency_info =
961 CreateRWHLatencyInfoIfNotExist(&ui_latency, touch_event.type);
962 TouchEventWithLatencyInfo touch_with_latency(touch_event, latency_info);
964 if (touch_emulator_ &&
965 touch_emulator_->HandleTouchEvent(touch_with_latency.event)) {
967 view_->ProcessAckedTouchEvent(
968 touch_with_latency, INPUT_EVENT_ACK_STATE_CONSUMED);
973 input_router_->SendTouchEvent(touch_with_latency);
976 void RenderWidgetHostImpl::ForwardKeyboardEvent(
977 const NativeWebKeyboardEvent& key_event) {
978 TRACE_EVENT0("input", "RenderWidgetHostImpl::ForwardKeyboardEvent");
979 if (IgnoreInputEvents())
982 if (!process_->HasConnection())
985 // First, let keypress listeners take a shot at handling the event. If a
986 // listener handles the event, it should not be propagated to the renderer.
987 if (KeyPressListenersHandleEvent(key_event)) {
988 // Some keypresses that are accepted by the listener might have follow up
989 // char events, which should be ignored.
990 if (key_event.type == WebKeyboardEvent::RawKeyDown)
991 suppress_next_char_events_ = true;
995 if (key_event.type == WebKeyboardEvent::Char &&
996 (key_event.windowsKeyCode == ui::VKEY_RETURN ||
997 key_event.windowsKeyCode == ui::VKEY_SPACE)) {
1001 // Double check the type to make sure caller hasn't sent us nonsense that
1002 // will mess up our key queue.
1003 if (!WebInputEvent::isKeyboardEventType(key_event.type))
1006 if (suppress_next_char_events_) {
1007 // If preceding RawKeyDown event was handled by the browser, then we need
1008 // suppress all Char events generated by it. Please note that, one
1009 // RawKeyDown event may generate multiple Char events, so we can't reset
1010 // |suppress_next_char_events_| until we get a KeyUp or a RawKeyDown.
1011 if (key_event.type == WebKeyboardEvent::Char)
1013 // We get a KeyUp or a RawKeyDown event.
1014 suppress_next_char_events_ = false;
1017 bool is_shortcut = false;
1019 // Only pre-handle the key event if it's not handled by the input method.
1020 if (delegate_ && !key_event.skip_in_browser) {
1021 // We need to set |suppress_next_char_events_| to true if
1022 // PreHandleKeyboardEvent() returns true, but |this| may already be
1023 // destroyed at that time. So set |suppress_next_char_events_| true here,
1024 // then revert it afterwards when necessary.
1025 if (key_event.type == WebKeyboardEvent::RawKeyDown)
1026 suppress_next_char_events_ = true;
1028 // Tab switching/closing accelerators aren't sent to the renderer to avoid
1029 // a hung/malicious renderer from interfering.
1030 if (delegate_->PreHandleKeyboardEvent(key_event, &is_shortcut))
1033 if (key_event.type == WebKeyboardEvent::RawKeyDown)
1034 suppress_next_char_events_ = false;
1037 if (touch_emulator_ && touch_emulator_->HandleKeyboardEvent(key_event))
1040 input_router_->SendKeyboardEvent(
1042 CreateRWHLatencyInfoIfNotExist(NULL, key_event.type),
1046 void RenderWidgetHostImpl::QueueSyntheticGesture(
1047 scoped_ptr<SyntheticGesture> synthetic_gesture,
1048 const base::Callback<void(SyntheticGesture::Result)>& on_complete) {
1049 if (!synthetic_gesture_controller_ && view_) {
1050 synthetic_gesture_controller_.reset(
1051 new SyntheticGestureController(
1052 view_->CreateSyntheticGestureTarget().Pass()));
1054 if (synthetic_gesture_controller_) {
1055 synthetic_gesture_controller_->QueueSyntheticGesture(
1056 synthetic_gesture.Pass(), on_complete);
1060 void RenderWidgetHostImpl::SetCursor(const WebCursor& cursor) {
1063 view_->UpdateCursor(cursor);
1066 void RenderWidgetHostImpl::ShowContextMenuAtPoint(const gfx::Point& point) {
1067 Send(new ViewMsg_ShowContextMenu(
1068 GetRoutingID(), ui::MENU_SOURCE_MOUSE, point));
1071 void RenderWidgetHostImpl::SendCursorVisibilityState(bool is_visible) {
1072 Send(new InputMsg_CursorVisibilityChange(GetRoutingID(), is_visible));
1075 int64 RenderWidgetHostImpl::GetLatencyComponentId() {
1076 return GetRoutingID() | (static_cast<int64>(GetProcess()->GetID()) << 32);
1080 void RenderWidgetHostImpl::DisableResizeAckCheckForTesting() {
1081 g_check_for_pending_resize_ack = false;
1084 ui::LatencyInfo RenderWidgetHostImpl::CreateRWHLatencyInfoIfNotExist(
1085 const ui::LatencyInfo* original, WebInputEvent::Type type) {
1086 ui::LatencyInfo info;
1089 // In Aura, gesture event will already carry its original touch event's
1090 // INPUT_EVENT_LATENCY_RWH_COMPONENT.
1091 if (!info.FindLatency(ui::INPUT_EVENT_LATENCY_BEGIN_RWH_COMPONENT,
1092 GetLatencyComponentId(),
1094 info.AddLatencyNumber(ui::INPUT_EVENT_LATENCY_BEGIN_RWH_COMPONENT,
1095 GetLatencyComponentId(),
1096 ++last_input_number_);
1097 info.TraceEventType(WebInputEventTraits::GetName(type));
1103 void RenderWidgetHostImpl::AddKeyPressEventCallback(
1104 const KeyPressEventCallback& callback) {
1105 key_press_event_callbacks_.push_back(callback);
1108 void RenderWidgetHostImpl::RemoveKeyPressEventCallback(
1109 const KeyPressEventCallback& callback) {
1110 for (size_t i = 0; i < key_press_event_callbacks_.size(); ++i) {
1111 if (key_press_event_callbacks_[i].Equals(callback)) {
1112 key_press_event_callbacks_.erase(
1113 key_press_event_callbacks_.begin() + i);
1119 void RenderWidgetHostImpl::AddMouseEventCallback(
1120 const MouseEventCallback& callback) {
1121 mouse_event_callbacks_.push_back(callback);
1124 void RenderWidgetHostImpl::RemoveMouseEventCallback(
1125 const MouseEventCallback& callback) {
1126 for (size_t i = 0; i < mouse_event_callbacks_.size(); ++i) {
1127 if (mouse_event_callbacks_[i].Equals(callback)) {
1128 mouse_event_callbacks_.erase(mouse_event_callbacks_.begin() + i);
1134 void RenderWidgetHostImpl::GetWebScreenInfo(blink::WebScreenInfo* result) {
1135 TRACE_EVENT0("renderer_host", "RenderWidgetHostImpl::GetWebScreenInfo");
1137 view_->GetScreenInfo(result);
1139 RenderWidgetHostViewBase::GetDefaultScreenInfo(result);
1140 screen_info_out_of_date_ = false;
1143 const NativeWebKeyboardEvent*
1144 RenderWidgetHostImpl::GetLastKeyboardEvent() const {
1145 return input_router_->GetLastKeyboardEvent();
1148 void RenderWidgetHostImpl::NotifyScreenInfoChanged() {
1149 // The resize message (which may not happen immediately) will carry with it
1150 // the screen info as well as the new size (if the screen has changed scale
1152 InvalidateScreenInfo();
1156 void RenderWidgetHostImpl::InvalidateScreenInfo() {
1157 screen_info_out_of_date_ = true;
1158 screen_info_.reset();
1161 void RenderWidgetHostImpl::GetSnapshotFromBrowser(
1162 const base::Callback<void(const unsigned char*,size_t)> callback) {
1163 int id = next_browser_snapshot_id_++;
1164 pending_browser_snapshots_.insert(std::make_pair(id, callback));
1165 Send(new ViewMsg_ForceRedraw(GetRoutingID(), id));
1168 void RenderWidgetHostImpl::OnSelectionChanged(const base::string16& text,
1170 const gfx::Range& range) {
1172 view_->SelectionChanged(text, offset, range);
1175 void RenderWidgetHostImpl::OnSelectionBoundsChanged(
1176 const ViewHostMsg_SelectionBounds_Params& params) {
1178 view_->SelectionBoundsChanged(params);
1182 void RenderWidgetHostImpl::UpdateVSyncParameters(base::TimeTicks timebase,
1183 base::TimeDelta interval) {
1184 Send(new ViewMsg_UpdateVSyncParameters(GetRoutingID(), timebase, interval));
1187 void RenderWidgetHostImpl::RendererExited(base::TerminationStatus status,
1189 // Clearing this flag causes us to re-create the renderer when recovering
1190 // from a crashed renderer.
1191 renderer_initialized_ = false;
1193 waiting_for_screen_rects_ack_ = false;
1195 // Must reset these to ensure that keyboard events work with a new renderer.
1196 suppress_next_char_events_ = false;
1198 // Reset some fields in preparation for recovering from a crash.
1199 ResetSizeAndRepaintPendingFlags();
1200 current_size_.SetSize(0, 0);
1201 // After the renderer crashes, the view is destroyed and so the
1202 // RenderWidgetHost cannot track its visibility anymore. We assume such
1203 // RenderWidgetHost to be visible for the sake of internal accounting - be
1204 // careful about changing this - see http://crbug.com/401859.
1206 // We need to at least make sure that the RenderProcessHost is notified about
1207 // the |is_hidden_| change, so that the renderer will have correct visibility
1208 // set when respawned.
1210 process_->WidgetRestored();
1214 // Reset this to ensure the hung renderer mechanism is working properly.
1215 in_flight_event_count_ = 0;
1218 GpuSurfaceTracker::Get()->SetSurfaceHandle(surface_id_,
1219 gfx::GLSurfaceHandle());
1220 view_->RenderProcessGone(status, exit_code);
1221 view_ = NULL; // The View should be deleted by RenderProcessGone.
1224 // Reconstruct the input router to ensure that it has fresh state for a new
1225 // renderer. Otherwise it may be stuck waiting for the old renderer to ack an
1226 // event. (In particular, the above call to view_->RenderProcessGone will
1227 // destroy the aura window, which may dispatch a synthetic mouse move.)
1228 input_router_.reset(new InputRouterImpl(
1229 process_, this, this, routing_id_, GetInputRouterConfigForPlatform()));
1231 synthetic_gesture_controller_.reset();
1234 void RenderWidgetHostImpl::UpdateTextDirection(WebTextDirection direction) {
1235 text_direction_updated_ = true;
1236 text_direction_ = direction;
1239 void RenderWidgetHostImpl::CancelUpdateTextDirection() {
1240 if (text_direction_updated_)
1241 text_direction_canceled_ = true;
1244 void RenderWidgetHostImpl::NotifyTextDirection() {
1245 if (text_direction_updated_) {
1246 if (!text_direction_canceled_)
1247 Send(new ViewMsg_SetTextDirection(GetRoutingID(), text_direction_));
1248 text_direction_updated_ = false;
1249 text_direction_canceled_ = false;
1253 void RenderWidgetHostImpl::SetInputMethodActive(bool activate) {
1254 input_method_active_ = activate;
1255 Send(new ViewMsg_SetInputMethodActive(GetRoutingID(), activate));
1258 void RenderWidgetHostImpl::CandidateWindowShown() {
1259 Send(new ViewMsg_CandidateWindowShown(GetRoutingID()));
1262 void RenderWidgetHostImpl::CandidateWindowUpdated() {
1263 Send(new ViewMsg_CandidateWindowUpdated(GetRoutingID()));
1266 void RenderWidgetHostImpl::CandidateWindowHidden() {
1267 Send(new ViewMsg_CandidateWindowHidden(GetRoutingID()));
1270 void RenderWidgetHostImpl::ImeSetComposition(
1271 const base::string16& text,
1272 const std::vector<blink::WebCompositionUnderline>& underlines,
1273 int selection_start,
1274 int selection_end) {
1275 Send(new InputMsg_ImeSetComposition(
1276 GetRoutingID(), text, underlines, selection_start, selection_end));
1279 void RenderWidgetHostImpl::ImeConfirmComposition(
1280 const base::string16& text,
1281 const gfx::Range& replacement_range,
1282 bool keep_selection) {
1283 Send(new InputMsg_ImeConfirmComposition(
1284 GetRoutingID(), text, replacement_range, keep_selection));
1287 void RenderWidgetHostImpl::ImeCancelComposition() {
1288 Send(new InputMsg_ImeSetComposition(GetRoutingID(), base::string16(),
1289 std::vector<blink::WebCompositionUnderline>(), 0, 0));
1292 gfx::Rect RenderWidgetHostImpl::GetRootWindowResizerRect() const {
1296 void RenderWidgetHostImpl::RequestToLockMouse(bool user_gesture,
1297 bool last_unlocked_by_target) {
1298 // Directly reject to lock the mouse. Subclass can override this method to
1299 // decide whether to allow mouse lock or not.
1300 GotResponseToLockMouseRequest(false);
1303 void RenderWidgetHostImpl::RejectMouseLockOrUnlockIfNecessary() {
1304 DCHECK(!pending_mouse_lock_request_ || !IsMouseLocked());
1305 if (pending_mouse_lock_request_) {
1306 pending_mouse_lock_request_ = false;
1307 Send(new ViewMsg_LockMouse_ACK(routing_id_, false));
1308 } else if (IsMouseLocked()) {
1309 view_->UnlockMouse();
1313 bool RenderWidgetHostImpl::IsMouseLocked() const {
1314 return view_ ? view_->IsMouseLocked() : false;
1317 bool RenderWidgetHostImpl::IsFullscreen() const {
1321 void RenderWidgetHostImpl::SetShouldAutoResize(bool enable) {
1322 should_auto_resize_ = enable;
1325 void RenderWidgetHostImpl::Destroy() {
1326 NotificationService::current()->Notify(
1327 NOTIFICATION_RENDER_WIDGET_HOST_DESTROYED,
1328 Source<RenderWidgetHost>(this),
1329 NotificationService::NoDetails());
1331 // Tell the view to die.
1332 // Note that in the process of the view shutting down, it can call a ton
1333 // of other messages on us. So if you do any other deinitialization here,
1334 // do it after this call to view_->Destroy().
1341 void RenderWidgetHostImpl::RendererIsUnresponsive() {
1342 NotificationService::current()->Notify(
1343 NOTIFICATION_RENDER_WIDGET_HOST_HANG,
1344 Source<RenderWidgetHost>(this),
1345 NotificationService::NoDetails());
1346 is_unresponsive_ = true;
1347 NotifyRendererUnresponsive();
1350 void RenderWidgetHostImpl::RendererIsResponsive() {
1351 if (is_unresponsive_) {
1352 is_unresponsive_ = false;
1353 NotifyRendererResponsive();
1357 void RenderWidgetHostImpl::OnRenderViewReady() {
1362 void RenderWidgetHostImpl::OnRenderProcessGone(int status, int exit_code) {
1363 // TODO(evanm): This synchronously ends up calling "delete this".
1364 // Is that really what we want in response to this message? I'm matching
1365 // previous behavior of the code here.
1369 void RenderWidgetHostImpl::OnClose() {
1373 void RenderWidgetHostImpl::OnSetTooltipText(
1374 const base::string16& tooltip_text,
1375 WebTextDirection text_direction_hint) {
1376 // First, add directionality marks around tooltip text if necessary.
1377 // A naive solution would be to simply always wrap the text. However, on
1378 // windows, Unicode directional embedding characters can't be displayed on
1379 // systems that lack RTL fonts and are instead displayed as empty squares.
1381 // To get around this we only wrap the string when we deem it necessary i.e.
1382 // when the locale direction is different than the tooltip direction hint.
1384 // Currently, we use element's directionality as the tooltip direction hint.
1385 // An alternate solution would be to set the overall directionality based on
1386 // trying to detect the directionality from the tooltip text rather than the
1387 // element direction. One could argue that would be a preferable solution
1388 // but we use the current approach to match Fx & IE's behavior.
1389 base::string16 wrapped_tooltip_text = tooltip_text;
1390 if (!tooltip_text.empty()) {
1391 if (text_direction_hint == blink::WebTextDirectionLeftToRight) {
1392 // Force the tooltip to have LTR directionality.
1393 wrapped_tooltip_text =
1394 base::i18n::GetDisplayStringInLTRDirectionality(wrapped_tooltip_text);
1395 } else if (text_direction_hint == blink::WebTextDirectionRightToLeft &&
1396 !base::i18n::IsRTL()) {
1397 // Force the tooltip to have RTL directionality.
1398 base::i18n::WrapStringWithRTLFormatting(&wrapped_tooltip_text);
1402 view_->SetTooltipText(wrapped_tooltip_text);
1405 void RenderWidgetHostImpl::OnUpdateScreenRectsAck() {
1406 waiting_for_screen_rects_ack_ = false;
1410 if (view_->GetViewBounds() == last_view_screen_rect_ &&
1411 view_->GetBoundsInRootWindow() == last_window_screen_rect_) {
1418 void RenderWidgetHostImpl::OnRequestMove(const gfx::Rect& pos) {
1420 view_->SetBounds(pos);
1421 Send(new ViewMsg_Move_ACK(routing_id_));
1425 bool RenderWidgetHostImpl::OnSwapCompositorFrame(
1426 const IPC::Message& message) {
1427 // This trace event is used in
1428 // chrome/browser/extensions/api/cast_streaming/performance_test.cc
1429 UNSHIPPED_TRACE_EVENT0("test_fps",
1430 TRACE_DISABLED_BY_DEFAULT("OnSwapCompositorFrame"));
1431 ViewHostMsg_SwapCompositorFrame::Param param;
1432 if (!ViewHostMsg_SwapCompositorFrame::Read(&message, ¶m))
1434 scoped_ptr<cc::CompositorFrame> frame(new cc::CompositorFrame);
1435 uint32 output_surface_id = param.a;
1436 param.b.AssignTo(frame.get());
1437 std::vector<IPC::Message> messages_to_deliver_with_frame;
1438 messages_to_deliver_with_frame.swap(param.c);
1440 for (size_t i = 0; i < frame->metadata.latency_info.size(); i++)
1441 AddLatencyInfoComponentIds(&frame->metadata.latency_info[i]);
1443 input_router_->OnViewUpdated(
1444 GetInputRouterViewFlagsFromCompositorFrameMetadata(frame->metadata));
1447 view_->OnSwapCompositorFrame(output_surface_id, frame.Pass());
1448 view_->DidReceiveRendererFrame();
1450 cc::CompositorFrameAck ack;
1451 if (frame->gl_frame_data) {
1452 ack.gl_frame_data = frame->gl_frame_data.Pass();
1453 ack.gl_frame_data->sync_point = 0;
1454 } else if (frame->delegated_frame_data) {
1455 cc::TransferableResource::ReturnResources(
1456 frame->delegated_frame_data->resource_list,
1458 } else if (frame->software_frame_data) {
1459 ack.last_software_frame_id = frame->software_frame_data->id;
1461 SendSwapCompositorFrameAck(routing_id_, output_surface_id,
1462 process_->GetID(), ack);
1465 RenderProcessHost* rph = GetProcess();
1466 for (std::vector<IPC::Message>::const_iterator i =
1467 messages_to_deliver_with_frame.begin();
1468 i != messages_to_deliver_with_frame.end();
1470 rph->OnMessageReceived(*i);
1471 if (i->dispatch_error())
1472 rph->OnBadMessageReceived(*i);
1474 messages_to_deliver_with_frame.clear();
1479 void RenderWidgetHostImpl::OnFlingingStopped() {
1481 view_->DidStopFlinging();
1484 void RenderWidgetHostImpl::OnUpdateRect(
1485 const ViewHostMsg_UpdateRect_Params& params) {
1486 TRACE_EVENT0("renderer_host", "RenderWidgetHostImpl::OnUpdateRect");
1487 TimeTicks paint_start = TimeTicks::Now();
1489 // Update our knowledge of the RenderWidget's size.
1490 current_size_ = params.view_size;
1491 // Update our knowledge of the RenderWidget's scroll offset.
1492 last_scroll_offset_ = params.scroll_offset;
1494 bool is_resize_ack =
1495 ViewHostMsg_UpdateRect_Flags::is_resize_ack(params.flags);
1497 // resize_ack_pending_ needs to be cleared before we call DidPaintRect, since
1498 // that will end up reaching GetBackingStore.
1499 if (is_resize_ack) {
1500 DCHECK(!g_check_for_pending_resize_ack || resize_ack_pending_);
1501 resize_ack_pending_ = false;
1504 bool is_repaint_ack =
1505 ViewHostMsg_UpdateRect_Flags::is_repaint_ack(params.flags);
1506 if (is_repaint_ack) {
1507 DCHECK(repaint_ack_pending_);
1508 TRACE_EVENT_ASYNC_END0(
1509 "renderer_host", "RenderWidgetHostImpl::repaint_ack_pending_", this);
1510 repaint_ack_pending_ = false;
1511 TimeDelta delta = TimeTicks::Now() - repaint_start_time_;
1512 UMA_HISTOGRAM_TIMES("MPArch.RWH_RepaintDelta", delta);
1515 DCHECK(!params.view_size.IsEmpty());
1517 DidUpdateBackingStore(params, paint_start);
1519 if (should_auto_resize_) {
1520 bool post_callback = new_auto_size_.IsEmpty();
1521 new_auto_size_ = params.view_size;
1522 if (post_callback) {
1523 base::MessageLoop::current()->PostTask(
1525 base::Bind(&RenderWidgetHostImpl::DelayedAutoResized,
1526 weak_factory_.GetWeakPtr()));
1530 // Log the time delta for processing a paint message. On platforms that don't
1531 // support asynchronous painting, this is equivalent to
1532 // MPArch.RWH_TotalPaintTime.
1533 TimeDelta delta = TimeTicks::Now() - paint_start;
1534 UMA_HISTOGRAM_TIMES("MPArch.RWH_OnMsgUpdateRect", delta);
1537 void RenderWidgetHostImpl::DidUpdateBackingStore(
1538 const ViewHostMsg_UpdateRect_Params& params,
1539 const TimeTicks& paint_start) {
1540 TRACE_EVENT0("renderer_host", "RenderWidgetHostImpl::DidUpdateBackingStore");
1541 TimeTicks update_start = TimeTicks::Now();
1543 // Move the plugins if the view hasn't already been destroyed. Plugin moves
1544 // will not be re-issued, so must move them now, regardless of whether we
1545 // paint or not. MovePluginWindows attempts to move the plugin windows and
1546 // in the process could dispatch other window messages which could cause the
1547 // view to be destroyed.
1549 view_->MovePluginWindows(params.plugin_window_moves);
1551 NotificationService::current()->Notify(
1552 NOTIFICATION_RENDER_WIDGET_HOST_DID_UPDATE_BACKING_STORE,
1553 Source<RenderWidgetHost>(this),
1554 NotificationService::NoDetails());
1556 // We don't need to update the view if the view is hidden. We must do this
1557 // early return after the ACK is sent, however, or the renderer will not send
1562 // If we got a resize ack, then perhaps we have another resize to send?
1563 bool is_resize_ack =
1564 ViewHostMsg_UpdateRect_Flags::is_resize_ack(params.flags);
1568 // Log the time delta for processing a paint message.
1569 TimeTicks now = TimeTicks::Now();
1570 TimeDelta delta = now - update_start;
1571 UMA_HISTOGRAM_TIMES("MPArch.RWH_DidUpdateBackingStore", delta);
1574 void RenderWidgetHostImpl::OnQueueSyntheticGesture(
1575 const SyntheticGesturePacket& gesture_packet) {
1576 // Only allow untrustworthy gestures if explicitly enabled.
1577 if (!base::CommandLine::ForCurrentProcess()->HasSwitch(
1578 cc::switches::kEnableGpuBenchmarking)) {
1579 RecordAction(base::UserMetricsAction("BadMessageTerminate_RWH7"));
1580 GetProcess()->ReceivedBadMessage();
1584 QueueSyntheticGesture(
1585 SyntheticGesture::Create(*gesture_packet.gesture_params()),
1586 base::Bind(&RenderWidgetHostImpl::OnSyntheticGestureCompleted,
1587 weak_factory_.GetWeakPtr()));
1590 void RenderWidgetHostImpl::OnFocus() {
1591 // Only RenderViewHost can deal with that message.
1592 RecordAction(base::UserMetricsAction("BadMessageTerminate_RWH4"));
1593 GetProcess()->ReceivedBadMessage();
1596 void RenderWidgetHostImpl::OnBlur() {
1597 // Only RenderViewHost can deal with that message.
1598 RecordAction(base::UserMetricsAction("BadMessageTerminate_RWH5"));
1599 GetProcess()->ReceivedBadMessage();
1602 void RenderWidgetHostImpl::OnSetCursor(const WebCursor& cursor) {
1606 void RenderWidgetHostImpl::OnSetTouchEventEmulationEnabled(
1607 bool enabled, bool allow_pinch) {
1608 SetTouchEventEmulationEnabled(enabled, allow_pinch);
1611 void RenderWidgetHostImpl::SetTouchEventEmulationEnabled(
1612 bool enabled, bool allow_pinch) {
1614 delegate_->OnTouchEmulationEnabled(enabled);
1617 if (!touch_emulator_)
1618 touch_emulator_.reset(new TouchEmulator(this));
1619 touch_emulator_->Enable(allow_pinch);
1621 if (touch_emulator_)
1622 touch_emulator_->Disable();
1626 void RenderWidgetHostImpl::OnTextInputStateChanged(
1627 const ViewHostMsg_TextInputState_Params& params) {
1629 view_->TextInputStateChanged(params);
1632 #if defined(OS_MACOSX) || defined(USE_AURA)
1633 void RenderWidgetHostImpl::OnImeCompositionRangeChanged(
1634 const gfx::Range& range,
1635 const std::vector<gfx::Rect>& character_bounds) {
1637 view_->ImeCompositionRangeChanged(range, character_bounds);
1641 void RenderWidgetHostImpl::OnImeCancelComposition() {
1643 view_->ImeCancelComposition();
1646 void RenderWidgetHostImpl::OnLockMouse(bool user_gesture,
1647 bool last_unlocked_by_target,
1650 if (pending_mouse_lock_request_) {
1651 Send(new ViewMsg_LockMouse_ACK(routing_id_, false));
1653 } else if (IsMouseLocked()) {
1654 Send(new ViewMsg_LockMouse_ACK(routing_id_, true));
1658 pending_mouse_lock_request_ = true;
1659 if (privileged && allow_privileged_mouse_lock_) {
1660 // Directly approve to lock the mouse.
1661 GotResponseToLockMouseRequest(true);
1663 RequestToLockMouse(user_gesture, last_unlocked_by_target);
1667 void RenderWidgetHostImpl::OnUnlockMouse() {
1668 RejectMouseLockOrUnlockIfNecessary();
1671 void RenderWidgetHostImpl::OnShowDisambiguationPopup(
1672 const gfx::Rect& rect,
1673 const gfx::Size& size,
1674 const cc::SharedBitmapId& id) {
1675 DCHECK(!rect.IsEmpty());
1676 DCHECK(!size.IsEmpty());
1678 scoped_ptr<cc::SharedBitmap> bitmap =
1679 HostSharedBitmapManager::current()->GetSharedBitmapFromId(size, id);
1681 RecordAction(base::UserMetricsAction("BadMessageTerminate_RWH6"));
1682 GetProcess()->ReceivedBadMessage();
1686 DCHECK(bitmap->pixels());
1688 SkImageInfo info = SkImageInfo::MakeN32Premul(size.width(), size.height());
1689 SkBitmap zoomed_bitmap;
1690 zoomed_bitmap.installPixels(info, bitmap->pixels(), info.minRowBytes());
1692 #if defined(OS_ANDROID)
1694 view_->ShowDisambiguationPopup(rect, zoomed_bitmap);
1699 zoomed_bitmap.setPixels(0);
1700 Send(new ViewMsg_ReleaseDisambiguationPopupBitmap(GetRoutingID(), id));
1704 void RenderWidgetHostImpl::OnWindowlessPluginDummyWindowCreated(
1705 gfx::NativeViewId dummy_activation_window) {
1706 HWND hwnd = reinterpret_cast<HWND>(dummy_activation_window);
1708 // This may happen as a result of a race condition when the plugin is going
1710 wchar_t window_title[MAX_PATH + 1] = {0};
1711 if (!IsWindow(hwnd) ||
1712 !GetWindowText(hwnd, window_title, arraysize(window_title)) ||
1713 lstrcmpiW(window_title, kDummyActivationWindowName) != 0) {
1717 #if defined(USE_AURA)
1719 reinterpret_cast<HWND>(view_->GetParentForWindowlessPlugin()));
1721 SetParent(hwnd, reinterpret_cast<HWND>(GetNativeViewId()));
1723 dummy_windows_for_activation_.push_back(hwnd);
1726 void RenderWidgetHostImpl::OnWindowlessPluginDummyWindowDestroyed(
1727 gfx::NativeViewId dummy_activation_window) {
1728 HWND hwnd = reinterpret_cast<HWND>(dummy_activation_window);
1729 std::list<HWND>::iterator i = dummy_windows_for_activation_.begin();
1730 for (; i != dummy_windows_for_activation_.end(); ++i) {
1732 dummy_windows_for_activation_.erase(i);
1736 NOTREACHED() << "Unknown dummy window";
1740 void RenderWidgetHostImpl::SetIgnoreInputEvents(bool ignore_input_events) {
1741 ignore_input_events_ = ignore_input_events;
1744 bool RenderWidgetHostImpl::KeyPressListenersHandleEvent(
1745 const NativeWebKeyboardEvent& event) {
1746 if (event.skip_in_browser || event.type != WebKeyboardEvent::RawKeyDown)
1749 for (size_t i = 0; i < key_press_event_callbacks_.size(); i++) {
1750 size_t original_size = key_press_event_callbacks_.size();
1751 if (key_press_event_callbacks_[i].Run(event))
1754 // Check whether the callback that just ran removed itself, in which case
1755 // the iterator needs to be decremented to properly account for the removal.
1756 size_t current_size = key_press_event_callbacks_.size();
1757 if (current_size != original_size) {
1758 DCHECK_EQ(original_size - 1, current_size);
1766 InputEventAckState RenderWidgetHostImpl::FilterInputEvent(
1767 const blink::WebInputEvent& event, const ui::LatencyInfo& latency_info) {
1768 // Don't ignore touch cancel events, since they may be sent while input
1769 // events are being ignored in order to keep the renderer from getting
1770 // confused about how many touches are active.
1771 if (IgnoreInputEvents() && event.type != WebInputEvent::TouchCancel)
1772 return INPUT_EVENT_ACK_STATE_NO_CONSUMER_EXISTS;
1774 if (!process_->HasConnection())
1775 return INPUT_EVENT_ACK_STATE_UNKNOWN;
1777 if (event.type == WebInputEvent::MouseDown)
1780 return view_ ? view_->FilterInputEvent(event)
1781 : INPUT_EVENT_ACK_STATE_NOT_CONSUMED;
1784 void RenderWidgetHostImpl::IncrementInFlightEventCount() {
1785 StartHangMonitorTimeout(
1786 TimeDelta::FromMilliseconds(hung_renderer_delay_ms_));
1787 increment_in_flight_event_count();
1790 void RenderWidgetHostImpl::DecrementInFlightEventCount() {
1791 DCHECK_GE(in_flight_event_count_, 0);
1792 // Cancel pending hung renderer checks since the renderer is responsive.
1793 if (decrement_in_flight_event_count() <= 0)
1794 StopHangMonitorTimeout();
1797 void RenderWidgetHostImpl::OnHasTouchEventHandlers(bool has_handlers) {
1798 has_touch_handler_ = has_handlers;
1801 void RenderWidgetHostImpl::DidFlush() {
1802 if (synthetic_gesture_controller_)
1803 synthetic_gesture_controller_->OnDidFlushInput();
1805 view_->OnDidFlushInput();
1808 void RenderWidgetHostImpl::DidOverscroll(const DidOverscrollParams& params) {
1810 view_->DidOverscroll(params);
1813 void RenderWidgetHostImpl::OnKeyboardEventAck(
1814 const NativeWebKeyboardEvent& event,
1815 InputEventAckState ack_result) {
1816 #if defined(OS_MACOSX)
1817 if (!is_hidden() && view_ && view_->PostProcessEventForPluginIme(event))
1821 // We only send unprocessed key event upwards if we are not hidden,
1822 // because the user has moved away from us and no longer expect any effect
1823 // of this key event.
1824 const bool processed = (INPUT_EVENT_ACK_STATE_CONSUMED == ack_result);
1825 if (delegate_ && !processed && !is_hidden() && !event.skip_in_browser) {
1826 delegate_->HandleKeyboardEvent(event);
1828 // WARNING: This RenderWidgetHostImpl can be deallocated at this point
1829 // (i.e. in the case of Ctrl+W, where the call to
1830 // HandleKeyboardEvent destroys this RenderWidgetHostImpl).
1834 void RenderWidgetHostImpl::OnWheelEventAck(
1835 const MouseWheelEventWithLatencyInfo& wheel_event,
1836 InputEventAckState ack_result) {
1837 if (!wheel_event.latency.FindLatency(
1838 ui::INPUT_EVENT_LATENCY_RENDERING_SCHEDULED_COMPONENT, 0, NULL)) {
1839 // MouseWheelEvent latency ends when it is acked but does not cause any
1840 // rendering scheduled.
1841 ui::LatencyInfo latency = wheel_event.latency;
1842 latency.AddLatencyNumber(
1843 ui::INPUT_EVENT_LATENCY_TERMINATED_MOUSE_COMPONENT, 0, 0);
1846 if (!is_hidden() && view_) {
1847 if (ack_result != INPUT_EVENT_ACK_STATE_CONSUMED &&
1848 delegate_->HandleWheelEvent(wheel_event.event)) {
1849 ack_result = INPUT_EVENT_ACK_STATE_CONSUMED;
1851 view_->WheelEventAck(wheel_event.event, ack_result);
1855 void RenderWidgetHostImpl::OnGestureEventAck(
1856 const GestureEventWithLatencyInfo& event,
1857 InputEventAckState ack_result) {
1858 if (!event.latency.FindLatency(
1859 ui::INPUT_EVENT_LATENCY_RENDERING_SCHEDULED_COMPONENT, 0, NULL)) {
1860 // GestureEvent latency ends when it is acked but does not cause any
1861 // rendering scheduled.
1862 ui::LatencyInfo latency = event.latency;
1863 latency.AddLatencyNumber(
1864 ui::INPUT_EVENT_LATENCY_TERMINATED_GESTURE_COMPONENT, 0 ,0);
1867 if (ack_result != INPUT_EVENT_ACK_STATE_CONSUMED) {
1868 if (delegate_->HandleGestureEvent(event.event))
1869 ack_result = INPUT_EVENT_ACK_STATE_CONSUMED;
1873 view_->GestureEventAck(event.event, ack_result);
1876 void RenderWidgetHostImpl::OnTouchEventAck(
1877 const TouchEventWithLatencyInfo& event,
1878 InputEventAckState ack_result) {
1879 TouchEventWithLatencyInfo touch_event = event;
1880 touch_event.latency.AddLatencyNumber(
1881 ui::INPUT_EVENT_LATENCY_ACKED_TOUCH_COMPONENT, 0, 0);
1882 // TouchEvent latency ends at ack if it didn't cause any rendering.
1883 if (!touch_event.latency.FindLatency(
1884 ui::INPUT_EVENT_LATENCY_RENDERING_SCHEDULED_COMPONENT, 0, NULL)) {
1885 touch_event.latency.AddLatencyNumber(
1886 ui::INPUT_EVENT_LATENCY_TERMINATED_TOUCH_COMPONENT, 0, 0);
1888 ComputeTouchLatency(touch_event.latency);
1890 if (touch_emulator_ &&
1891 touch_emulator_->HandleTouchEventAck(event.event, ack_result)) {
1896 view_->ProcessAckedTouchEvent(touch_event, ack_result);
1899 void RenderWidgetHostImpl::OnUnexpectedEventAck(UnexpectedEventAckType type) {
1900 if (type == BAD_ACK_MESSAGE) {
1901 RecordAction(base::UserMetricsAction("BadMessageTerminate_RWH2"));
1902 process_->ReceivedBadMessage();
1903 } else if (type == UNEXPECTED_EVENT_TYPE) {
1904 suppress_next_char_events_ = false;
1908 void RenderWidgetHostImpl::OnSyntheticGestureCompleted(
1909 SyntheticGesture::Result result) {
1910 Send(new InputMsg_SyntheticGestureCompleted(GetRoutingID()));
1913 const gfx::Vector2d& RenderWidgetHostImpl::GetLastScrollOffset() const {
1914 return last_scroll_offset_;
1917 bool RenderWidgetHostImpl::IgnoreInputEvents() const {
1918 return ignore_input_events_ || process_->IgnoreInputEvents();
1921 bool RenderWidgetHostImpl::ShouldForwardTouchEvent() const {
1922 // It's important that the emulator sees a complete native touch stream,
1923 // allowing it to perform touch filtering as appropriate.
1924 // TODO(dgozman): Remove when touch stream forwarding issues resolved, see
1925 // crbug.com/375940.
1926 if (touch_emulator_ && touch_emulator_->enabled())
1929 return input_router_->ShouldForwardTouchEvent();
1932 void RenderWidgetHostImpl::StartUserGesture() {
1936 void RenderWidgetHostImpl::Stop() {
1937 Send(new ViewMsg_Stop(GetRoutingID()));
1940 void RenderWidgetHostImpl::SetBackgroundOpaque(bool opaque) {
1941 Send(new ViewMsg_SetBackgroundOpaque(GetRoutingID(), opaque));
1944 void RenderWidgetHostImpl::SetEditCommandsForNextKeyEvent(
1945 const std::vector<EditCommand>& commands) {
1946 Send(new InputMsg_SetEditCommandsForNextKeyEvent(GetRoutingID(), commands));
1949 void RenderWidgetHostImpl::ExecuteEditCommand(const std::string& command,
1950 const std::string& value) {
1951 Send(new InputMsg_ExecuteEditCommand(GetRoutingID(), command, value));
1954 void RenderWidgetHostImpl::ScrollFocusedEditableNodeIntoRect(
1955 const gfx::Rect& rect) {
1956 Send(new InputMsg_ScrollFocusedEditableNodeIntoRect(GetRoutingID(), rect));
1959 void RenderWidgetHostImpl::MoveCaret(const gfx::Point& point) {
1960 Send(new InputMsg_MoveCaret(GetRoutingID(), point));
1963 bool RenderWidgetHostImpl::GotResponseToLockMouseRequest(bool allowed) {
1965 RejectMouseLockOrUnlockIfNecessary();
1968 if (!pending_mouse_lock_request_) {
1969 // This is possible, e.g., the plugin sends us an unlock request before
1970 // the user allows to lock to mouse.
1974 pending_mouse_lock_request_ = false;
1975 if (!view_ || !view_->HasFocus()|| !view_->LockMouse()) {
1976 Send(new ViewMsg_LockMouse_ACK(routing_id_, false));
1979 Send(new ViewMsg_LockMouse_ACK(routing_id_, true));
1986 void RenderWidgetHostImpl::AcknowledgeBufferPresent(
1987 int32 route_id, int gpu_host_id,
1988 const AcceleratedSurfaceMsg_BufferPresented_Params& params) {
1989 GpuProcessHostUIShim* ui_shim = GpuProcessHostUIShim::FromID(gpu_host_id);
1991 ui_shim->Send(new AcceleratedSurfaceMsg_BufferPresented(route_id,
1997 void RenderWidgetHostImpl::SendSwapCompositorFrameAck(
1999 uint32 output_surface_id,
2000 int renderer_host_id,
2001 const cc::CompositorFrameAck& ack) {
2002 RenderProcessHost* host = RenderProcessHost::FromID(renderer_host_id);
2005 host->Send(new ViewMsg_SwapCompositorFrameAck(
2006 route_id, output_surface_id, ack));
2010 void RenderWidgetHostImpl::SendReclaimCompositorResources(
2012 uint32 output_surface_id,
2013 int renderer_host_id,
2014 const cc::CompositorFrameAck& ack) {
2015 RenderProcessHost* host = RenderProcessHost::FromID(renderer_host_id);
2019 new ViewMsg_ReclaimCompositorResources(route_id, output_surface_id, ack));
2022 void RenderWidgetHostImpl::DelayedAutoResized() {
2023 gfx::Size new_size = new_auto_size_;
2024 // Clear the new_auto_size_ since the empty value is used as a flag to
2025 // indicate that no callback is in progress (i.e. without this line
2026 // DelayedAutoResized will not get called again).
2027 new_auto_size_.SetSize(0, 0);
2028 if (!should_auto_resize_)
2031 OnRenderAutoResized(new_size);
2034 void RenderWidgetHostImpl::DetachDelegate() {
2038 void RenderWidgetHostImpl::ComputeTouchLatency(
2039 const ui::LatencyInfo& latency_info) {
2040 ui::LatencyInfo::LatencyComponent ui_component;
2041 ui::LatencyInfo::LatencyComponent rwh_component;
2042 ui::LatencyInfo::LatencyComponent acked_component;
2044 if (!latency_info.FindLatency(ui::INPUT_EVENT_LATENCY_UI_COMPONENT,
2047 !latency_info.FindLatency(ui::INPUT_EVENT_LATENCY_BEGIN_RWH_COMPONENT,
2048 GetLatencyComponentId(),
2052 DCHECK(ui_component.event_count == 1);
2053 DCHECK(rwh_component.event_count == 1);
2055 base::TimeDelta ui_delta =
2056 rwh_component.event_time - ui_component.event_time;
2057 UMA_HISTOGRAM_CUSTOM_COUNTS(
2058 "Event.Latency.Browser.TouchUI",
2059 ui_delta.InMicroseconds(),
2064 if (latency_info.FindLatency(ui::INPUT_EVENT_LATENCY_ACKED_TOUCH_COMPONENT,
2066 &acked_component)) {
2067 DCHECK(acked_component.event_count == 1);
2068 base::TimeDelta acked_delta =
2069 acked_component.event_time - rwh_component.event_time;
2070 UMA_HISTOGRAM_CUSTOM_COUNTS(
2071 "Event.Latency.Browser.TouchAcked",
2072 acked_delta.InMicroseconds(),
2079 void RenderWidgetHostImpl::FrameSwapped(const ui::LatencyInfo& latency_info) {
2080 ui::LatencyInfo::LatencyComponent window_snapshot_component;
2081 if (latency_info.FindLatency(ui::WINDOW_OLD_SNAPSHOT_FRAME_NUMBER_COMPONENT,
2082 GetLatencyComponentId(),
2083 &window_snapshot_component)) {
2084 WindowOldSnapshotReachedScreen(
2085 static_cast<int>(window_snapshot_component.sequence_number));
2087 if (latency_info.FindLatency(ui::WINDOW_SNAPSHOT_FRAME_NUMBER_COMPONENT,
2088 GetLatencyComponentId(),
2089 &window_snapshot_component)) {
2090 int sequence_number = static_cast<int>(
2091 window_snapshot_component.sequence_number);
2092 #if defined(OS_MACOSX)
2093 // On Mac, when using CoreAnmation, there is a delay between when content
2094 // is drawn to the screen, and when the snapshot will actually pick up
2095 // that content. Insert a manual delay of 1/6th of a second (to simulate
2096 // 10 frames at 60 fps) before actually taking the snapshot.
2097 base::MessageLoop::current()->PostDelayedTask(
2099 base::Bind(&RenderWidgetHostImpl::WindowSnapshotReachedScreen,
2100 weak_factory_.GetWeakPtr(),
2102 base::TimeDelta::FromSecondsD(1. / 6));
2104 WindowSnapshotReachedScreen(sequence_number);
2108 ui::LatencyInfo::LatencyComponent swap_component;
2109 if (!latency_info.FindLatency(
2110 ui::INPUT_EVENT_LATENCY_TERMINATED_FRAME_SWAP_COMPONENT,
2115 ui::LatencyInfo::LatencyComponent tab_switch_component;
2116 if (latency_info.FindLatency(ui::TAB_SHOW_COMPONENT,
2117 GetLatencyComponentId(),
2118 &tab_switch_component)) {
2119 base::TimeDelta delta =
2120 swap_component.event_time - tab_switch_component.event_time;
2121 for (size_t i = 0; i < tab_switch_component.event_count; i++) {
2122 UMA_HISTOGRAM_TIMES("MPArch.RWH_TabSwitchPaintDuration", delta);
2126 ui::LatencyInfo::LatencyComponent rwh_component;
2127 if (!latency_info.FindLatency(ui::INPUT_EVENT_LATENCY_BEGIN_RWH_COMPONENT,
2128 GetLatencyComponentId(),
2133 ui::LatencyInfo::LatencyComponent original_component;
2134 if (latency_info.FindLatency(
2135 ui::INPUT_EVENT_LATENCY_SCROLL_UPDATE_ORIGINAL_COMPONENT,
2136 GetLatencyComponentId(),
2137 &original_component)) {
2138 // This UMA metric tracks the time from when the original touch event is
2139 // created (averaged if there are multiple) to when the scroll gesture
2140 // results in final frame swap.
2141 base::TimeDelta delta =
2142 swap_component.event_time - original_component.event_time;
2143 for (size_t i = 0; i < original_component.event_count; i++) {
2144 UMA_HISTOGRAM_CUSTOM_COUNTS(
2145 "Event.Latency.TouchToScrollUpdateSwap",
2146 delta.InMicroseconds(),
2154 void RenderWidgetHostImpl::DidReceiveRendererFrame() {
2155 view_->DidReceiveRendererFrame();
2158 void RenderWidgetHostImpl::WindowSnapshotAsyncCallback(
2161 gfx::Size snapshot_size,
2162 scoped_refptr<base::RefCountedBytes> png_data) {
2164 std::vector<unsigned char> png_vector;
2165 Send(new ViewMsg_WindowSnapshotCompleted(
2166 routing_id, snapshot_id, gfx::Size(), png_vector));
2170 Send(new ViewMsg_WindowSnapshotCompleted(
2171 routing_id, snapshot_id, snapshot_size, png_data->data()));
2174 void RenderWidgetHostImpl::WindowOldSnapshotReachedScreen(int snapshot_id) {
2175 DCHECK(base::MessageLoopForUI::IsCurrent());
2177 std::vector<unsigned char> png;
2179 // This feature is behind the kEnableGpuBenchmarking command line switch
2180 // because it poses security concerns and should only be used for testing.
2181 const base::CommandLine& command_line =
2182 *base::CommandLine::ForCurrentProcess();
2183 if (!command_line.HasSwitch(cc::switches::kEnableGpuBenchmarking)) {
2184 Send(new ViewMsg_WindowSnapshotCompleted(
2185 GetRoutingID(), snapshot_id, gfx::Size(), png));
2189 gfx::Rect view_bounds = GetView()->GetViewBounds();
2190 gfx::Rect snapshot_bounds(view_bounds.size());
2191 gfx::Size snapshot_size = snapshot_bounds.size();
2193 if (ui::GrabViewSnapshot(
2194 GetView()->GetNativeView(), &png, snapshot_bounds)) {
2195 Send(new ViewMsg_WindowSnapshotCompleted(
2196 GetRoutingID(), snapshot_id, snapshot_size, png));
2200 ui::GrabViewSnapshotAsync(
2201 GetView()->GetNativeView(),
2203 base::ThreadTaskRunnerHandle::Get(),
2204 base::Bind(&RenderWidgetHostImpl::WindowSnapshotAsyncCallback,
2205 weak_factory_.GetWeakPtr(),
2211 void RenderWidgetHostImpl::WindowSnapshotReachedScreen(int snapshot_id) {
2212 DCHECK(base::MessageLoopForUI::IsCurrent());
2214 gfx::Rect view_bounds = GetView()->GetViewBounds();
2215 gfx::Rect snapshot_bounds(view_bounds.size());
2217 std::vector<unsigned char> png;
2218 if (ui::GrabViewSnapshot(
2219 GetView()->GetNativeView(), &png, snapshot_bounds)) {
2220 OnSnapshotDataReceived(snapshot_id, &png.front(), png.size());
2224 ui::GrabViewSnapshotAsync(
2225 GetView()->GetNativeView(),
2227 base::ThreadTaskRunnerHandle::Get(),
2228 base::Bind(&RenderWidgetHostImpl::OnSnapshotDataReceivedAsync,
2229 weak_factory_.GetWeakPtr(),
2233 void RenderWidgetHostImpl::OnSnapshotDataReceived(int snapshot_id,
2234 const unsigned char* data,
2236 // Any pending snapshots with a lower ID than the one received are considered
2237 // to be implicitly complete, and returned the same snapshot data.
2238 PendingSnapshotMap::iterator it = pending_browser_snapshots_.begin();
2239 while(it != pending_browser_snapshots_.end()) {
2240 if (it->first <= snapshot_id) {
2241 it->second.Run(data, size);
2242 pending_browser_snapshots_.erase(it++);
2249 void RenderWidgetHostImpl::OnSnapshotDataReceivedAsync(
2251 scoped_refptr<base::RefCountedBytes> png_data) {
2253 OnSnapshotDataReceived(snapshot_id, png_data->front(), png_data->size());
2255 OnSnapshotDataReceived(snapshot_id, NULL, 0);
2259 void RenderWidgetHostImpl::CompositorFrameDrawn(
2260 const std::vector<ui::LatencyInfo>& latency_info) {
2261 for (size_t i = 0; i < latency_info.size(); i++) {
2262 std::set<RenderWidgetHostImpl*> rwhi_set;
2263 for (ui::LatencyInfo::LatencyMap::const_iterator b =
2264 latency_info[i].latency_components.begin();
2265 b != latency_info[i].latency_components.end();
2267 if (b->first.first == ui::INPUT_EVENT_LATENCY_BEGIN_RWH_COMPONENT ||
2268 b->first.first == ui::WINDOW_SNAPSHOT_FRAME_NUMBER_COMPONENT ||
2269 b->first.first == ui::WINDOW_OLD_SNAPSHOT_FRAME_NUMBER_COMPONENT ||
2270 b->first.first == ui::TAB_SHOW_COMPONENT) {
2271 // Matches with GetLatencyComponentId
2272 int routing_id = b->first.second & 0xffffffff;
2273 int process_id = (b->first.second >> 32) & 0xffffffff;
2274 RenderWidgetHost* rwh =
2275 RenderWidgetHost::FromID(process_id, routing_id);
2279 RenderWidgetHostImpl* rwhi = RenderWidgetHostImpl::From(rwh);
2280 if (rwhi_set.insert(rwhi).second)
2281 rwhi->FrameSwapped(latency_info[i]);
2287 void RenderWidgetHostImpl::AddLatencyInfoComponentIds(
2288 ui::LatencyInfo* latency_info) {
2289 ui::LatencyInfo::LatencyMap new_components;
2290 ui::LatencyInfo::LatencyMap::iterator lc =
2291 latency_info->latency_components.begin();
2292 while (lc != latency_info->latency_components.end()) {
2293 ui::LatencyComponentType component_type = lc->first.first;
2294 if (component_type == ui::WINDOW_SNAPSHOT_FRAME_NUMBER_COMPONENT ||
2295 component_type == ui::WINDOW_OLD_SNAPSHOT_FRAME_NUMBER_COMPONENT) {
2296 // Generate a new component entry with the correct component ID
2297 ui::LatencyInfo::LatencyMap::key_type key =
2298 std::make_pair(component_type, GetLatencyComponentId());
2299 new_components[key] = lc->second;
2301 // Remove the old entry
2302 latency_info->latency_components.erase(lc++);
2308 // Add newly generated components into the latency info
2309 for (lc = new_components.begin(); lc != new_components.end(); ++lc) {
2310 latency_info->latency_components[lc->first] = lc->second;
2314 BrowserAccessibilityManager*
2315 RenderWidgetHostImpl::GetRootBrowserAccessibilityManager() {
2316 return delegate_ ? delegate_->GetRootBrowserAccessibilityManager() : NULL;
2319 BrowserAccessibilityManager*
2320 RenderWidgetHostImpl::GetOrCreateRootBrowserAccessibilityManager() {
2322 delegate_->GetOrCreateRootBrowserAccessibilityManager() : NULL;
2326 gfx::NativeViewAccessible
2327 RenderWidgetHostImpl::GetParentNativeViewAccessible() {
2328 return delegate_ ? delegate_->GetParentNativeViewAccessible() : NULL;
2332 SkColorType RenderWidgetHostImpl::PreferredReadbackFormat() {
2334 return view_->PreferredReadbackFormat();
2335 return kN32_SkColorType;
2338 } // namespace content