Upstream version 9.38.198.0
[platform/framework/web/crosswalk.git] / src / content / browser / renderer_host / render_widget_host_impl.cc
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.
4
5 #include "content/browser/renderer_host/render_widget_host_impl.h"
6
7 #include <math.h>
8 #include <set>
9 #include <utility>
10
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"
72
73 #if defined(OS_WIN)
74 #include "content/common/plugin_constants_win.h"
75 #endif
76
77 using base::Time;
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;
86
87 namespace content {
88 namespace {
89
90 bool g_check_for_pending_resize_ack = true;
91
92 typedef std::pair<int32, int32> RenderWidgetHostID;
93 typedef base::hash_map<RenderWidgetHostID, RenderWidgetHostImpl*>
94     RoutingIDWidgetMap;
95 base::LazyInstance<RoutingIDWidgetMap> g_routing_id_widget_map =
96     LAZY_INSTANCE_INITIALIZER;
97
98 int GetInputRouterViewFlagsFromCompositorFrameMetadata(
99     const cc::CompositorFrameMetadata metadata) {
100   int view_flags = InputRouter::VIEW_FLAGS_NONE;
101
102   if (metadata.min_page_scale_factor == metadata.max_page_scale_factor)
103     view_flags |= InputRouter::FIXED_PAGE_SCALE;
104
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;
110
111   return view_flags;
112 }
113
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 {
118  public:
119   RenderWidgetHostIteratorImpl()
120       : current_index_(0) {
121   }
122
123   virtual ~RenderWidgetHostIteratorImpl() {
124   }
125
126   void Add(RenderWidgetHost* host) {
127     hosts_.push_back(RenderWidgetHostID(host->GetProcess()->GetID(),
128                                         host->GetRoutingID()));
129   }
130
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);
137       ++current_index_;
138     }
139     return host;
140   }
141
142  private:
143   std::vector<RenderWidgetHostID> hosts_;
144   size_t current_index_;
145
146   DISALLOW_COPY_AND_ASSIGN(RenderWidgetHostIteratorImpl);
147 };
148
149 }  // namespace
150
151 ///////////////////////////////////////////////////////////////////////////////
152 // RenderWidgetHostImpl
153
154 RenderWidgetHostImpl::RenderWidgetHostImpl(RenderWidgetHostDelegate* delegate,
155                                            RenderProcessHost* process,
156                                            int routing_id,
157                                            bool hidden)
158     : view_(NULL),
159       renderer_initialized_(false),
160       hung_renderer_delay_ms_(kHungRendererDelayMs),
161       delegate_(delegate),
162       process_(process),
163       routing_id_(routing_id),
164       surface_id_(0),
165       is_loading_(false),
166       is_hidden_(hidden),
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),
187       weak_factory_(this),
188       last_input_number_(static_cast<int64>(GetProcess()->GetID()) << 32),
189       next_browser_snapshot_id_(1) {
190   CHECK(delegate_);
191   if (routing_id_ == MSG_ROUTING_NONE) {
192     routing_id_ = process_->GetNextRoutingID();
193     surface_id_ = GpuSurfaceTracker::Get()->AddSurfaceForRenderer(
194         process_->GetID(),
195         routing_id_);
196   } else {
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(
205         process_->GetID(),
206         routing_id_);
207     DCHECK(surface_id_);
208   }
209
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);
215
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.
218   if (!hidden)
219     process_->WidgetRestored();
220
221   input_router_.reset(new InputRouterImpl(
222       process_, this, this, routing_id_, GetInputRouterConfigForPlatform()));
223
224   touch_emulator_.reset();
225
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())));
234   }
235 }
236
237 RenderWidgetHostImpl::~RenderWidgetHostImpl() {
238   SetView(NULL);
239
240   GpuSurfaceTracker::Get()->RemoveSurface(surface_id_);
241   surface_id_ = 0;
242
243   process_->RemoveRoute(routing_id_);
244   g_routing_id_widget_map.Get().erase(
245       RenderWidgetHostID(process_->GetID(), routing_id_));
246
247   if (delegate_)
248     delegate_->RenderWidgetDeleted(this);
249 }
250
251 // static
252 RenderWidgetHost* RenderWidgetHost::FromID(
253     int32 process_id,
254     int32 routing_id) {
255   return RenderWidgetHostImpl::FromID(process_id, routing_id);
256 }
257
258 // static
259 RenderWidgetHostImpl* RenderWidgetHostImpl::FromID(
260     int32 process_id,
261     int32 routing_id) {
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;
267 }
268
269 // static
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();
275        ++it) {
276     RenderWidgetHost* widget = it->second;
277
278     if (!widget->IsRenderView()) {
279       hosts->Add(widget);
280       continue;
281     }
282
283     // Add only active RenderViewHosts.
284     RenderViewHost* rvh = RenderViewHost::From(widget);
285     if (RenderViewHostImpl::IsRVHStateActive(
286             static_cast<RenderViewHostImpl*>(rvh)->rvh_state()))
287       hosts->Add(widget);
288   }
289
290   return scoped_ptr<RenderWidgetHostIterator>(hosts);
291 }
292
293 // static
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();
300        ++it) {
301     hosts->Add(it->second);
302   }
303
304   return scoped_ptr<RenderWidgetHostIterator>(hosts);
305 }
306
307 // static
308 RenderWidgetHostImpl* RenderWidgetHostImpl::From(RenderWidgetHost* rwh) {
309   return rwh->AsRenderWidgetHostImpl();
310 }
311
312 void RenderWidgetHostImpl::SetView(RenderWidgetHostViewBase* view) {
313   view_ = view;
314
315   GpuSurfaceTracker::Get()->SetSurfaceHandle(
316       surface_id_, GetCompositingSurface());
317
318   synthetic_gesture_controller_.reset();
319 }
320
321 RenderProcessHost* RenderWidgetHostImpl::GetProcess() const {
322   return process_;
323 }
324
325 int RenderWidgetHostImpl::GetRoutingID() const {
326   return routing_id_;
327 }
328
329 RenderWidgetHostView* RenderWidgetHostImpl::GetView() const {
330   return view_;
331 }
332
333 RenderWidgetHostImpl* RenderWidgetHostImpl::AsRenderWidgetHostImpl() {
334   return this;
335 }
336
337 gfx::NativeViewId RenderWidgetHostImpl::GetNativeViewId() const {
338   if (view_)
339     return view_->GetNativeViewId();
340   return 0;
341 }
342
343 gfx::GLSurfaceHandle RenderWidgetHostImpl::GetCompositingSurface() {
344   if (view_)
345     return view_->GetCompositingSurface();
346   return gfx::GLSurfaceHandle();
347 }
348
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);
354   }
355   repaint_ack_pending_ = false;
356   last_requested_size_.SetSize(0, 0);
357 }
358
359 void RenderWidgetHostImpl::SendScreenRects() {
360   if (!renderer_initialized_ || waiting_for_screen_rects_ack_)
361     return;
362
363   if (is_hidden_) {
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.
366     return;
367   }
368
369   if (!view_)
370     return;
371
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_));
376   if (delegate_)
377     delegate_->DidSendScreenRects(this);
378   waiting_for_screen_rects_ack_ = true;
379 }
380
381 void RenderWidgetHostImpl::SuppressNextCharEvents() {
382   suppress_next_char_events_ = true;
383 }
384
385 void RenderWidgetHostImpl::FlushInput() {
386   input_router_->Flush();
387   if (synthetic_gesture_controller_)
388     synthetic_gesture_controller_->Flush(base::TimeTicks::Now());
389 }
390
391 void RenderWidgetHostImpl::SetNeedsFlush() {
392   if (view_)
393     view_->OnSetNeedsFlushInput();
394 }
395
396 void RenderWidgetHostImpl::Init() {
397   DCHECK(process_->HasConnection());
398
399   renderer_initialized_ = true;
400
401   GpuSurfaceTracker::Get()->SetSurfaceHandle(
402       surface_id_, GetCompositingSurface());
403
404   // Send the ack along with the information on placement.
405   Send(new ViewMsg_CreatingNew_ACK(routing_id_));
406   GetProcess()->ResumeRequestsForView(routing_id_);
407
408   WasResized();
409 }
410
411 void RenderWidgetHostImpl::Shutdown() {
412   RejectMouseLockOrUnlockIfNecessary();
413
414   if (process_->HasConnection()) {
415     // Tell the renderer object to close.
416     bool rv = Send(new ViewMsg_Close(routing_id_));
417     DCHECK(rv);
418   }
419
420   Destroy();
421 }
422
423 bool RenderWidgetHostImpl::IsLoading() const {
424   return is_loading_;
425 }
426
427 bool RenderWidgetHostImpl::IsRenderView() const {
428   return false;
429 }
430
431 bool RenderWidgetHostImpl::OnMessageReceived(const IPC::Message &msg) {
432   bool handled = true;
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)
463 #if defined(OS_WIN)
464     IPC_MESSAGE_HANDLER(ViewHostMsg_WindowlessPluginDummyWindowCreated,
465                         OnWindowlessPluginDummyWindowCreated)
466     IPC_MESSAGE_HANDLER(ViewHostMsg_WindowlessPluginDummyWindowDestroyed,
467                         OnWindowlessPluginDummyWindowDestroyed)
468 #endif
469 #if defined(OS_MACOSX) || defined(USE_AURA)
470     IPC_MESSAGE_HANDLER(InputHostMsg_ImeCompositionRangeChanged,
471                         OnImeCompositionRangeChanged)
472 #endif
473     IPC_MESSAGE_UNHANDLED(handled = false)
474   IPC_END_MESSAGE_MAP()
475
476   if (!handled && input_router_ && input_router_->OnMessageReceived(msg))
477     return true;
478
479   if (!handled && view_ && view_->OnMessageReceived(msg))
480     return true;
481
482   return handled;
483 }
484
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));
488
489   return process_->Send(msg);
490 }
491
492 void RenderWidgetHostImpl::WasHidden() {
493   if (is_hidden_)
494     return;
495
496   is_hidden_ = true;
497
498   // Don't bother reporting hung state when we aren't active.
499   StopHangMonitorTimeout();
500
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_));
504
505   // Tell the RenderProcessHost we were hidden.
506   process_->WidgetHidden();
507
508   bool is_visible = false;
509   NotificationService::current()->Notify(
510       NOTIFICATION_RENDER_WIDGET_VISIBILITY_CHANGED,
511       Source<RenderWidgetHost>(this),
512       Details<bool>(&is_visible));
513 }
514
515 void RenderWidgetHostImpl::WasShown(const ui::LatencyInfo& latency_info) {
516   if (!is_hidden_)
517     return;
518   is_hidden_ = false;
519
520   SendScreenRects();
521
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));
526
527   process_->WidgetRestored();
528
529   bool is_visible = true;
530   NotificationService::current()->Notify(
531       NOTIFICATION_RENDER_WIDGET_VISIBILITY_CHANGED,
532       Source<RenderWidgetHost>(this),
533       Details<bool>(&is_visible));
534
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
539   // 3. WasHidden
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
542   //    is.
543   // By invoking WasResized the renderer is updated as necessary. WasResized
544   // does nothing if the sizes are already in sync.
545   //
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.
550   WasResized();
551 }
552
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_) {
558     return;
559   }
560
561   gfx::Size new_size(view_->GetRequestedRendererSize());
562
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();
571
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_;
579
580   if (!size_changed && !side_payload_changed)
581     return;
582
583   if (!screen_info_) {
584     screen_info_.reset(new blink::WebScreenInfo);
585     GetWebScreenInfo(screen_info_.get());
586   }
587
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;
592
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;
603   } else {
604     last_requested_size_ = new_size;
605   }
606 }
607
608 void RenderWidgetHostImpl::ResizeRectChanged(const gfx::Rect& new_rect) {
609   Send(new ViewMsg_ChangeResizeRect(routing_id_, new_rect));
610 }
611
612 void RenderWidgetHostImpl::GotFocus() {
613   Focus();
614 }
615
616 void RenderWidgetHostImpl::Focus() {
617   Send(new InputMsg_SetFocus(routing_id_, true));
618 }
619
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
623   // request later.
624   if (IsMouseLocked())
625     view_->UnlockMouse();
626
627   if (touch_emulator_)
628     touch_emulator_->CancelTouch();
629
630   Send(new InputMsg_SetFocus(routing_id_, false));
631 }
632
633 void RenderWidgetHostImpl::LostCapture() {
634   if (touch_emulator_)
635     touch_emulator_->CancelTouch();
636
637   Send(new InputMsg_MouseCaptureLost(routing_id_));
638 }
639
640 void RenderWidgetHostImpl::SetActive(bool active) {
641   Send(new ViewMsg_SetActive(routing_id_, active));
642 }
643
644 void RenderWidgetHostImpl::LostMouseLock() {
645   Send(new ViewMsg_MouseLockLost(routing_id_));
646 }
647
648 void RenderWidgetHostImpl::ViewDestroyed() {
649   RejectMouseLockOrUnlockIfNecessary();
650
651   // TODO(evanm): tracking this may no longer be necessary;
652   // eliminate this function if so.
653   SetView(NULL);
654 }
655
656 void RenderWidgetHostImpl::SetIsLoading(bool is_loading) {
657   is_loading_ = is_loading;
658   if (!view_)
659     return;
660   view_->SetIsLoading(is_loading);
661 }
662
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) {
668   if (view_) {
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);
675     return;
676   }
677
678   callback.Run(false, SkBitmap());
679 }
680
681 bool RenderWidgetHostImpl::CanCopyFromBackingStore() {
682   if (view_)
683     return view_->IsSurfaceAvailableForCopy();
684   return false;
685 }
686
687 #if defined(OS_ANDROID)
688 void RenderWidgetHostImpl::LockBackingStore() {
689   if (view_)
690     view_->LockCompositingSurface();
691 }
692
693 void RenderWidgetHostImpl::UnlockBackingStore() {
694   if (view_)
695     view_->UnlockCompositingSurface();
696 }
697 #endif
698
699 #if defined(OS_MACOSX)
700 void RenderWidgetHostImpl::PauseForPendingResizeOrRepaints() {
701   TRACE_EVENT0("browser",
702       "RenderWidgetHostImpl::PauseForPendingResizeOrRepaints");
703
704   if (!CanPauseForPendingResizeOrRepaints())
705     return;
706
707   WaitForSurface();
708 }
709
710 bool RenderWidgetHostImpl::CanPauseForPendingResizeOrRepaints() {
711   // Do not pause if the view is hidden.
712   if (is_hidden())
713     return false;
714
715   // Do not pause if there is not a paint or resize already coming.
716   if (!repaint_ack_pending_ && !resize_ack_pending_)
717     return false;
718
719   return true;
720 }
721
722 void RenderWidgetHostImpl::WaitForSurface() {
723   TRACE_EVENT0("browser", "RenderWidgetHostImpl::WaitForSurface");
724
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;
729
730   if (!view_)
731     return;
732
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())
741       return;
742     view_size = view_rect.size();
743   }
744
745   TRACE_EVENT2("renderer_host",
746                "RenderWidgetHostImpl::WaitForBackingStore",
747                "width",
748                base::IntToString(view_size.width()),
749                "height",
750                base::IntToString(view_size.height()));
751
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!";
757
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);
763
764   // We might have a surface that we can use!
765   if (view_->HasAcceleratedSurface(view_size))
766     return;
767
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));
776   }
777
778   TimeDelta max_delay = TimeDelta::FromMilliseconds(kPaintMsgTimeoutMS);
779   TimeTicks end_time = TimeTicks::Now() + max_delay;
780   do {
781     TRACE_EVENT0("renderer_host", "WaitForSurface::WaitForUpdate");
782
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.
786     IPC::Message msg;
787     if (RenderWidgetResizeHelper::Get()->WaitForSingleTaskToRun(max_delay)) {
788
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_;
793
794       // Break now if we got a backing store or accelerated surface of the
795       // correct size.
796       if (view_->HasAcceleratedSurface(view_size))
797         return;
798     } else {
799       TRACE_EVENT0("renderer_host", "WaitForSurface::Timeout");
800       break;
801     }
802
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));
809 }
810 #endif
811
812 bool RenderWidgetHostImpl::ScheduleComposite() {
813   if (is_hidden_ || current_size_.IsEmpty() || repaint_ack_pending_ ||
814       resize_ack_pending_) {
815     return false;
816   }
817
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_));
824   return true;
825 }
826
827 void RenderWidgetHostImpl::StartHangMonitorTimeout(base::TimeDelta delay) {
828   if (hang_monitor_timeout_)
829     hang_monitor_timeout_->Start(delay);
830 }
831
832 void RenderWidgetHostImpl::RestartHangMonitorTimeout() {
833   if (hang_monitor_timeout_)
834     hang_monitor_timeout_->Restart(
835         base::TimeDelta::FromMilliseconds(hung_renderer_delay_ms_));
836 }
837
838 void RenderWidgetHostImpl::StopHangMonitorTimeout() {
839   if (hang_monitor_timeout_)
840     hang_monitor_timeout_->Stop();
841   RendererIsResponsive();
842 }
843
844 void RenderWidgetHostImpl::ForwardMouseEvent(const WebMouseEvent& mouse_event) {
845   ForwardMouseEventWithLatencyInfo(mouse_event, ui::LatencyInfo());
846 }
847
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);
853
854   ui::LatencyInfo latency_info =
855       CreateRWHLatencyInfoIfNotExist(&ui_latency, mouse_event.type);
856
857   for (size_t i = 0; i < mouse_event_callbacks_.size(); ++i) {
858     if (mouse_event_callbacks_[i].Run(mouse_event))
859       return;
860   }
861
862   if (IgnoreInputEvents())
863     return;
864
865   if (touch_emulator_ && touch_emulator_->HandleMouseEvent(mouse_event))
866     return;
867
868   input_router_->SendMouseEvent(MouseEventWithLatencyInfo(mouse_event,
869                                                           latency_info));
870 }
871
872 void RenderWidgetHostImpl::OnPointerEventActivate() {
873 }
874
875 void RenderWidgetHostImpl::ForwardWheelEvent(
876     const WebMouseWheelEvent& wheel_event) {
877   ForwardWheelEventWithLatencyInfo(wheel_event, ui::LatencyInfo());
878 }
879
880 void RenderWidgetHostImpl::ForwardWheelEventWithLatencyInfo(
881       const blink::WebMouseWheelEvent& wheel_event,
882       const ui::LatencyInfo& ui_latency) {
883   TRACE_EVENT0("input", "RenderWidgetHostImpl::ForwardWheelEvent");
884
885   ui::LatencyInfo latency_info =
886       CreateRWHLatencyInfoIfNotExist(&ui_latency, wheel_event.type);
887
888   if (IgnoreInputEvents())
889     return;
890
891   if (touch_emulator_ && touch_emulator_->HandleMouseWheelEvent(wheel_event))
892     return;
893
894   input_router_->SendWheelEvent(MouseWheelEventWithLatencyInfo(wheel_event,
895                                                                latency_info));
896 }
897
898 void RenderWidgetHostImpl::ForwardGestureEvent(
899     const blink::WebGestureEvent& gesture_event) {
900   ForwardGestureEventWithLatencyInfo(gesture_event, ui::LatencyInfo());
901 }
902
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())
909     return;
910
911   if (delegate_->PreHandleGestureEvent(gesture_event))
912     return;
913
914   ui::LatencyInfo latency_info =
915       CreateRWHLatencyInfoIfNotExist(&ui_latency, gesture_event.type);
916
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_);
922
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,
928                                  0,
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);
936     }
937   }
938
939   GestureEventWithLatencyInfo gesture_with_latency(gesture_event, latency_info);
940   input_router_->SendGestureEvent(gesture_with_latency);
941 }
942
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);
950 }
951
952 void RenderWidgetHostImpl::ForwardTouchEventWithLatencyInfo(
953       const blink::WebTouchEvent& touch_event,
954       const ui::LatencyInfo& ui_latency) {
955   TRACE_EVENT0("input", "RenderWidgetHostImpl::ForwardTouchEvent");
956
957   // Always forward TouchEvents for touch stream consistency. They will be
958   // ignored if appropriate in FilterInputEvent().
959
960   ui::LatencyInfo latency_info =
961       CreateRWHLatencyInfoIfNotExist(&ui_latency, touch_event.type);
962   TouchEventWithLatencyInfo touch_with_latency(touch_event, latency_info);
963
964   if (touch_emulator_ &&
965       touch_emulator_->HandleTouchEvent(touch_with_latency.event)) {
966     if (view_) {
967       view_->ProcessAckedTouchEvent(
968           touch_with_latency, INPUT_EVENT_ACK_STATE_CONSUMED);
969     }
970     return;
971   }
972
973   input_router_->SendTouchEvent(touch_with_latency);
974 }
975
976 void RenderWidgetHostImpl::ForwardKeyboardEvent(
977     const NativeWebKeyboardEvent& key_event) {
978   TRACE_EVENT0("input", "RenderWidgetHostImpl::ForwardKeyboardEvent");
979   if (IgnoreInputEvents())
980     return;
981
982   if (!process_->HasConnection())
983     return;
984
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;
992     return;
993   }
994
995   if (key_event.type == WebKeyboardEvent::Char &&
996       (key_event.windowsKeyCode == ui::VKEY_RETURN ||
997        key_event.windowsKeyCode == ui::VKEY_SPACE)) {
998     OnUserGesture();
999   }
1000
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))
1004     return;
1005
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)
1012       return;
1013     // We get a KeyUp or a RawKeyDown event.
1014     suppress_next_char_events_ = false;
1015   }
1016
1017   bool is_shortcut = false;
1018
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;
1027
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))
1031       return;
1032
1033     if (key_event.type == WebKeyboardEvent::RawKeyDown)
1034       suppress_next_char_events_ = false;
1035   }
1036
1037   if (touch_emulator_ && touch_emulator_->HandleKeyboardEvent(key_event))
1038     return;
1039
1040   input_router_->SendKeyboardEvent(
1041       key_event,
1042       CreateRWHLatencyInfoIfNotExist(NULL, key_event.type),
1043       is_shortcut);
1044 }
1045
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()));
1053   }
1054   if (synthetic_gesture_controller_) {
1055     synthetic_gesture_controller_->QueueSyntheticGesture(
1056         synthetic_gesture.Pass(), on_complete);
1057   }
1058 }
1059
1060 void RenderWidgetHostImpl::SetCursor(const WebCursor& cursor) {
1061   if (!view_)
1062     return;
1063   view_->UpdateCursor(cursor);
1064 }
1065
1066 void RenderWidgetHostImpl::ShowContextMenuAtPoint(const gfx::Point& point) {
1067   Send(new ViewMsg_ShowContextMenu(
1068       GetRoutingID(), ui::MENU_SOURCE_MOUSE, point));
1069 }
1070
1071 void RenderWidgetHostImpl::SendCursorVisibilityState(bool is_visible) {
1072   Send(new InputMsg_CursorVisibilityChange(GetRoutingID(), is_visible));
1073 }
1074
1075 int64 RenderWidgetHostImpl::GetLatencyComponentId() {
1076   return GetRoutingID() | (static_cast<int64>(GetProcess()->GetID()) << 32);
1077 }
1078
1079 // static
1080 void RenderWidgetHostImpl::DisableResizeAckCheckForTesting() {
1081   g_check_for_pending_resize_ack = false;
1082 }
1083
1084 ui::LatencyInfo RenderWidgetHostImpl::CreateRWHLatencyInfoIfNotExist(
1085     const ui::LatencyInfo* original, WebInputEvent::Type type) {
1086   ui::LatencyInfo info;
1087   if (original)
1088     info = *original;
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(),
1093                         NULL)) {
1094     info.AddLatencyNumber(ui::INPUT_EVENT_LATENCY_BEGIN_RWH_COMPONENT,
1095                           GetLatencyComponentId(),
1096                           ++last_input_number_);
1097     info.TraceEventType(WebInputEventTraits::GetName(type));
1098   }
1099   return info;
1100 }
1101
1102
1103 void RenderWidgetHostImpl::AddKeyPressEventCallback(
1104     const KeyPressEventCallback& callback) {
1105   key_press_event_callbacks_.push_back(callback);
1106 }
1107
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);
1114       return;
1115     }
1116   }
1117 }
1118
1119 void RenderWidgetHostImpl::AddMouseEventCallback(
1120     const MouseEventCallback& callback) {
1121   mouse_event_callbacks_.push_back(callback);
1122 }
1123
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);
1129       return;
1130     }
1131   }
1132 }
1133
1134 void RenderWidgetHostImpl::GetWebScreenInfo(blink::WebScreenInfo* result) {
1135   TRACE_EVENT0("renderer_host", "RenderWidgetHostImpl::GetWebScreenInfo");
1136   if (view_)
1137     view_->GetScreenInfo(result);
1138   else
1139     RenderWidgetHostViewBase::GetDefaultScreenInfo(result);
1140   screen_info_out_of_date_ = false;
1141 }
1142
1143 const NativeWebKeyboardEvent*
1144     RenderWidgetHostImpl::GetLastKeyboardEvent() const {
1145   return input_router_->GetLastKeyboardEvent();
1146 }
1147
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
1151   // factor).
1152   InvalidateScreenInfo();
1153   WasResized();
1154 }
1155
1156 void RenderWidgetHostImpl::InvalidateScreenInfo() {
1157   screen_info_out_of_date_ = true;
1158   screen_info_.reset();
1159 }
1160
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));
1166 }
1167
1168 void RenderWidgetHostImpl::OnSelectionChanged(const base::string16& text,
1169                                               size_t offset,
1170                                               const gfx::Range& range) {
1171   if (view_)
1172     view_->SelectionChanged(text, offset, range);
1173 }
1174
1175 void RenderWidgetHostImpl::OnSelectionBoundsChanged(
1176     const ViewHostMsg_SelectionBounds_Params& params) {
1177   if (view_) {
1178     view_->SelectionBoundsChanged(params);
1179   }
1180 }
1181
1182 void RenderWidgetHostImpl::UpdateVSyncParameters(base::TimeTicks timebase,
1183                                                  base::TimeDelta interval) {
1184   Send(new ViewMsg_UpdateVSyncParameters(GetRoutingID(), timebase, interval));
1185 }
1186
1187 void RenderWidgetHostImpl::RendererExited(base::TerminationStatus status,
1188                                           int exit_code) {
1189   // Clearing this flag causes us to re-create the renderer when recovering
1190   // from a crashed renderer.
1191   renderer_initialized_ = false;
1192
1193   waiting_for_screen_rects_ack_ = false;
1194
1195   // Must reset these to ensure that keyboard events work with a new renderer.
1196   suppress_next_char_events_ = false;
1197
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.
1205   //
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.
1209   if (!is_hidden_) {
1210     process_->WidgetRestored();
1211     is_hidden_ = false;
1212   }
1213
1214   // Reset this to ensure the hung renderer mechanism is working properly.
1215   in_flight_event_count_ = 0;
1216
1217   if (view_) {
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.
1222   }
1223
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()));
1230
1231   synthetic_gesture_controller_.reset();
1232 }
1233
1234 void RenderWidgetHostImpl::UpdateTextDirection(WebTextDirection direction) {
1235   text_direction_updated_ = true;
1236   text_direction_ = direction;
1237 }
1238
1239 void RenderWidgetHostImpl::CancelUpdateTextDirection() {
1240   if (text_direction_updated_)
1241     text_direction_canceled_ = true;
1242 }
1243
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;
1250   }
1251 }
1252
1253 void RenderWidgetHostImpl::SetInputMethodActive(bool activate) {
1254   input_method_active_ = activate;
1255   Send(new ViewMsg_SetInputMethodActive(GetRoutingID(), activate));
1256 }
1257
1258 void RenderWidgetHostImpl::CandidateWindowShown() {
1259   Send(new ViewMsg_CandidateWindowShown(GetRoutingID()));
1260 }
1261
1262 void RenderWidgetHostImpl::CandidateWindowUpdated() {
1263   Send(new ViewMsg_CandidateWindowUpdated(GetRoutingID()));
1264 }
1265
1266 void RenderWidgetHostImpl::CandidateWindowHidden() {
1267   Send(new ViewMsg_CandidateWindowHidden(GetRoutingID()));
1268 }
1269
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));
1277 }
1278
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));
1285 }
1286
1287 void RenderWidgetHostImpl::ImeCancelComposition() {
1288   Send(new InputMsg_ImeSetComposition(GetRoutingID(), base::string16(),
1289             std::vector<blink::WebCompositionUnderline>(), 0, 0));
1290 }
1291
1292 gfx::Rect RenderWidgetHostImpl::GetRootWindowResizerRect() const {
1293   return gfx::Rect();
1294 }
1295
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);
1301 }
1302
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();
1310   }
1311 }
1312
1313 bool RenderWidgetHostImpl::IsMouseLocked() const {
1314   return view_ ? view_->IsMouseLocked() : false;
1315 }
1316
1317 bool RenderWidgetHostImpl::IsFullscreen() const {
1318   return false;
1319 }
1320
1321 void RenderWidgetHostImpl::SetShouldAutoResize(bool enable) {
1322   should_auto_resize_ = enable;
1323 }
1324
1325 void RenderWidgetHostImpl::Destroy() {
1326   NotificationService::current()->Notify(
1327       NOTIFICATION_RENDER_WIDGET_HOST_DESTROYED,
1328       Source<RenderWidgetHost>(this),
1329       NotificationService::NoDetails());
1330
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().
1335   if (view_)
1336     view_->Destroy();
1337
1338   delete this;
1339 }
1340
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();
1348 }
1349
1350 void RenderWidgetHostImpl::RendererIsResponsive() {
1351   if (is_unresponsive_) {
1352     is_unresponsive_ = false;
1353     NotifyRendererResponsive();
1354   }
1355 }
1356
1357 void RenderWidgetHostImpl::OnRenderViewReady() {
1358   SendScreenRects();
1359   WasResized();
1360 }
1361
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.
1366   Destroy();
1367 }
1368
1369 void RenderWidgetHostImpl::OnClose() {
1370   Shutdown();
1371 }
1372
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.
1380   //
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.
1383   //
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);
1399     }
1400   }
1401   if (GetView())
1402     view_->SetTooltipText(wrapped_tooltip_text);
1403 }
1404
1405 void RenderWidgetHostImpl::OnUpdateScreenRectsAck() {
1406   waiting_for_screen_rects_ack_ = false;
1407   if (!view_)
1408     return;
1409
1410   if (view_->GetViewBounds() == last_view_screen_rect_ &&
1411       view_->GetBoundsInRootWindow() == last_window_screen_rect_) {
1412     return;
1413   }
1414
1415   SendScreenRects();
1416 }
1417
1418 void RenderWidgetHostImpl::OnRequestMove(const gfx::Rect& pos) {
1419   if (view_) {
1420     view_->SetBounds(pos);
1421     Send(new ViewMsg_Move_ACK(routing_id_));
1422   }
1423 }
1424
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, &param))
1433     return false;
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);
1439
1440   for (size_t i = 0; i < frame->metadata.latency_info.size(); i++)
1441     AddLatencyInfoComponentIds(&frame->metadata.latency_info[i]);
1442
1443   input_router_->OnViewUpdated(
1444       GetInputRouterViewFlagsFromCompositorFrameMetadata(frame->metadata));
1445
1446   if (view_) {
1447     view_->OnSwapCompositorFrame(output_surface_id, frame.Pass());
1448     view_->DidReceiveRendererFrame();
1449   } else {
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,
1457           &ack.resources);
1458     } else if (frame->software_frame_data) {
1459       ack.last_software_frame_id = frame->software_frame_data->id;
1460     }
1461     SendSwapCompositorFrameAck(routing_id_, output_surface_id,
1462                                process_->GetID(), ack);
1463   }
1464
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();
1469        ++i) {
1470     rph->OnMessageReceived(*i);
1471     if (i->dispatch_error())
1472       rph->OnBadMessageReceived(*i);
1473   }
1474   messages_to_deliver_with_frame.clear();
1475
1476   return true;
1477 }
1478
1479 void RenderWidgetHostImpl::OnFlingingStopped() {
1480   if (view_)
1481     view_->DidStopFlinging();
1482 }
1483
1484 void RenderWidgetHostImpl::OnUpdateRect(
1485     const ViewHostMsg_UpdateRect_Params& params) {
1486   TRACE_EVENT0("renderer_host", "RenderWidgetHostImpl::OnUpdateRect");
1487   TimeTicks paint_start = TimeTicks::Now();
1488
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;
1493
1494   bool is_resize_ack =
1495       ViewHostMsg_UpdateRect_Flags::is_resize_ack(params.flags);
1496
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;
1502   }
1503
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);
1513   }
1514
1515   DCHECK(!params.view_size.IsEmpty());
1516
1517   DidUpdateBackingStore(params, paint_start);
1518
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(
1524           FROM_HERE,
1525           base::Bind(&RenderWidgetHostImpl::DelayedAutoResized,
1526                      weak_factory_.GetWeakPtr()));
1527     }
1528   }
1529
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);
1535 }
1536
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();
1542
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.
1548   if (view_)
1549     view_->MovePluginWindows(params.plugin_window_moves);
1550
1551   NotificationService::current()->Notify(
1552       NOTIFICATION_RENDER_WIDGET_HOST_DID_UPDATE_BACKING_STORE,
1553       Source<RenderWidgetHost>(this),
1554       NotificationService::NoDetails());
1555
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
1558   // us more data.
1559   if (is_hidden_)
1560     return;
1561
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);
1565   if (is_resize_ack)
1566     WasResized();
1567
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);
1572 }
1573
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();
1581     return;
1582   }
1583
1584   QueueSyntheticGesture(
1585         SyntheticGesture::Create(*gesture_packet.gesture_params()),
1586         base::Bind(&RenderWidgetHostImpl::OnSyntheticGestureCompleted,
1587                    weak_factory_.GetWeakPtr()));
1588 }
1589
1590 void RenderWidgetHostImpl::OnFocus() {
1591   // Only RenderViewHost can deal with that message.
1592   RecordAction(base::UserMetricsAction("BadMessageTerminate_RWH4"));
1593   GetProcess()->ReceivedBadMessage();
1594 }
1595
1596 void RenderWidgetHostImpl::OnBlur() {
1597   // Only RenderViewHost can deal with that message.
1598   RecordAction(base::UserMetricsAction("BadMessageTerminate_RWH5"));
1599   GetProcess()->ReceivedBadMessage();
1600 }
1601
1602 void RenderWidgetHostImpl::OnSetCursor(const WebCursor& cursor) {
1603   SetCursor(cursor);
1604 }
1605
1606 void RenderWidgetHostImpl::OnSetTouchEventEmulationEnabled(
1607     bool enabled, bool allow_pinch) {
1608   SetTouchEventEmulationEnabled(enabled, allow_pinch);
1609 }
1610
1611 void RenderWidgetHostImpl::SetTouchEventEmulationEnabled(
1612     bool enabled, bool allow_pinch) {
1613   if (delegate_)
1614     delegate_->OnTouchEmulationEnabled(enabled);
1615
1616   if (enabled) {
1617     if (!touch_emulator_)
1618       touch_emulator_.reset(new TouchEmulator(this));
1619     touch_emulator_->Enable(allow_pinch);
1620   } else {
1621     if (touch_emulator_)
1622       touch_emulator_->Disable();
1623   }
1624 }
1625
1626 void RenderWidgetHostImpl::OnTextInputStateChanged(
1627     const ViewHostMsg_TextInputState_Params& params) {
1628   if (view_)
1629     view_->TextInputStateChanged(params);
1630 }
1631
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) {
1636   if (view_)
1637     view_->ImeCompositionRangeChanged(range, character_bounds);
1638 }
1639 #endif
1640
1641 void RenderWidgetHostImpl::OnImeCancelComposition() {
1642   if (view_)
1643     view_->ImeCancelComposition();
1644 }
1645
1646 void RenderWidgetHostImpl::OnLockMouse(bool user_gesture,
1647                                        bool last_unlocked_by_target,
1648                                        bool privileged) {
1649
1650   if (pending_mouse_lock_request_) {
1651     Send(new ViewMsg_LockMouse_ACK(routing_id_, false));
1652     return;
1653   } else if (IsMouseLocked()) {
1654     Send(new ViewMsg_LockMouse_ACK(routing_id_, true));
1655     return;
1656   }
1657
1658   pending_mouse_lock_request_ = true;
1659   if (privileged && allow_privileged_mouse_lock_) {
1660     // Directly approve to lock the mouse.
1661     GotResponseToLockMouseRequest(true);
1662   } else {
1663     RequestToLockMouse(user_gesture, last_unlocked_by_target);
1664   }
1665 }
1666
1667 void RenderWidgetHostImpl::OnUnlockMouse() {
1668   RejectMouseLockOrUnlockIfNecessary();
1669 }
1670
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());
1677
1678   scoped_ptr<cc::SharedBitmap> bitmap =
1679       HostSharedBitmapManager::current()->GetSharedBitmapFromId(size, id);
1680   if (!bitmap) {
1681     RecordAction(base::UserMetricsAction("BadMessageTerminate_RWH6"));
1682     GetProcess()->ReceivedBadMessage();
1683     return;
1684   }
1685
1686   DCHECK(bitmap->pixels());
1687
1688   SkImageInfo info = SkImageInfo::MakeN32Premul(size.width(), size.height());
1689   SkBitmap zoomed_bitmap;
1690   zoomed_bitmap.installPixels(info, bitmap->pixels(), info.minRowBytes());
1691
1692 #if defined(OS_ANDROID)
1693   if (view_)
1694     view_->ShowDisambiguationPopup(rect, zoomed_bitmap);
1695 #else
1696   NOTIMPLEMENTED();
1697 #endif
1698
1699   zoomed_bitmap.setPixels(0);
1700   Send(new ViewMsg_ReleaseDisambiguationPopupBitmap(GetRoutingID(), id));
1701 }
1702
1703 #if defined(OS_WIN)
1704 void RenderWidgetHostImpl::OnWindowlessPluginDummyWindowCreated(
1705     gfx::NativeViewId dummy_activation_window) {
1706   HWND hwnd = reinterpret_cast<HWND>(dummy_activation_window);
1707
1708   // This may happen as a result of a race condition when the plugin is going
1709   // away.
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) {
1714     return;
1715   }
1716
1717 #if defined(USE_AURA)
1718   SetParent(hwnd,
1719             reinterpret_cast<HWND>(view_->GetParentForWindowlessPlugin()));
1720 #else
1721   SetParent(hwnd, reinterpret_cast<HWND>(GetNativeViewId()));
1722 #endif
1723   dummy_windows_for_activation_.push_back(hwnd);
1724 }
1725
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) {
1731     if ((*i) == hwnd) {
1732       dummy_windows_for_activation_.erase(i);
1733       return;
1734     }
1735   }
1736   NOTREACHED() << "Unknown dummy window";
1737 }
1738 #endif
1739
1740 void RenderWidgetHostImpl::SetIgnoreInputEvents(bool ignore_input_events) {
1741   ignore_input_events_ = ignore_input_events;
1742 }
1743
1744 bool RenderWidgetHostImpl::KeyPressListenersHandleEvent(
1745     const NativeWebKeyboardEvent& event) {
1746   if (event.skip_in_browser || event.type != WebKeyboardEvent::RawKeyDown)
1747     return false;
1748
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))
1752       return true;
1753
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);
1759       --i;
1760     }
1761   }
1762
1763   return false;
1764 }
1765
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;
1773
1774   if (!process_->HasConnection())
1775     return INPUT_EVENT_ACK_STATE_UNKNOWN;
1776
1777   if (event.type == WebInputEvent::MouseDown)
1778     OnUserGesture();
1779
1780   return view_ ? view_->FilterInputEvent(event)
1781                : INPUT_EVENT_ACK_STATE_NOT_CONSUMED;
1782 }
1783
1784 void RenderWidgetHostImpl::IncrementInFlightEventCount() {
1785   StartHangMonitorTimeout(
1786       TimeDelta::FromMilliseconds(hung_renderer_delay_ms_));
1787   increment_in_flight_event_count();
1788 }
1789
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();
1795 }
1796
1797 void RenderWidgetHostImpl::OnHasTouchEventHandlers(bool has_handlers) {
1798   has_touch_handler_ = has_handlers;
1799 }
1800
1801 void RenderWidgetHostImpl::DidFlush() {
1802   if (synthetic_gesture_controller_)
1803     synthetic_gesture_controller_->OnDidFlushInput();
1804   if (view_)
1805     view_->OnDidFlushInput();
1806 }
1807
1808 void RenderWidgetHostImpl::DidOverscroll(const DidOverscrollParams& params) {
1809   if (view_)
1810     view_->DidOverscroll(params);
1811 }
1812
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))
1818     return;
1819 #endif
1820
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);
1827
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).
1831   }
1832 }
1833
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);
1844   }
1845
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;
1850     }
1851     view_->WheelEventAck(wheel_event.event, ack_result);
1852   }
1853 }
1854
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);
1865   }
1866
1867   if (ack_result != INPUT_EVENT_ACK_STATE_CONSUMED) {
1868     if (delegate_->HandleGestureEvent(event.event))
1869       ack_result = INPUT_EVENT_ACK_STATE_CONSUMED;
1870   }
1871
1872   if (view_)
1873     view_->GestureEventAck(event.event, ack_result);
1874 }
1875
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);
1887   }
1888   ComputeTouchLatency(touch_event.latency);
1889
1890   if (touch_emulator_ &&
1891       touch_emulator_->HandleTouchEventAck(event.event, ack_result)) {
1892     return;
1893   }
1894
1895   if (view_)
1896     view_->ProcessAckedTouchEvent(touch_event, ack_result);
1897 }
1898
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;
1905   }
1906 }
1907
1908 void RenderWidgetHostImpl::OnSyntheticGestureCompleted(
1909     SyntheticGesture::Result result) {
1910   Send(new InputMsg_SyntheticGestureCompleted(GetRoutingID()));
1911 }
1912
1913 const gfx::Vector2d& RenderWidgetHostImpl::GetLastScrollOffset() const {
1914   return last_scroll_offset_;
1915 }
1916
1917 bool RenderWidgetHostImpl::IgnoreInputEvents() const {
1918   return ignore_input_events_ || process_->IgnoreInputEvents();
1919 }
1920
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())
1927     return true;
1928
1929   return input_router_->ShouldForwardTouchEvent();
1930 }
1931
1932 void RenderWidgetHostImpl::StartUserGesture() {
1933   OnUserGesture();
1934 }
1935
1936 void RenderWidgetHostImpl::Stop() {
1937   Send(new ViewMsg_Stop(GetRoutingID()));
1938 }
1939
1940 void RenderWidgetHostImpl::SetBackgroundOpaque(bool opaque) {
1941   Send(new ViewMsg_SetBackgroundOpaque(GetRoutingID(), opaque));
1942 }
1943
1944 void RenderWidgetHostImpl::SetEditCommandsForNextKeyEvent(
1945     const std::vector<EditCommand>& commands) {
1946   Send(new InputMsg_SetEditCommandsForNextKeyEvent(GetRoutingID(), commands));
1947 }
1948
1949 void RenderWidgetHostImpl::ExecuteEditCommand(const std::string& command,
1950                                               const std::string& value) {
1951   Send(new InputMsg_ExecuteEditCommand(GetRoutingID(), command, value));
1952 }
1953
1954 void RenderWidgetHostImpl::ScrollFocusedEditableNodeIntoRect(
1955     const gfx::Rect& rect) {
1956   Send(new InputMsg_ScrollFocusedEditableNodeIntoRect(GetRoutingID(), rect));
1957 }
1958
1959 void RenderWidgetHostImpl::MoveCaret(const gfx::Point& point) {
1960   Send(new InputMsg_MoveCaret(GetRoutingID(), point));
1961 }
1962
1963 bool RenderWidgetHostImpl::GotResponseToLockMouseRequest(bool allowed) {
1964   if (!allowed) {
1965     RejectMouseLockOrUnlockIfNecessary();
1966     return false;
1967   } else {
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.
1971       return false;
1972     }
1973
1974     pending_mouse_lock_request_ = false;
1975     if (!view_ || !view_->HasFocus()|| !view_->LockMouse()) {
1976       Send(new ViewMsg_LockMouse_ACK(routing_id_, false));
1977       return false;
1978     } else {
1979       Send(new ViewMsg_LockMouse_ACK(routing_id_, true));
1980       return true;
1981     }
1982   }
1983 }
1984
1985 // static
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);
1990   if (ui_shim) {
1991     ui_shim->Send(new AcceleratedSurfaceMsg_BufferPresented(route_id,
1992                                                             params));
1993   }
1994 }
1995
1996 // static
1997 void RenderWidgetHostImpl::SendSwapCompositorFrameAck(
1998     int32 route_id,
1999     uint32 output_surface_id,
2000     int renderer_host_id,
2001     const cc::CompositorFrameAck& ack) {
2002   RenderProcessHost* host = RenderProcessHost::FromID(renderer_host_id);
2003   if (!host)
2004     return;
2005   host->Send(new ViewMsg_SwapCompositorFrameAck(
2006       route_id, output_surface_id, ack));
2007 }
2008
2009 // static
2010 void RenderWidgetHostImpl::SendReclaimCompositorResources(
2011     int32 route_id,
2012     uint32 output_surface_id,
2013     int renderer_host_id,
2014     const cc::CompositorFrameAck& ack) {
2015   RenderProcessHost* host = RenderProcessHost::FromID(renderer_host_id);
2016   if (!host)
2017     return;
2018   host->Send(
2019       new ViewMsg_ReclaimCompositorResources(route_id, output_surface_id, ack));
2020 }
2021
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_)
2029     return;
2030
2031   OnRenderAutoResized(new_size);
2032 }
2033
2034 void RenderWidgetHostImpl::DetachDelegate() {
2035   delegate_ = NULL;
2036 }
2037
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;
2043
2044   if (!latency_info.FindLatency(ui::INPUT_EVENT_LATENCY_UI_COMPONENT,
2045                                 0,
2046                                 &ui_component) ||
2047       !latency_info.FindLatency(ui::INPUT_EVENT_LATENCY_BEGIN_RWH_COMPONENT,
2048                                 GetLatencyComponentId(),
2049                                 &rwh_component))
2050     return;
2051
2052   DCHECK(ui_component.event_count == 1);
2053   DCHECK(rwh_component.event_count == 1);
2054
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(),
2060       1,
2061       20000,
2062       100);
2063
2064   if (latency_info.FindLatency(ui::INPUT_EVENT_LATENCY_ACKED_TOUCH_COMPONENT,
2065                                0,
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(),
2073         1,
2074         1000000,
2075         100);
2076   }
2077 }
2078
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));
2086   }
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(
2098         FROM_HERE,
2099         base::Bind(&RenderWidgetHostImpl::WindowSnapshotReachedScreen,
2100                    weak_factory_.GetWeakPtr(),
2101                    sequence_number),
2102         base::TimeDelta::FromSecondsD(1. / 6));
2103 #else
2104     WindowSnapshotReachedScreen(sequence_number);
2105 #endif
2106   }
2107
2108   ui::LatencyInfo::LatencyComponent swap_component;
2109   if (!latency_info.FindLatency(
2110           ui::INPUT_EVENT_LATENCY_TERMINATED_FRAME_SWAP_COMPONENT,
2111           0,
2112           &swap_component)) {
2113     return;
2114   }
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);
2123     }
2124   }
2125
2126   ui::LatencyInfo::LatencyComponent rwh_component;
2127   if (!latency_info.FindLatency(ui::INPUT_EVENT_LATENCY_BEGIN_RWH_COMPONENT,
2128                                 GetLatencyComponentId(),
2129                                 &rwh_component)) {
2130     return;
2131   }
2132
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(),
2147           1,
2148           1000000,
2149           100);
2150     }
2151   }
2152 }
2153
2154 void RenderWidgetHostImpl::DidReceiveRendererFrame() {
2155   view_->DidReceiveRendererFrame();
2156 }
2157
2158 void RenderWidgetHostImpl::WindowSnapshotAsyncCallback(
2159     int routing_id,
2160     int snapshot_id,
2161     gfx::Size snapshot_size,
2162     scoped_refptr<base::RefCountedBytes> png_data) {
2163   if (!png_data) {
2164     std::vector<unsigned char> png_vector;
2165     Send(new ViewMsg_WindowSnapshotCompleted(
2166         routing_id, snapshot_id, gfx::Size(), png_vector));
2167     return;
2168   }
2169
2170   Send(new ViewMsg_WindowSnapshotCompleted(
2171       routing_id, snapshot_id, snapshot_size, png_data->data()));
2172 }
2173
2174 void RenderWidgetHostImpl::WindowOldSnapshotReachedScreen(int snapshot_id) {
2175   DCHECK(base::MessageLoopForUI::IsCurrent());
2176
2177   std::vector<unsigned char> png;
2178
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));
2186     return;
2187   }
2188
2189   gfx::Rect view_bounds = GetView()->GetViewBounds();
2190   gfx::Rect snapshot_bounds(view_bounds.size());
2191   gfx::Size snapshot_size = snapshot_bounds.size();
2192
2193   if (ui::GrabViewSnapshot(
2194           GetView()->GetNativeView(), &png, snapshot_bounds)) {
2195     Send(new ViewMsg_WindowSnapshotCompleted(
2196         GetRoutingID(), snapshot_id, snapshot_size, png));
2197     return;
2198   }
2199
2200   ui::GrabViewSnapshotAsync(
2201       GetView()->GetNativeView(),
2202       snapshot_bounds,
2203       base::ThreadTaskRunnerHandle::Get(),
2204       base::Bind(&RenderWidgetHostImpl::WindowSnapshotAsyncCallback,
2205                  weak_factory_.GetWeakPtr(),
2206                  GetRoutingID(),
2207                  snapshot_id,
2208                  snapshot_size));
2209 }
2210
2211 void RenderWidgetHostImpl::WindowSnapshotReachedScreen(int snapshot_id) {
2212   DCHECK(base::MessageLoopForUI::IsCurrent());
2213
2214   gfx::Rect view_bounds = GetView()->GetViewBounds();
2215   gfx::Rect snapshot_bounds(view_bounds.size());
2216
2217   std::vector<unsigned char> png;
2218   if (ui::GrabViewSnapshot(
2219       GetView()->GetNativeView(), &png, snapshot_bounds)) {
2220     OnSnapshotDataReceived(snapshot_id, &png.front(), png.size());
2221     return;
2222   }
2223
2224   ui::GrabViewSnapshotAsync(
2225       GetView()->GetNativeView(),
2226       snapshot_bounds,
2227       base::ThreadTaskRunnerHandle::Get(),
2228       base::Bind(&RenderWidgetHostImpl::OnSnapshotDataReceivedAsync,
2229                  weak_factory_.GetWeakPtr(),
2230                  snapshot_id));
2231 }
2232
2233 void RenderWidgetHostImpl::OnSnapshotDataReceived(int snapshot_id,
2234                                                   const unsigned char* data,
2235                                                   size_t size) {
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++);
2243       } else {
2244         ++it;
2245       }
2246   }
2247 }
2248
2249 void RenderWidgetHostImpl::OnSnapshotDataReceivedAsync(
2250     int snapshot_id,
2251     scoped_refptr<base::RefCountedBytes> png_data) {
2252   if (png_data)
2253     OnSnapshotDataReceived(snapshot_id, png_data->front(), png_data->size());
2254   else
2255     OnSnapshotDataReceived(snapshot_id, NULL, 0);
2256 }
2257
2258 // static
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();
2266          ++b) {
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);
2276         if (!rwh) {
2277           continue;
2278         }
2279         RenderWidgetHostImpl* rwhi = RenderWidgetHostImpl::From(rwh);
2280         if (rwhi_set.insert(rwhi).second)
2281           rwhi->FrameSwapped(latency_info[i]);
2282       }
2283     }
2284   }
2285 }
2286
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;
2300
2301       // Remove the old entry
2302       latency_info->latency_components.erase(lc++);
2303     } else {
2304       ++lc;
2305     }
2306   }
2307
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;
2311   }
2312 }
2313
2314 BrowserAccessibilityManager*
2315     RenderWidgetHostImpl::GetRootBrowserAccessibilityManager() {
2316   return delegate_ ? delegate_->GetRootBrowserAccessibilityManager() : NULL;
2317 }
2318
2319 BrowserAccessibilityManager*
2320     RenderWidgetHostImpl::GetOrCreateRootBrowserAccessibilityManager() {
2321   return delegate_ ?
2322       delegate_->GetOrCreateRootBrowserAccessibilityManager() : NULL;
2323 }
2324
2325 #if defined(OS_WIN)
2326 gfx::NativeViewAccessible
2327     RenderWidgetHostImpl::GetParentNativeViewAccessible() {
2328   return delegate_ ? delegate_->GetParentNativeViewAccessible() : NULL;
2329 }
2330 #endif
2331
2332 SkColorType RenderWidgetHostImpl::PreferredReadbackFormat() {
2333   if (view_)
2334     return view_->PreferredReadbackFormat();
2335   return kN32_SkColorType;
2336 }
2337
2338 }  // namespace content