Upstream version 11.39.250.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       top_controls_layout_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       last_input_number_(static_cast<int64>(GetProcess()->GetID()) << 32),
188       next_browser_snapshot_id_(1),
189       weak_factory_(this) {
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   if (view_weak_)
239     view_weak_->RenderWidgetHostGone();
240   SetView(NULL);
241
242   GpuSurfaceTracker::Get()->RemoveSurface(surface_id_);
243   surface_id_ = 0;
244
245   process_->RemoveRoute(routing_id_);
246   g_routing_id_widget_map.Get().erase(
247       RenderWidgetHostID(process_->GetID(), routing_id_));
248
249   if (delegate_)
250     delegate_->RenderWidgetDeleted(this);
251 }
252
253 // static
254 RenderWidgetHost* RenderWidgetHost::FromID(
255     int32 process_id,
256     int32 routing_id) {
257   return RenderWidgetHostImpl::FromID(process_id, routing_id);
258 }
259
260 // static
261 RenderWidgetHostImpl* RenderWidgetHostImpl::FromID(
262     int32 process_id,
263     int32 routing_id) {
264   DCHECK_CURRENTLY_ON(BrowserThread::UI);
265   RoutingIDWidgetMap* widgets = g_routing_id_widget_map.Pointer();
266   RoutingIDWidgetMap::iterator it = widgets->find(
267       RenderWidgetHostID(process_id, routing_id));
268   return it == widgets->end() ? NULL : it->second;
269 }
270
271 // static
272 scoped_ptr<RenderWidgetHostIterator> RenderWidgetHost::GetRenderWidgetHosts() {
273   RenderWidgetHostIteratorImpl* hosts = new RenderWidgetHostIteratorImpl();
274   RoutingIDWidgetMap* widgets = g_routing_id_widget_map.Pointer();
275   for (RoutingIDWidgetMap::const_iterator it = widgets->begin();
276        it != widgets->end();
277        ++it) {
278     RenderWidgetHost* widget = it->second;
279
280     if (!widget->IsRenderView()) {
281       hosts->Add(widget);
282       continue;
283     }
284
285     // Add only active RenderViewHosts.
286     RenderViewHost* rvh = RenderViewHost::From(widget);
287     if (RenderViewHostImpl::IsRVHStateActive(
288             static_cast<RenderViewHostImpl*>(rvh)->rvh_state()))
289       hosts->Add(widget);
290   }
291
292   return scoped_ptr<RenderWidgetHostIterator>(hosts);
293 }
294
295 // static
296 scoped_ptr<RenderWidgetHostIterator>
297 RenderWidgetHostImpl::GetAllRenderWidgetHosts() {
298   RenderWidgetHostIteratorImpl* hosts = new RenderWidgetHostIteratorImpl();
299   RoutingIDWidgetMap* widgets = g_routing_id_widget_map.Pointer();
300   for (RoutingIDWidgetMap::const_iterator it = widgets->begin();
301        it != widgets->end();
302        ++it) {
303     hosts->Add(it->second);
304   }
305
306   return scoped_ptr<RenderWidgetHostIterator>(hosts);
307 }
308
309 // static
310 RenderWidgetHostImpl* RenderWidgetHostImpl::From(RenderWidgetHost* rwh) {
311   return rwh->AsRenderWidgetHostImpl();
312 }
313
314 void RenderWidgetHostImpl::SetView(RenderWidgetHostViewBase* view) {
315   if (view)
316     view_weak_ = view->GetWeakPtr();
317   else
318     view_weak_.reset();
319   view_ = view;
320
321   GpuSurfaceTracker::Get()->SetSurfaceHandle(
322       surface_id_, GetCompositingSurface());
323
324   synthetic_gesture_controller_.reset();
325 }
326
327 RenderProcessHost* RenderWidgetHostImpl::GetProcess() const {
328   return process_;
329 }
330
331 int RenderWidgetHostImpl::GetRoutingID() const {
332   return routing_id_;
333 }
334
335 RenderWidgetHostView* RenderWidgetHostImpl::GetView() const {
336   return view_;
337 }
338
339 RenderWidgetHostImpl* RenderWidgetHostImpl::AsRenderWidgetHostImpl() {
340   return this;
341 }
342
343 gfx::NativeViewId RenderWidgetHostImpl::GetNativeViewId() const {
344   if (view_)
345     return view_->GetNativeViewId();
346   return 0;
347 }
348
349 gfx::GLSurfaceHandle RenderWidgetHostImpl::GetCompositingSurface() {
350   if (view_)
351     return view_->GetCompositingSurface();
352   return gfx::GLSurfaceHandle();
353 }
354
355 void RenderWidgetHostImpl::ResetSizeAndRepaintPendingFlags() {
356   resize_ack_pending_ = false;
357   if (repaint_ack_pending_) {
358     TRACE_EVENT_ASYNC_END0(
359         "renderer_host", "RenderWidgetHostImpl::repaint_ack_pending_", this);
360   }
361   repaint_ack_pending_ = false;
362   last_requested_size_.SetSize(0, 0);
363 }
364
365 void RenderWidgetHostImpl::SendScreenRects() {
366   if (!renderer_initialized_ || waiting_for_screen_rects_ack_)
367     return;
368
369   if (is_hidden_) {
370     // On GTK, this comes in for backgrounded tabs. Ignore, to match what
371     // happens on Win & Mac, and when the view is shown it'll call this again.
372     return;
373   }
374
375   if (!view_)
376     return;
377
378   last_view_screen_rect_ = view_->GetViewBounds();
379   last_window_screen_rect_ = view_->GetBoundsInRootWindow();
380   Send(new ViewMsg_UpdateScreenRects(
381       GetRoutingID(), last_view_screen_rect_, last_window_screen_rect_));
382   if (delegate_)
383     delegate_->DidSendScreenRects(this);
384   waiting_for_screen_rects_ack_ = true;
385 }
386
387 void RenderWidgetHostImpl::SuppressNextCharEvents() {
388   suppress_next_char_events_ = true;
389 }
390
391 void RenderWidgetHostImpl::FlushInput() {
392   input_router_->Flush();
393   if (synthetic_gesture_controller_)
394     synthetic_gesture_controller_->Flush(base::TimeTicks::Now());
395 }
396
397 void RenderWidgetHostImpl::SetNeedsFlush() {
398   if (view_)
399     view_->OnSetNeedsFlushInput();
400 }
401
402 void RenderWidgetHostImpl::Init() {
403   DCHECK(process_->HasConnection());
404
405   renderer_initialized_ = true;
406
407   GpuSurfaceTracker::Get()->SetSurfaceHandle(
408       surface_id_, GetCompositingSurface());
409
410   // Send the ack along with the information on placement.
411   Send(new ViewMsg_CreatingNew_ACK(routing_id_));
412   GetProcess()->ResumeRequestsForView(routing_id_);
413
414   WasResized();
415 }
416
417 void RenderWidgetHostImpl::Shutdown() {
418   RejectMouseLockOrUnlockIfNecessary();
419
420   if (process_->HasConnection()) {
421     // Tell the renderer object to close.
422     bool rv = Send(new ViewMsg_Close(routing_id_));
423     DCHECK(rv);
424   }
425
426   Destroy();
427 }
428
429 bool RenderWidgetHostImpl::IsLoading() const {
430   return is_loading_;
431 }
432
433 bool RenderWidgetHostImpl::IsRenderView() const {
434   return false;
435 }
436
437 bool RenderWidgetHostImpl::OnMessageReceived(const IPC::Message &msg) {
438   bool handled = true;
439   IPC_BEGIN_MESSAGE_MAP(RenderWidgetHostImpl, msg)
440     IPC_MESSAGE_HANDLER(InputHostMsg_QueueSyntheticGesture,
441                         OnQueueSyntheticGesture)
442     IPC_MESSAGE_HANDLER(InputHostMsg_ImeCancelComposition,
443                         OnImeCancelComposition)
444     IPC_MESSAGE_HANDLER(ViewHostMsg_RenderViewReady, OnRenderViewReady)
445     IPC_MESSAGE_HANDLER(ViewHostMsg_RenderProcessGone, OnRenderProcessGone)
446     IPC_MESSAGE_HANDLER(ViewHostMsg_Close, OnClose)
447     IPC_MESSAGE_HANDLER(ViewHostMsg_UpdateScreenRects_ACK,
448                         OnUpdateScreenRectsAck)
449     IPC_MESSAGE_HANDLER(ViewHostMsg_RequestMove, OnRequestMove)
450     IPC_MESSAGE_HANDLER(ViewHostMsg_SetTooltipText, OnSetTooltipText)
451     IPC_MESSAGE_HANDLER_GENERIC(ViewHostMsg_SwapCompositorFrame,
452                                 OnSwapCompositorFrame(msg))
453     IPC_MESSAGE_HANDLER(ViewHostMsg_DidStopFlinging, OnFlingingStopped)
454     IPC_MESSAGE_HANDLER(ViewHostMsg_UpdateRect, OnUpdateRect)
455     IPC_MESSAGE_HANDLER(ViewHostMsg_Focus, OnFocus)
456     IPC_MESSAGE_HANDLER(ViewHostMsg_Blur, OnBlur)
457     IPC_MESSAGE_HANDLER(ViewHostMsg_SetCursor, OnSetCursor)
458     IPC_MESSAGE_HANDLER(ViewHostMsg_TextInputTypeChanged,
459                         OnTextInputTypeChanged)
460     IPC_MESSAGE_HANDLER(ViewHostMsg_LockMouse, OnLockMouse)
461     IPC_MESSAGE_HANDLER(ViewHostMsg_UnlockMouse, OnUnlockMouse)
462     IPC_MESSAGE_HANDLER(ViewHostMsg_ShowDisambiguationPopup,
463                         OnShowDisambiguationPopup)
464     IPC_MESSAGE_HANDLER(ViewHostMsg_SelectionChanged, OnSelectionChanged)
465     IPC_MESSAGE_HANDLER(ViewHostMsg_SelectionBoundsChanged,
466                         OnSelectionBoundsChanged)
467 #if defined(OS_WIN)
468     IPC_MESSAGE_HANDLER(ViewHostMsg_WindowlessPluginDummyWindowCreated,
469                         OnWindowlessPluginDummyWindowCreated)
470     IPC_MESSAGE_HANDLER(ViewHostMsg_WindowlessPluginDummyWindowDestroyed,
471                         OnWindowlessPluginDummyWindowDestroyed)
472 #endif
473 #if defined(OS_MACOSX) || defined(USE_AURA)
474     IPC_MESSAGE_HANDLER(InputHostMsg_ImeCompositionRangeChanged,
475                         OnImeCompositionRangeChanged)
476 #endif
477     IPC_MESSAGE_UNHANDLED(handled = false)
478   IPC_END_MESSAGE_MAP()
479
480   if (!handled && input_router_ && input_router_->OnMessageReceived(msg))
481     return true;
482
483   if (!handled && view_ && view_->OnMessageReceived(msg))
484     return true;
485
486   return handled;
487 }
488
489 bool RenderWidgetHostImpl::Send(IPC::Message* msg) {
490   if (IPC_MESSAGE_ID_CLASS(msg->type()) == InputMsgStart)
491     return input_router_->SendInput(make_scoped_ptr(msg));
492
493   return process_->Send(msg);
494 }
495
496 void RenderWidgetHostImpl::SetIsLoading(bool is_loading) {
497   is_loading_ = is_loading;
498   if (!view_)
499     return;
500   view_->SetIsLoading(is_loading);
501 }
502
503 void RenderWidgetHostImpl::WasHidden() {
504   if (is_hidden_)
505     return;
506
507   is_hidden_ = true;
508
509   // Don't bother reporting hung state when we aren't active.
510   StopHangMonitorTimeout();
511
512   // If we have a renderer, then inform it that we are being hidden so it can
513   // reduce its resource utilization.
514   Send(new ViewMsg_WasHidden(routing_id_));
515
516   // Tell the RenderProcessHost we were hidden.
517   process_->WidgetHidden();
518
519   bool is_visible = false;
520   NotificationService::current()->Notify(
521       NOTIFICATION_RENDER_WIDGET_VISIBILITY_CHANGED,
522       Source<RenderWidgetHost>(this),
523       Details<bool>(&is_visible));
524 }
525
526 void RenderWidgetHostImpl::WasShown(const ui::LatencyInfo& latency_info) {
527   if (!is_hidden_)
528     return;
529   is_hidden_ = false;
530
531   SendScreenRects();
532
533   // Always repaint on restore.
534   bool needs_repainting = true;
535   needs_repainting_on_restore_ = false;
536   Send(new ViewMsg_WasShown(routing_id_, needs_repainting, latency_info));
537
538   process_->WidgetRestored();
539
540   bool is_visible = true;
541   NotificationService::current()->Notify(
542       NOTIFICATION_RENDER_WIDGET_VISIBILITY_CHANGED,
543       Source<RenderWidgetHost>(this),
544       Details<bool>(&is_visible));
545
546   // It's possible for our size to be out of sync with the renderer. The
547   // following is one case that leads to this:
548   // 1. WasResized -> Send ViewMsg_Resize to render
549   // 2. WasResized -> do nothing as resize_ack_pending_ is true
550   // 3. WasHidden
551   // 4. OnUpdateRect from (1) processed. Does NOT invoke WasResized as view
552   //    is hidden. Now renderer/browser out of sync with what they think size
553   //    is.
554   // By invoking WasResized the renderer is updated as necessary. WasResized
555   // does nothing if the sizes are already in sync.
556   //
557   // TODO: ideally ViewMsg_WasShown would take a size. This way, the renderer
558   // could handle both the restore and resize at once. This isn't that big a
559   // deal as RenderWidget::WasShown delays updating, so that the resize from
560   // WasResized is usually processed before the renderer is painted.
561   WasResized();
562 }
563
564 void RenderWidgetHostImpl::WasResized() {
565   // Skip if the |delegate_| has already been detached because
566   // it's web contents is being deleted.
567   if (resize_ack_pending_ || !process_->HasConnection() || !view_ ||
568       !renderer_initialized_ || should_auto_resize_ || !delegate_) {
569     return;
570   }
571
572   gfx::Size new_size(view_->GetRequestedRendererSize());
573
574   gfx::Size old_physical_backing_size = physical_backing_size_;
575   physical_backing_size_ = view_->GetPhysicalBackingSize();
576   bool was_fullscreen = is_fullscreen_;
577   is_fullscreen_ = IsFullscreen();
578   float old_top_controls_layout_height =
579       top_controls_layout_height_;
580   top_controls_layout_height_ =
581       view_->GetTopControlsLayoutHeight();
582   gfx::Size old_visible_viewport_size = visible_viewport_size_;
583   visible_viewport_size_ = view_->GetVisibleViewportSize();
584
585   bool size_changed = new_size != last_requested_size_;
586   bool side_payload_changed =
587       screen_info_out_of_date_ ||
588       old_physical_backing_size != physical_backing_size_ ||
589       was_fullscreen != is_fullscreen_ ||
590       old_top_controls_layout_height !=
591           top_controls_layout_height_ ||
592       old_visible_viewport_size != visible_viewport_size_;
593
594   if (!size_changed && !side_payload_changed)
595     return;
596
597   if (!screen_info_) {
598     screen_info_.reset(new blink::WebScreenInfo);
599     GetWebScreenInfo(screen_info_.get());
600   }
601
602   // We don't expect to receive an ACK when the requested size or the physical
603   // backing size is empty, or when the main viewport size didn't change.
604   if (!new_size.IsEmpty() && !physical_backing_size_.IsEmpty() && size_changed)
605     resize_ack_pending_ = g_check_for_pending_resize_ack;
606
607   ViewMsg_Resize_Params params;
608   params.screen_info = *screen_info_;
609   params.new_size = new_size;
610   params.physical_backing_size = physical_backing_size_;
611   params.top_controls_layout_height = top_controls_layout_height_;
612   params.visible_viewport_size = visible_viewport_size_;
613   params.resizer_rect = GetRootWindowResizerRect();
614   params.is_fullscreen = is_fullscreen_;
615   if (!Send(new ViewMsg_Resize(routing_id_, params))) {
616     resize_ack_pending_ = false;
617   } else {
618     last_requested_size_ = new_size;
619   }
620 }
621
622 void RenderWidgetHostImpl::ResizeRectChanged(const gfx::Rect& new_rect) {
623   Send(new ViewMsg_ChangeResizeRect(routing_id_, new_rect));
624 }
625
626 void RenderWidgetHostImpl::GotFocus() {
627   Focus();
628 }
629
630 void RenderWidgetHostImpl::Focus() {
631   Send(new InputMsg_SetFocus(routing_id_, true));
632 }
633
634 void RenderWidgetHostImpl::Blur() {
635   // If there is a pending mouse lock request, we don't want to reject it at
636   // this point. The user can switch focus back to this view and approve the
637   // request later.
638   if (IsMouseLocked())
639     view_->UnlockMouse();
640
641   if (touch_emulator_)
642     touch_emulator_->CancelTouch();
643
644   Send(new InputMsg_SetFocus(routing_id_, false));
645 }
646
647 void RenderWidgetHostImpl::LostCapture() {
648   if (touch_emulator_)
649     touch_emulator_->CancelTouch();
650
651   Send(new InputMsg_MouseCaptureLost(routing_id_));
652 }
653
654 void RenderWidgetHostImpl::SetActive(bool active) {
655   Send(new ViewMsg_SetActive(routing_id_, active));
656 }
657
658 void RenderWidgetHostImpl::LostMouseLock() {
659   Send(new ViewMsg_MouseLockLost(routing_id_));
660 }
661
662 void RenderWidgetHostImpl::ViewDestroyed() {
663   RejectMouseLockOrUnlockIfNecessary();
664
665   // TODO(evanm): tracking this may no longer be necessary;
666   // eliminate this function if so.
667   SetView(NULL);
668 }
669
670 void RenderWidgetHostImpl::CopyFromBackingStore(
671     const gfx::Rect& src_subrect,
672     const gfx::Size& accelerated_dst_size,
673     const base::Callback<void(bool, const SkBitmap&)>& callback,
674     const SkColorType color_type) {
675   if (view_) {
676     TRACE_EVENT0("browser",
677         "RenderWidgetHostImpl::CopyFromBackingStore::FromCompositingSurface");
678     gfx::Rect accelerated_copy_rect = src_subrect.IsEmpty() ?
679         gfx::Rect(view_->GetViewBounds().size()) : src_subrect;
680     view_->CopyFromCompositingSurface(
681         accelerated_copy_rect, accelerated_dst_size, callback, color_type);
682     return;
683   }
684
685   callback.Run(false, SkBitmap());
686 }
687
688 bool RenderWidgetHostImpl::CanCopyFromBackingStore() {
689   if (view_)
690     return view_->IsSurfaceAvailableForCopy();
691   return false;
692 }
693
694 #if defined(OS_ANDROID)
695 void RenderWidgetHostImpl::LockBackingStore() {
696   if (view_)
697     view_->LockCompositingSurface();
698 }
699
700 void RenderWidgetHostImpl::UnlockBackingStore() {
701   if (view_)
702     view_->UnlockCompositingSurface();
703 }
704 #endif
705
706 #if defined(OS_MACOSX)
707 void RenderWidgetHostImpl::PauseForPendingResizeOrRepaints() {
708   TRACE_EVENT0("browser",
709       "RenderWidgetHostImpl::PauseForPendingResizeOrRepaints");
710
711   if (!CanPauseForPendingResizeOrRepaints())
712     return;
713
714   WaitForSurface();
715 }
716
717 bool RenderWidgetHostImpl::CanPauseForPendingResizeOrRepaints() {
718   // Do not pause if the view is hidden.
719   if (is_hidden())
720     return false;
721
722   // Do not pause if there is not a paint or resize already coming.
723   if (!repaint_ack_pending_ && !resize_ack_pending_)
724     return false;
725
726   return true;
727 }
728
729 void RenderWidgetHostImpl::WaitForSurface() {
730   TRACE_EVENT0("browser", "RenderWidgetHostImpl::WaitForSurface");
731
732   // How long to (synchronously) wait for the renderer to respond with a
733   // new frame when our current frame doesn't exist or is the wrong size.
734   // This timeout impacts the "choppiness" of our window resize.
735   const int kPaintMsgTimeoutMS = 50;
736
737   if (!view_)
738     return;
739
740   // The view_size will be current_size_ for auto-sized views and otherwise the
741   // size of the view_. (For auto-sized views, current_size_ is updated during
742   // UpdateRect messages.)
743   gfx::Size view_size = current_size_;
744   if (!should_auto_resize_) {
745     // Get the desired size from the current view bounds.
746     gfx::Rect view_rect = view_->GetViewBounds();
747     if (view_rect.IsEmpty())
748       return;
749     view_size = view_rect.size();
750   }
751
752   TRACE_EVENT2("renderer_host",
753                "RenderWidgetHostImpl::WaitForBackingStore",
754                "width",
755                base::IntToString(view_size.width()),
756                "height",
757                base::IntToString(view_size.height()));
758
759   // We should not be asked to paint while we are hidden.  If we are hidden,
760   // then it means that our consumer failed to call WasShown. If we're not
761   // force creating the backing store, it's OK since we can feel free to give
762   // out our cached one if we have it.
763   DCHECK(!is_hidden_) << "WaitForSurface called while hidden!";
764
765   // We should never be called recursively; this can theoretically lead to
766   // infinite recursion and almost certainly leads to lower performance.
767   DCHECK(!in_get_backing_store_) << "WaitForSurface called recursively!";
768   base::AutoReset<bool> auto_reset_in_get_backing_store(
769       &in_get_backing_store_, true);
770
771   // We might have a surface that we can use!
772   if (view_->HasAcceleratedSurface(view_size))
773     return;
774
775   // We do not have a suitable backing store in the cache, so send out a
776   // request to the renderer to paint the view if required.
777   if (!repaint_ack_pending_ && !resize_ack_pending_) {
778     repaint_start_time_ = TimeTicks::Now();
779     repaint_ack_pending_ = true;
780     TRACE_EVENT_ASYNC_BEGIN0(
781         "renderer_host", "RenderWidgetHostImpl::repaint_ack_pending_", this);
782     Send(new ViewMsg_Repaint(routing_id_, view_size));
783   }
784
785   TimeDelta max_delay = TimeDelta::FromMilliseconds(kPaintMsgTimeoutMS);
786   TimeTicks end_time = TimeTicks::Now() + max_delay;
787   do {
788     TRACE_EVENT0("renderer_host", "WaitForSurface::WaitForUpdate");
789
790     // When we have asked the RenderWidget to resize, and we are still waiting
791     // on a response, block for a little while to see if we can't get a response
792     // before returning the old (incorrectly sized) backing store.
793     IPC::Message msg;
794     if (RenderWidgetResizeHelper::Get()->WaitForSingleTaskToRun(max_delay)) {
795
796       // For auto-resized views, current_size_ determines the view_size and it
797       // may have changed during the handling of an UpdateRect message.
798       if (should_auto_resize_)
799         view_size = current_size_;
800
801       // Break now if we got a backing store or accelerated surface of the
802       // correct size.
803       if (view_->HasAcceleratedSurface(view_size))
804         return;
805     } else {
806       TRACE_EVENT0("renderer_host", "WaitForSurface::Timeout");
807       break;
808     }
809
810     // Loop if we still have time left and haven't gotten a properly sized
811     // BackingStore yet. This is necessary to support the GPU path which
812     // typically has multiple frames pipelined -- we may need to skip one or two
813     // BackingStore messages to get to the latest.
814     max_delay = end_time - TimeTicks::Now();
815   } while (max_delay > TimeDelta::FromSeconds(0));
816 }
817 #endif
818
819 bool RenderWidgetHostImpl::ScheduleComposite() {
820   if (is_hidden_ || current_size_.IsEmpty() || repaint_ack_pending_ ||
821       resize_ack_pending_) {
822     return false;
823   }
824
825   // Send out a request to the renderer to paint the view if required.
826   repaint_start_time_ = TimeTicks::Now();
827   repaint_ack_pending_ = true;
828   TRACE_EVENT_ASYNC_BEGIN0(
829       "renderer_host", "RenderWidgetHostImpl::repaint_ack_pending_", this);
830   Send(new ViewMsg_Repaint(routing_id_, current_size_));
831   return true;
832 }
833
834 void RenderWidgetHostImpl::StartHangMonitorTimeout(base::TimeDelta delay) {
835   if (hang_monitor_timeout_)
836     hang_monitor_timeout_->Start(delay);
837 }
838
839 void RenderWidgetHostImpl::RestartHangMonitorTimeout() {
840   if (hang_monitor_timeout_)
841     hang_monitor_timeout_->Restart(
842         base::TimeDelta::FromMilliseconds(hung_renderer_delay_ms_));
843 }
844
845 void RenderWidgetHostImpl::StopHangMonitorTimeout() {
846   if (hang_monitor_timeout_)
847     hang_monitor_timeout_->Stop();
848   RendererIsResponsive();
849 }
850
851 void RenderWidgetHostImpl::ForwardMouseEvent(const WebMouseEvent& mouse_event) {
852   ForwardMouseEventWithLatencyInfo(mouse_event, ui::LatencyInfo());
853 }
854
855 void RenderWidgetHostImpl::ForwardMouseEventWithLatencyInfo(
856       const blink::WebMouseEvent& mouse_event,
857       const ui::LatencyInfo& ui_latency) {
858   TRACE_EVENT2("input", "RenderWidgetHostImpl::ForwardMouseEvent",
859                "x", mouse_event.x, "y", mouse_event.y);
860   ui::LatencyInfo::InputCoordinate logical_coordinate(mouse_event.x,
861                                                       mouse_event.y);
862
863   ui::LatencyInfo latency_info = CreateRWHLatencyInfoIfNotExist(
864       &ui_latency, mouse_event.type, &logical_coordinate, 1);
865
866   for (size_t i = 0; i < mouse_event_callbacks_.size(); ++i) {
867     if (mouse_event_callbacks_[i].Run(mouse_event))
868       return;
869   }
870
871   if (IgnoreInputEvents())
872     return;
873
874   if (touch_emulator_ && touch_emulator_->HandleMouseEvent(mouse_event))
875     return;
876
877   input_router_->SendMouseEvent(MouseEventWithLatencyInfo(mouse_event,
878                                                           latency_info));
879 }
880
881 void RenderWidgetHostImpl::OnPointerEventActivate() {
882 }
883
884 void RenderWidgetHostImpl::ForwardWheelEvent(
885     const WebMouseWheelEvent& wheel_event) {
886   ForwardWheelEventWithLatencyInfo(wheel_event, ui::LatencyInfo());
887 }
888
889 void RenderWidgetHostImpl::ForwardWheelEventWithLatencyInfo(
890       const blink::WebMouseWheelEvent& wheel_event,
891       const ui::LatencyInfo& ui_latency) {
892   TRACE_EVENT0("input", "RenderWidgetHostImpl::ForwardWheelEvent");
893
894   ui::LatencyInfo::InputCoordinate logical_coordinate(wheel_event.x,
895                                                       wheel_event.y);
896
897   ui::LatencyInfo latency_info = CreateRWHLatencyInfoIfNotExist(
898       &ui_latency, wheel_event.type, &logical_coordinate, 1);
899
900   if (IgnoreInputEvents())
901     return;
902
903   if (touch_emulator_ && touch_emulator_->HandleMouseWheelEvent(wheel_event))
904     return;
905
906   input_router_->SendWheelEvent(MouseWheelEventWithLatencyInfo(wheel_event,
907                                                                latency_info));
908 }
909
910 void RenderWidgetHostImpl::ForwardGestureEvent(
911     const blink::WebGestureEvent& gesture_event) {
912   ForwardGestureEventWithLatencyInfo(gesture_event, ui::LatencyInfo());
913 }
914
915 void RenderWidgetHostImpl::ForwardGestureEventWithLatencyInfo(
916     const blink::WebGestureEvent& gesture_event,
917     const ui::LatencyInfo& ui_latency) {
918   TRACE_EVENT0("input", "RenderWidgetHostImpl::ForwardGestureEvent");
919   // Early out if necessary, prior to performing latency logic.
920   if (IgnoreInputEvents())
921     return;
922
923   if (delegate_->PreHandleGestureEvent(gesture_event))
924     return;
925
926   ui::LatencyInfo::InputCoordinate logical_coordinate(gesture_event.x,
927                                                       gesture_event.y);
928
929   ui::LatencyInfo latency_info = CreateRWHLatencyInfoIfNotExist(
930       &ui_latency, gesture_event.type, &logical_coordinate, 1);
931
932   if (gesture_event.type == blink::WebInputEvent::GestureScrollUpdate) {
933     latency_info.AddLatencyNumber(
934         ui::INPUT_EVENT_LATENCY_SCROLL_UPDATE_RWH_COMPONENT,
935         GetLatencyComponentId(),
936         ++last_input_number_);
937
938     // Make a copy of the INPUT_EVENT_LATENCY_ORIGINAL_COMPONENT with a
939     // different name INPUT_EVENT_LATENCY_SCROLL_UPDATE_ORIGINAL_COMPONENT.
940     // So we can track the latency specifically for scroll update events.
941     ui::LatencyInfo::LatencyComponent original_component;
942     if (latency_info.FindLatency(ui::INPUT_EVENT_LATENCY_ORIGINAL_COMPONENT,
943                                  0,
944                                  &original_component)) {
945       latency_info.AddLatencyNumberWithTimestamp(
946           ui::INPUT_EVENT_LATENCY_SCROLL_UPDATE_ORIGINAL_COMPONENT,
947           GetLatencyComponentId(),
948           original_component.sequence_number,
949           original_component.event_time,
950           original_component.event_count);
951     }
952   }
953
954   GestureEventWithLatencyInfo gesture_with_latency(gesture_event, latency_info);
955   input_router_->SendGestureEvent(gesture_with_latency);
956 }
957
958 void RenderWidgetHostImpl::ForwardEmulatedTouchEvent(
959       const blink::WebTouchEvent& touch_event) {
960   TRACE_EVENT0("input", "RenderWidgetHostImpl::ForwardEmulatedTouchEvent");
961
962   ui::LatencyInfo::InputCoordinate
963       logical_coordinates[ui::LatencyInfo::kMaxInputCoordinates];
964   size_t logical_coordinates_size =
965       std::min(arraysize(logical_coordinates),
966                static_cast<size_t>(touch_event.touchesLength));
967   for (size_t i = 0; i < logical_coordinates_size; i++) {
968     logical_coordinates[i] = ui::LatencyInfo::InputCoordinate(
969         touch_event.touches[i].position.x, touch_event.touches[i].position.y);
970   }
971
972   ui::LatencyInfo latency_info = CreateRWHLatencyInfoIfNotExist(
973       NULL, touch_event.type, logical_coordinates, logical_coordinates_size);
974   TouchEventWithLatencyInfo touch_with_latency(touch_event, latency_info);
975   input_router_->SendTouchEvent(touch_with_latency);
976 }
977
978 void RenderWidgetHostImpl::ForwardTouchEventWithLatencyInfo(
979       const blink::WebTouchEvent& touch_event,
980       const ui::LatencyInfo& ui_latency) {
981   TRACE_EVENT0("input", "RenderWidgetHostImpl::ForwardTouchEvent");
982
983   // Always forward TouchEvents for touch stream consistency. They will be
984   // ignored if appropriate in FilterInputEvent().
985
986   ui::LatencyInfo::InputCoordinate
987       logical_coordinates[ui::LatencyInfo::kMaxInputCoordinates];
988   size_t logical_coordinates_size =
989       std::min(arraysize(logical_coordinates),
990                static_cast<size_t>(touch_event.touchesLength));
991   for (size_t i = 0; i < logical_coordinates_size; i++) {
992     logical_coordinates[i] = ui::LatencyInfo::InputCoordinate(
993         touch_event.touches[i].position.x, touch_event.touches[i].position.y);
994   }
995
996   ui::LatencyInfo latency_info =
997       CreateRWHLatencyInfoIfNotExist(&ui_latency,
998                                      touch_event.type,
999                                      logical_coordinates,
1000                                      logical_coordinates_size);
1001   TouchEventWithLatencyInfo touch_with_latency(touch_event, latency_info);
1002
1003   if (touch_emulator_ &&
1004       touch_emulator_->HandleTouchEvent(touch_with_latency.event)) {
1005     if (view_) {
1006       view_->ProcessAckedTouchEvent(
1007           touch_with_latency, INPUT_EVENT_ACK_STATE_CONSUMED);
1008     }
1009     return;
1010   }
1011
1012   input_router_->SendTouchEvent(touch_with_latency);
1013 }
1014
1015 void RenderWidgetHostImpl::ForwardKeyboardEvent(
1016     const NativeWebKeyboardEvent& key_event) {
1017   TRACE_EVENT0("input", "RenderWidgetHostImpl::ForwardKeyboardEvent");
1018   if (IgnoreInputEvents())
1019     return;
1020
1021   if (!process_->HasConnection())
1022     return;
1023
1024   // First, let keypress listeners take a shot at handling the event.  If a
1025   // listener handles the event, it should not be propagated to the renderer.
1026   if (KeyPressListenersHandleEvent(key_event)) {
1027     // Some keypresses that are accepted by the listener might have follow up
1028     // char events, which should be ignored.
1029     if (key_event.type == WebKeyboardEvent::RawKeyDown)
1030       suppress_next_char_events_ = true;
1031     return;
1032   }
1033
1034   if (key_event.type == WebKeyboardEvent::Char &&
1035       (key_event.windowsKeyCode == ui::VKEY_RETURN ||
1036        key_event.windowsKeyCode == ui::VKEY_SPACE)) {
1037     OnUserGesture();
1038   }
1039
1040   // Double check the type to make sure caller hasn't sent us nonsense that
1041   // will mess up our key queue.
1042   if (!WebInputEvent::isKeyboardEventType(key_event.type))
1043     return;
1044
1045   if (suppress_next_char_events_) {
1046     // If preceding RawKeyDown event was handled by the browser, then we need
1047     // suppress all Char events generated by it. Please note that, one
1048     // RawKeyDown event may generate multiple Char events, so we can't reset
1049     // |suppress_next_char_events_| until we get a KeyUp or a RawKeyDown.
1050     if (key_event.type == WebKeyboardEvent::Char)
1051       return;
1052     // We get a KeyUp or a RawKeyDown event.
1053     suppress_next_char_events_ = false;
1054   }
1055
1056   bool is_shortcut = false;
1057
1058   // Only pre-handle the key event if it's not handled by the input method.
1059   if (delegate_ && !key_event.skip_in_browser) {
1060     // We need to set |suppress_next_char_events_| to true if
1061     // PreHandleKeyboardEvent() returns true, but |this| may already be
1062     // destroyed at that time. So set |suppress_next_char_events_| true here,
1063     // then revert it afterwards when necessary.
1064     if (key_event.type == WebKeyboardEvent::RawKeyDown)
1065       suppress_next_char_events_ = true;
1066
1067     // Tab switching/closing accelerators aren't sent to the renderer to avoid
1068     // a hung/malicious renderer from interfering.
1069     if (delegate_->PreHandleKeyboardEvent(key_event, &is_shortcut))
1070       return;
1071
1072     if (key_event.type == WebKeyboardEvent::RawKeyDown)
1073       suppress_next_char_events_ = false;
1074   }
1075
1076   if (touch_emulator_ && touch_emulator_->HandleKeyboardEvent(key_event))
1077     return;
1078
1079   input_router_->SendKeyboardEvent(
1080       key_event,
1081       CreateRWHLatencyInfoIfNotExist(NULL, key_event.type, NULL, 0),
1082       is_shortcut);
1083 }
1084
1085 void RenderWidgetHostImpl::QueueSyntheticGesture(
1086     scoped_ptr<SyntheticGesture> synthetic_gesture,
1087     const base::Callback<void(SyntheticGesture::Result)>& on_complete) {
1088   if (!synthetic_gesture_controller_ && view_) {
1089     synthetic_gesture_controller_.reset(
1090         new SyntheticGestureController(
1091             view_->CreateSyntheticGestureTarget().Pass()));
1092   }
1093   if (synthetic_gesture_controller_) {
1094     synthetic_gesture_controller_->QueueSyntheticGesture(
1095         synthetic_gesture.Pass(), on_complete);
1096   }
1097 }
1098
1099 void RenderWidgetHostImpl::SetCursor(const WebCursor& cursor) {
1100   if (!view_)
1101     return;
1102   view_->UpdateCursor(cursor);
1103 }
1104
1105 void RenderWidgetHostImpl::ShowContextMenuAtPoint(const gfx::Point& point) {
1106   Send(new ViewMsg_ShowContextMenu(
1107       GetRoutingID(), ui::MENU_SOURCE_MOUSE, point));
1108 }
1109
1110 void RenderWidgetHostImpl::SendCursorVisibilityState(bool is_visible) {
1111   Send(new InputMsg_CursorVisibilityChange(GetRoutingID(), is_visible));
1112 }
1113
1114 int64 RenderWidgetHostImpl::GetLatencyComponentId() {
1115   return GetRoutingID() | (static_cast<int64>(GetProcess()->GetID()) << 32);
1116 }
1117
1118 // static
1119 void RenderWidgetHostImpl::DisableResizeAckCheckForTesting() {
1120   g_check_for_pending_resize_ack = false;
1121 }
1122
1123 ui::LatencyInfo RenderWidgetHostImpl::CreateRWHLatencyInfoIfNotExist(
1124     const ui::LatencyInfo* original,
1125     WebInputEvent::Type type,
1126     const ui::LatencyInfo::InputCoordinate* logical_coordinates,
1127     size_t logical_coordinates_size) {
1128   ui::LatencyInfo info;
1129   if (original)
1130     info = *original;
1131   // In Aura, gesture event will already carry its original touch event's
1132   // INPUT_EVENT_LATENCY_RWH_COMPONENT.
1133   if (!info.FindLatency(ui::INPUT_EVENT_LATENCY_BEGIN_RWH_COMPONENT,
1134                         GetLatencyComponentId(),
1135                         NULL)) {
1136     info.AddLatencyNumber(ui::INPUT_EVENT_LATENCY_BEGIN_RWH_COMPONENT,
1137                           GetLatencyComponentId(),
1138                           ++last_input_number_);
1139     info.TraceEventType(WebInputEventTraits::GetName(type));
1140
1141     // Convert logical coordinates to physical coordinates, based on the
1142     // device scale factor.
1143     float device_scale_factor =
1144         screen_info_ ? screen_info_->deviceScaleFactor : 1;
1145     DCHECK(logical_coordinates_size <= ui::LatencyInfo::kMaxInputCoordinates);
1146     info.input_coordinates_size = logical_coordinates_size;
1147     for (size_t i = 0; i < info.input_coordinates_size; i++) {
1148       info.input_coordinates[i].x =
1149           logical_coordinates[i].x * device_scale_factor;
1150       info.input_coordinates[i].y =
1151           logical_coordinates[i].y * device_scale_factor;
1152     }
1153   }
1154
1155   return info;
1156 }
1157
1158
1159 void RenderWidgetHostImpl::AddKeyPressEventCallback(
1160     const KeyPressEventCallback& callback) {
1161   key_press_event_callbacks_.push_back(callback);
1162 }
1163
1164 void RenderWidgetHostImpl::RemoveKeyPressEventCallback(
1165     const KeyPressEventCallback& callback) {
1166   for (size_t i = 0; i < key_press_event_callbacks_.size(); ++i) {
1167     if (key_press_event_callbacks_[i].Equals(callback)) {
1168       key_press_event_callbacks_.erase(
1169           key_press_event_callbacks_.begin() + i);
1170       return;
1171     }
1172   }
1173 }
1174
1175 void RenderWidgetHostImpl::AddMouseEventCallback(
1176     const MouseEventCallback& callback) {
1177   mouse_event_callbacks_.push_back(callback);
1178 }
1179
1180 void RenderWidgetHostImpl::RemoveMouseEventCallback(
1181     const MouseEventCallback& callback) {
1182   for (size_t i = 0; i < mouse_event_callbacks_.size(); ++i) {
1183     if (mouse_event_callbacks_[i].Equals(callback)) {
1184       mouse_event_callbacks_.erase(mouse_event_callbacks_.begin() + i);
1185       return;
1186     }
1187   }
1188 }
1189
1190 void RenderWidgetHostImpl::GetWebScreenInfo(blink::WebScreenInfo* result) {
1191   TRACE_EVENT0("renderer_host", "RenderWidgetHostImpl::GetWebScreenInfo");
1192   if (view_)
1193     view_->GetScreenInfo(result);
1194   else
1195     RenderWidgetHostViewBase::GetDefaultScreenInfo(result);
1196   screen_info_out_of_date_ = false;
1197 }
1198
1199 const NativeWebKeyboardEvent*
1200     RenderWidgetHostImpl::GetLastKeyboardEvent() const {
1201   return input_router_->GetLastKeyboardEvent();
1202 }
1203
1204 void RenderWidgetHostImpl::NotifyScreenInfoChanged() {
1205   // The resize message (which may not happen immediately) will carry with it
1206   // the screen info as well as the new size (if the screen has changed scale
1207   // factor).
1208   InvalidateScreenInfo();
1209   WasResized();
1210 }
1211
1212 void RenderWidgetHostImpl::InvalidateScreenInfo() {
1213   screen_info_out_of_date_ = true;
1214   screen_info_.reset();
1215 }
1216
1217 void RenderWidgetHostImpl::GetSnapshotFromBrowser(
1218     const base::Callback<void(const unsigned char*,size_t)> callback) {
1219   int id = next_browser_snapshot_id_++;
1220   pending_browser_snapshots_.insert(std::make_pair(id, callback));
1221   Send(new ViewMsg_ForceRedraw(GetRoutingID(), id));
1222 }
1223
1224 void RenderWidgetHostImpl::OnSelectionChanged(const base::string16& text,
1225                                               size_t offset,
1226                                               const gfx::Range& range) {
1227   if (view_)
1228     view_->SelectionChanged(text, offset, range);
1229 }
1230
1231 void RenderWidgetHostImpl::OnSelectionBoundsChanged(
1232     const ViewHostMsg_SelectionBounds_Params& params) {
1233   if (view_) {
1234     view_->SelectionBoundsChanged(params);
1235   }
1236 }
1237
1238 void RenderWidgetHostImpl::UpdateVSyncParameters(base::TimeTicks timebase,
1239                                                  base::TimeDelta interval) {
1240   Send(new ViewMsg_UpdateVSyncParameters(GetRoutingID(), timebase, interval));
1241 }
1242
1243 void RenderWidgetHostImpl::RendererExited(base::TerminationStatus status,
1244                                           int exit_code) {
1245   // Clearing this flag causes us to re-create the renderer when recovering
1246   // from a crashed renderer.
1247   renderer_initialized_ = false;
1248
1249   waiting_for_screen_rects_ack_ = false;
1250
1251   // Must reset these to ensure that keyboard events work with a new renderer.
1252   suppress_next_char_events_ = false;
1253
1254   // Reset some fields in preparation for recovering from a crash.
1255   ResetSizeAndRepaintPendingFlags();
1256   current_size_.SetSize(0, 0);
1257   // After the renderer crashes, the view is destroyed and so the
1258   // RenderWidgetHost cannot track its visibility anymore. We assume such
1259   // RenderWidgetHost to be visible for the sake of internal accounting - be
1260   // careful about changing this - see http://crbug.com/401859.
1261   //
1262   // We need to at least make sure that the RenderProcessHost is notified about
1263   // the |is_hidden_| change, so that the renderer will have correct visibility
1264   // set when respawned.
1265   if (is_hidden_) {
1266     process_->WidgetRestored();
1267     is_hidden_ = false;
1268   }
1269
1270   // Reset this to ensure the hung renderer mechanism is working properly.
1271   in_flight_event_count_ = 0;
1272
1273   if (view_) {
1274     GpuSurfaceTracker::Get()->SetSurfaceHandle(surface_id_,
1275                                                gfx::GLSurfaceHandle());
1276     view_->RenderProcessGone(status, exit_code);
1277     view_ = NULL; // The View should be deleted by RenderProcessGone.
1278     view_weak_.reset();
1279   }
1280
1281   // Reconstruct the input router to ensure that it has fresh state for a new
1282   // renderer. Otherwise it may be stuck waiting for the old renderer to ack an
1283   // event. (In particular, the above call to view_->RenderProcessGone will
1284   // destroy the aura window, which may dispatch a synthetic mouse move.)
1285   input_router_.reset(new InputRouterImpl(
1286       process_, this, this, routing_id_, GetInputRouterConfigForPlatform()));
1287
1288   synthetic_gesture_controller_.reset();
1289 }
1290
1291 void RenderWidgetHostImpl::UpdateTextDirection(WebTextDirection direction) {
1292   text_direction_updated_ = true;
1293   text_direction_ = direction;
1294 }
1295
1296 void RenderWidgetHostImpl::CancelUpdateTextDirection() {
1297   if (text_direction_updated_)
1298     text_direction_canceled_ = true;
1299 }
1300
1301 void RenderWidgetHostImpl::NotifyTextDirection() {
1302   if (text_direction_updated_) {
1303     if (!text_direction_canceled_)
1304       Send(new ViewMsg_SetTextDirection(GetRoutingID(), text_direction_));
1305     text_direction_updated_ = false;
1306     text_direction_canceled_ = false;
1307   }
1308 }
1309
1310 void RenderWidgetHostImpl::SetInputMethodActive(bool activate) {
1311   input_method_active_ = activate;
1312   Send(new ViewMsg_SetInputMethodActive(GetRoutingID(), activate));
1313 }
1314
1315 void RenderWidgetHostImpl::CandidateWindowShown() {
1316   Send(new ViewMsg_CandidateWindowShown(GetRoutingID()));
1317 }
1318
1319 void RenderWidgetHostImpl::CandidateWindowUpdated() {
1320   Send(new ViewMsg_CandidateWindowUpdated(GetRoutingID()));
1321 }
1322
1323 void RenderWidgetHostImpl::CandidateWindowHidden() {
1324   Send(new ViewMsg_CandidateWindowHidden(GetRoutingID()));
1325 }
1326
1327 void RenderWidgetHostImpl::ImeSetComposition(
1328     const base::string16& text,
1329     const std::vector<blink::WebCompositionUnderline>& underlines,
1330     int selection_start,
1331     int selection_end) {
1332   Send(new InputMsg_ImeSetComposition(
1333             GetRoutingID(), text, underlines, selection_start, selection_end));
1334 }
1335
1336 void RenderWidgetHostImpl::ImeConfirmComposition(
1337     const base::string16& text,
1338     const gfx::Range& replacement_range,
1339     bool keep_selection) {
1340   Send(new InputMsg_ImeConfirmComposition(
1341         GetRoutingID(), text, replacement_range, keep_selection));
1342 }
1343
1344 void RenderWidgetHostImpl::ImeCancelComposition() {
1345   Send(new InputMsg_ImeSetComposition(GetRoutingID(), base::string16(),
1346             std::vector<blink::WebCompositionUnderline>(), 0, 0));
1347 }
1348
1349 gfx::Rect RenderWidgetHostImpl::GetRootWindowResizerRect() const {
1350   return gfx::Rect();
1351 }
1352
1353 void RenderWidgetHostImpl::RequestToLockMouse(bool user_gesture,
1354                                               bool last_unlocked_by_target) {
1355   // Directly reject to lock the mouse. Subclass can override this method to
1356   // decide whether to allow mouse lock or not.
1357   GotResponseToLockMouseRequest(false);
1358 }
1359
1360 void RenderWidgetHostImpl::RejectMouseLockOrUnlockIfNecessary() {
1361   DCHECK(!pending_mouse_lock_request_ || !IsMouseLocked());
1362   if (pending_mouse_lock_request_) {
1363     pending_mouse_lock_request_ = false;
1364     Send(new ViewMsg_LockMouse_ACK(routing_id_, false));
1365   } else if (IsMouseLocked()) {
1366     view_->UnlockMouse();
1367   }
1368 }
1369
1370 bool RenderWidgetHostImpl::IsMouseLocked() const {
1371   return view_ ? view_->IsMouseLocked() : false;
1372 }
1373
1374 bool RenderWidgetHostImpl::IsFullscreen() const {
1375   return false;
1376 }
1377
1378 void RenderWidgetHostImpl::SetShouldAutoResize(bool enable) {
1379   should_auto_resize_ = enable;
1380 }
1381
1382 void RenderWidgetHostImpl::Destroy() {
1383   NotificationService::current()->Notify(
1384       NOTIFICATION_RENDER_WIDGET_HOST_DESTROYED,
1385       Source<RenderWidgetHost>(this),
1386       NotificationService::NoDetails());
1387
1388   // Tell the view to die.
1389   // Note that in the process of the view shutting down, it can call a ton
1390   // of other messages on us.  So if you do any other deinitialization here,
1391   // do it after this call to view_->Destroy().
1392   if (view_)
1393     view_->Destroy();
1394
1395   delete this;
1396 }
1397
1398 void RenderWidgetHostImpl::RendererIsUnresponsive() {
1399   NotificationService::current()->Notify(
1400       NOTIFICATION_RENDER_WIDGET_HOST_HANG,
1401       Source<RenderWidgetHost>(this),
1402       NotificationService::NoDetails());
1403   is_unresponsive_ = true;
1404   NotifyRendererUnresponsive();
1405 }
1406
1407 void RenderWidgetHostImpl::RendererIsResponsive() {
1408   if (is_unresponsive_) {
1409     is_unresponsive_ = false;
1410     NotifyRendererResponsive();
1411   }
1412 }
1413
1414 void RenderWidgetHostImpl::OnRenderViewReady() {
1415   SendScreenRects();
1416   WasResized();
1417 }
1418
1419 void RenderWidgetHostImpl::OnRenderProcessGone(int status, int exit_code) {
1420   // TODO(evanm): This synchronously ends up calling "delete this".
1421   // Is that really what we want in response to this message?  I'm matching
1422   // previous behavior of the code here.
1423   Destroy();
1424 }
1425
1426 void RenderWidgetHostImpl::OnClose() {
1427   Shutdown();
1428 }
1429
1430 void RenderWidgetHostImpl::OnSetTooltipText(
1431     const base::string16& tooltip_text,
1432     WebTextDirection text_direction_hint) {
1433   // First, add directionality marks around tooltip text if necessary.
1434   // A naive solution would be to simply always wrap the text. However, on
1435   // windows, Unicode directional embedding characters can't be displayed on
1436   // systems that lack RTL fonts and are instead displayed as empty squares.
1437   //
1438   // To get around this we only wrap the string when we deem it necessary i.e.
1439   // when the locale direction is different than the tooltip direction hint.
1440   //
1441   // Currently, we use element's directionality as the tooltip direction hint.
1442   // An alternate solution would be to set the overall directionality based on
1443   // trying to detect the directionality from the tooltip text rather than the
1444   // element direction.  One could argue that would be a preferable solution
1445   // but we use the current approach to match Fx & IE's behavior.
1446   base::string16 wrapped_tooltip_text = tooltip_text;
1447   if (!tooltip_text.empty()) {
1448     if (text_direction_hint == blink::WebTextDirectionLeftToRight) {
1449       // Force the tooltip to have LTR directionality.
1450       wrapped_tooltip_text =
1451           base::i18n::GetDisplayStringInLTRDirectionality(wrapped_tooltip_text);
1452     } else if (text_direction_hint == blink::WebTextDirectionRightToLeft &&
1453                !base::i18n::IsRTL()) {
1454       // Force the tooltip to have RTL directionality.
1455       base::i18n::WrapStringWithRTLFormatting(&wrapped_tooltip_text);
1456     }
1457   }
1458   if (GetView())
1459     view_->SetTooltipText(wrapped_tooltip_text);
1460 }
1461
1462 void RenderWidgetHostImpl::OnUpdateScreenRectsAck() {
1463   waiting_for_screen_rects_ack_ = false;
1464   if (!view_)
1465     return;
1466
1467   if (view_->GetViewBounds() == last_view_screen_rect_ &&
1468       view_->GetBoundsInRootWindow() == last_window_screen_rect_) {
1469     return;
1470   }
1471
1472   SendScreenRects();
1473 }
1474
1475 void RenderWidgetHostImpl::OnRequestMove(const gfx::Rect& pos) {
1476   if (view_) {
1477     view_->SetBounds(pos);
1478     Send(new ViewMsg_Move_ACK(routing_id_));
1479   }
1480 }
1481
1482 bool RenderWidgetHostImpl::OnSwapCompositorFrame(
1483     const IPC::Message& message) {
1484   // This trace event is used in
1485   // chrome/browser/extensions/api/cast_streaming/performance_test.cc
1486   TRACE_EVENT0("test_fps",
1487                TRACE_DISABLED_BY_DEFAULT("OnSwapCompositorFrame"));
1488   ViewHostMsg_SwapCompositorFrame::Param param;
1489   if (!ViewHostMsg_SwapCompositorFrame::Read(&message, &param))
1490     return false;
1491   scoped_ptr<cc::CompositorFrame> frame(new cc::CompositorFrame);
1492   uint32 output_surface_id = param.a;
1493   param.b.AssignTo(frame.get());
1494   std::vector<IPC::Message> messages_to_deliver_with_frame;
1495   messages_to_deliver_with_frame.swap(param.c);
1496
1497   for (size_t i = 0; i < frame->metadata.latency_info.size(); i++)
1498     AddLatencyInfoComponentIds(&frame->metadata.latency_info[i]);
1499
1500   input_router_->OnViewUpdated(
1501       GetInputRouterViewFlagsFromCompositorFrameMetadata(frame->metadata));
1502
1503   if (view_) {
1504     view_->OnSwapCompositorFrame(output_surface_id, frame.Pass());
1505     view_->DidReceiveRendererFrame();
1506   } else {
1507     cc::CompositorFrameAck ack;
1508     if (frame->gl_frame_data) {
1509       ack.gl_frame_data = frame->gl_frame_data.Pass();
1510       ack.gl_frame_data->sync_point = 0;
1511     } else if (frame->delegated_frame_data) {
1512       cc::TransferableResource::ReturnResources(
1513           frame->delegated_frame_data->resource_list,
1514           &ack.resources);
1515     } else if (frame->software_frame_data) {
1516       ack.last_software_frame_id = frame->software_frame_data->id;
1517     }
1518     SendSwapCompositorFrameAck(routing_id_, output_surface_id,
1519                                process_->GetID(), ack);
1520   }
1521
1522   RenderProcessHost* rph = GetProcess();
1523   for (std::vector<IPC::Message>::const_iterator i =
1524            messages_to_deliver_with_frame.begin();
1525        i != messages_to_deliver_with_frame.end();
1526        ++i) {
1527     rph->OnMessageReceived(*i);
1528     if (i->dispatch_error())
1529       rph->OnBadMessageReceived(*i);
1530   }
1531   messages_to_deliver_with_frame.clear();
1532
1533   return true;
1534 }
1535
1536 void RenderWidgetHostImpl::OnFlingingStopped() {
1537   if (view_)
1538     view_->DidStopFlinging();
1539 }
1540
1541 void RenderWidgetHostImpl::OnUpdateRect(
1542     const ViewHostMsg_UpdateRect_Params& params) {
1543   TRACE_EVENT0("renderer_host", "RenderWidgetHostImpl::OnUpdateRect");
1544   TimeTicks paint_start = TimeTicks::Now();
1545
1546   // Update our knowledge of the RenderWidget's size.
1547   current_size_ = params.view_size;
1548
1549   bool is_resize_ack =
1550       ViewHostMsg_UpdateRect_Flags::is_resize_ack(params.flags);
1551
1552   // resize_ack_pending_ needs to be cleared before we call DidPaintRect, since
1553   // that will end up reaching GetBackingStore.
1554   if (is_resize_ack) {
1555     DCHECK(!g_check_for_pending_resize_ack || resize_ack_pending_);
1556     resize_ack_pending_ = false;
1557   }
1558
1559   bool is_repaint_ack =
1560       ViewHostMsg_UpdateRect_Flags::is_repaint_ack(params.flags);
1561   if (is_repaint_ack) {
1562     DCHECK(repaint_ack_pending_);
1563     TRACE_EVENT_ASYNC_END0(
1564         "renderer_host", "RenderWidgetHostImpl::repaint_ack_pending_", this);
1565     repaint_ack_pending_ = false;
1566     TimeDelta delta = TimeTicks::Now() - repaint_start_time_;
1567     UMA_HISTOGRAM_TIMES("MPArch.RWH_RepaintDelta", delta);
1568   }
1569
1570   DCHECK(!params.view_size.IsEmpty());
1571
1572   DidUpdateBackingStore(params, paint_start);
1573
1574   if (should_auto_resize_) {
1575     bool post_callback = new_auto_size_.IsEmpty();
1576     new_auto_size_ = params.view_size;
1577     if (post_callback) {
1578       base::MessageLoop::current()->PostTask(
1579           FROM_HERE,
1580           base::Bind(&RenderWidgetHostImpl::DelayedAutoResized,
1581                      weak_factory_.GetWeakPtr()));
1582     }
1583   }
1584
1585   // Log the time delta for processing a paint message. On platforms that don't
1586   // support asynchronous painting, this is equivalent to
1587   // MPArch.RWH_TotalPaintTime.
1588   TimeDelta delta = TimeTicks::Now() - paint_start;
1589   UMA_HISTOGRAM_TIMES("MPArch.RWH_OnMsgUpdateRect", delta);
1590 }
1591
1592 void RenderWidgetHostImpl::DidUpdateBackingStore(
1593     const ViewHostMsg_UpdateRect_Params& params,
1594     const TimeTicks& paint_start) {
1595   TRACE_EVENT0("renderer_host", "RenderWidgetHostImpl::DidUpdateBackingStore");
1596   TimeTicks update_start = TimeTicks::Now();
1597
1598   // Move the plugins if the view hasn't already been destroyed.  Plugin moves
1599   // will not be re-issued, so must move them now, regardless of whether we
1600   // paint or not.  MovePluginWindows attempts to move the plugin windows and
1601   // in the process could dispatch other window messages which could cause the
1602   // view to be destroyed.
1603   if (view_)
1604     view_->MovePluginWindows(params.plugin_window_moves);
1605
1606   NotificationService::current()->Notify(
1607       NOTIFICATION_RENDER_WIDGET_HOST_DID_UPDATE_BACKING_STORE,
1608       Source<RenderWidgetHost>(this),
1609       NotificationService::NoDetails());
1610
1611   // We don't need to update the view if the view is hidden. We must do this
1612   // early return after the ACK is sent, however, or the renderer will not send
1613   // us more data.
1614   if (is_hidden_)
1615     return;
1616
1617   // If we got a resize ack, then perhaps we have another resize to send?
1618   bool is_resize_ack =
1619       ViewHostMsg_UpdateRect_Flags::is_resize_ack(params.flags);
1620   if (is_resize_ack)
1621     WasResized();
1622
1623   // Log the time delta for processing a paint message.
1624   TimeTicks now = TimeTicks::Now();
1625   TimeDelta delta = now - update_start;
1626   UMA_HISTOGRAM_TIMES("MPArch.RWH_DidUpdateBackingStore", delta);
1627 }
1628
1629 void RenderWidgetHostImpl::OnQueueSyntheticGesture(
1630     const SyntheticGesturePacket& gesture_packet) {
1631   // Only allow untrustworthy gestures if explicitly enabled.
1632   if (!base::CommandLine::ForCurrentProcess()->HasSwitch(
1633           cc::switches::kEnableGpuBenchmarking)) {
1634     RecordAction(base::UserMetricsAction("BadMessageTerminate_RWH7"));
1635     GetProcess()->ReceivedBadMessage();
1636     return;
1637   }
1638
1639   QueueSyntheticGesture(
1640         SyntheticGesture::Create(*gesture_packet.gesture_params()),
1641         base::Bind(&RenderWidgetHostImpl::OnSyntheticGestureCompleted,
1642                    weak_factory_.GetWeakPtr()));
1643 }
1644
1645 void RenderWidgetHostImpl::OnFocus() {
1646   // Only RenderViewHost can deal with that message.
1647   RecordAction(base::UserMetricsAction("BadMessageTerminate_RWH4"));
1648   GetProcess()->ReceivedBadMessage();
1649 }
1650
1651 void RenderWidgetHostImpl::OnBlur() {
1652   // Only RenderViewHost can deal with that message.
1653   RecordAction(base::UserMetricsAction("BadMessageTerminate_RWH5"));
1654   GetProcess()->ReceivedBadMessage();
1655 }
1656
1657 void RenderWidgetHostImpl::OnSetCursor(const WebCursor& cursor) {
1658   SetCursor(cursor);
1659 }
1660
1661 void RenderWidgetHostImpl::SetTouchEventEmulationEnabled(bool enabled) {
1662   if (enabled) {
1663     if (!touch_emulator_)
1664       touch_emulator_.reset(new TouchEmulator(this));
1665     touch_emulator_->Enable();
1666   } else {
1667     if (touch_emulator_)
1668       touch_emulator_->Disable();
1669   }
1670 }
1671
1672 void RenderWidgetHostImpl::OnTextInputTypeChanged(
1673     ui::TextInputType type,
1674     ui::TextInputMode input_mode,
1675     bool can_compose_inline) {
1676   if (view_)
1677     view_->TextInputTypeChanged(type, input_mode, can_compose_inline);
1678 }
1679
1680 #if defined(OS_MACOSX) || defined(USE_AURA)
1681 void RenderWidgetHostImpl::OnImeCompositionRangeChanged(
1682     const gfx::Range& range,
1683     const std::vector<gfx::Rect>& character_bounds) {
1684   if (view_)
1685     view_->ImeCompositionRangeChanged(range, character_bounds);
1686 }
1687 #endif
1688
1689 void RenderWidgetHostImpl::OnImeCancelComposition() {
1690   if (view_)
1691     view_->ImeCancelComposition();
1692 }
1693
1694 void RenderWidgetHostImpl::OnLockMouse(bool user_gesture,
1695                                        bool last_unlocked_by_target,
1696                                        bool privileged) {
1697
1698   if (pending_mouse_lock_request_) {
1699     Send(new ViewMsg_LockMouse_ACK(routing_id_, false));
1700     return;
1701   } else if (IsMouseLocked()) {
1702     Send(new ViewMsg_LockMouse_ACK(routing_id_, true));
1703     return;
1704   }
1705
1706   pending_mouse_lock_request_ = true;
1707   if (privileged && allow_privileged_mouse_lock_) {
1708     // Directly approve to lock the mouse.
1709     GotResponseToLockMouseRequest(true);
1710   } else {
1711     RequestToLockMouse(user_gesture, last_unlocked_by_target);
1712   }
1713 }
1714
1715 void RenderWidgetHostImpl::OnUnlockMouse() {
1716   RejectMouseLockOrUnlockIfNecessary();
1717 }
1718
1719 void RenderWidgetHostImpl::OnShowDisambiguationPopup(
1720     const gfx::Rect& rect_pixels,
1721     const gfx::Size& size,
1722     const cc::SharedBitmapId& id) {
1723   DCHECK(!rect_pixels.IsEmpty());
1724   DCHECK(!size.IsEmpty());
1725
1726   scoped_ptr<cc::SharedBitmap> bitmap =
1727       HostSharedBitmapManager::current()->GetSharedBitmapFromId(size, id);
1728   if (!bitmap) {
1729     RecordAction(base::UserMetricsAction("BadMessageTerminate_RWH6"));
1730     GetProcess()->ReceivedBadMessage();
1731     return;
1732   }
1733
1734   DCHECK(bitmap->pixels());
1735
1736   SkImageInfo info = SkImageInfo::MakeN32Premul(size.width(), size.height());
1737   SkBitmap zoomed_bitmap;
1738   zoomed_bitmap.installPixels(info, bitmap->pixels(), info.minRowBytes());
1739
1740 #if defined(OS_ANDROID) || defined(TOOLKIT_VIEWS)
1741   // Note that |rect| is in coordinates of pixels relative to the window origin.
1742   // Aura-based systems will want to convert this to DIPs.
1743   if (view_)
1744     view_->ShowDisambiguationPopup(rect_pixels, zoomed_bitmap);
1745 #else
1746   NOTIMPLEMENTED();
1747 #endif
1748
1749   // It is assumed that the disambiguation popup will make a copy of the
1750   // provided zoomed image, so we delete this one.
1751   zoomed_bitmap.setPixels(0);
1752   Send(new ViewMsg_ReleaseDisambiguationPopupBitmap(GetRoutingID(), id));
1753 }
1754
1755 #if defined(OS_WIN)
1756 void RenderWidgetHostImpl::OnWindowlessPluginDummyWindowCreated(
1757     gfx::NativeViewId dummy_activation_window) {
1758   HWND hwnd = reinterpret_cast<HWND>(dummy_activation_window);
1759
1760   // This may happen as a result of a race condition when the plugin is going
1761   // away.
1762   wchar_t window_title[MAX_PATH + 1] = {0};
1763   if (!IsWindow(hwnd) ||
1764       !GetWindowText(hwnd, window_title, arraysize(window_title)) ||
1765       lstrcmpiW(window_title, kDummyActivationWindowName) != 0) {
1766     return;
1767   }
1768
1769 #if defined(USE_AURA)
1770   SetParent(hwnd,
1771             reinterpret_cast<HWND>(view_->GetParentForWindowlessPlugin()));
1772 #else
1773   SetParent(hwnd, reinterpret_cast<HWND>(GetNativeViewId()));
1774 #endif
1775   dummy_windows_for_activation_.push_back(hwnd);
1776 }
1777
1778 void RenderWidgetHostImpl::OnWindowlessPluginDummyWindowDestroyed(
1779     gfx::NativeViewId dummy_activation_window) {
1780   HWND hwnd = reinterpret_cast<HWND>(dummy_activation_window);
1781   std::list<HWND>::iterator i = dummy_windows_for_activation_.begin();
1782   for (; i != dummy_windows_for_activation_.end(); ++i) {
1783     if ((*i) == hwnd) {
1784       dummy_windows_for_activation_.erase(i);
1785       return;
1786     }
1787   }
1788   NOTREACHED() << "Unknown dummy window";
1789 }
1790 #endif
1791
1792 void RenderWidgetHostImpl::SetIgnoreInputEvents(bool ignore_input_events) {
1793   ignore_input_events_ = ignore_input_events;
1794 }
1795
1796 bool RenderWidgetHostImpl::KeyPressListenersHandleEvent(
1797     const NativeWebKeyboardEvent& event) {
1798   if (event.skip_in_browser || event.type != WebKeyboardEvent::RawKeyDown)
1799     return false;
1800
1801   for (size_t i = 0; i < key_press_event_callbacks_.size(); i++) {
1802     size_t original_size = key_press_event_callbacks_.size();
1803     if (key_press_event_callbacks_[i].Run(event))
1804       return true;
1805
1806     // Check whether the callback that just ran removed itself, in which case
1807     // the iterator needs to be decremented to properly account for the removal.
1808     size_t current_size = key_press_event_callbacks_.size();
1809     if (current_size != original_size) {
1810       DCHECK_EQ(original_size - 1, current_size);
1811       --i;
1812     }
1813   }
1814
1815   return false;
1816 }
1817
1818 InputEventAckState RenderWidgetHostImpl::FilterInputEvent(
1819     const blink::WebInputEvent& event, const ui::LatencyInfo& latency_info) {
1820   // Don't ignore touch cancel events, since they may be sent while input
1821   // events are being ignored in order to keep the renderer from getting
1822   // confused about how many touches are active.
1823   if (IgnoreInputEvents() && event.type != WebInputEvent::TouchCancel)
1824     return INPUT_EVENT_ACK_STATE_NO_CONSUMER_EXISTS;
1825
1826   if (!process_->HasConnection())
1827     return INPUT_EVENT_ACK_STATE_UNKNOWN;
1828
1829   if (event.type == WebInputEvent::MouseDown)
1830     OnUserGesture();
1831
1832   return view_ ? view_->FilterInputEvent(event)
1833                : INPUT_EVENT_ACK_STATE_NOT_CONSUMED;
1834 }
1835
1836 void RenderWidgetHostImpl::IncrementInFlightEventCount() {
1837   StartHangMonitorTimeout(
1838       TimeDelta::FromMilliseconds(hung_renderer_delay_ms_));
1839   increment_in_flight_event_count();
1840 }
1841
1842 void RenderWidgetHostImpl::DecrementInFlightEventCount() {
1843   DCHECK_GE(in_flight_event_count_, 0);
1844   if (decrement_in_flight_event_count() <= 0) {
1845     // Cancel pending hung renderer checks since the renderer is responsive.
1846     StopHangMonitorTimeout();
1847   } else {
1848     // The renderer is responsive, but there are in-flight events to wait for.
1849     RestartHangMonitorTimeout();
1850   }
1851 }
1852
1853 void RenderWidgetHostImpl::OnHasTouchEventHandlers(bool has_handlers) {
1854   has_touch_handler_ = has_handlers;
1855 }
1856
1857 void RenderWidgetHostImpl::DidFlush() {
1858   if (synthetic_gesture_controller_)
1859     synthetic_gesture_controller_->OnDidFlushInput();
1860   if (view_)
1861     view_->OnDidFlushInput();
1862 }
1863
1864 void RenderWidgetHostImpl::DidOverscroll(const DidOverscrollParams& params) {
1865   if (view_)
1866     view_->DidOverscroll(params);
1867 }
1868
1869 void RenderWidgetHostImpl::OnKeyboardEventAck(
1870       const NativeWebKeyboardEvent& event,
1871       InputEventAckState ack_result) {
1872 #if defined(OS_MACOSX)
1873   if (!is_hidden() && view_ && view_->PostProcessEventForPluginIme(event))
1874     return;
1875 #endif
1876
1877   // We only send unprocessed key event upwards if we are not hidden,
1878   // because the user has moved away from us and no longer expect any effect
1879   // of this key event.
1880   const bool processed = (INPUT_EVENT_ACK_STATE_CONSUMED == ack_result);
1881   if (delegate_ && !processed && !is_hidden() && !event.skip_in_browser) {
1882     delegate_->HandleKeyboardEvent(event);
1883
1884     // WARNING: This RenderWidgetHostImpl can be deallocated at this point
1885     // (i.e.  in the case of Ctrl+W, where the call to
1886     // HandleKeyboardEvent destroys this RenderWidgetHostImpl).
1887   }
1888 }
1889
1890 void RenderWidgetHostImpl::OnWheelEventAck(
1891     const MouseWheelEventWithLatencyInfo& wheel_event,
1892     InputEventAckState ack_result) {
1893   if (!wheel_event.latency.FindLatency(
1894           ui::INPUT_EVENT_LATENCY_RENDERING_SCHEDULED_COMPONENT, 0, NULL)) {
1895     // MouseWheelEvent latency ends when it is acked but does not cause any
1896     // rendering scheduled.
1897     ui::LatencyInfo latency = wheel_event.latency;
1898     latency.AddLatencyNumber(
1899         ui::INPUT_EVENT_LATENCY_TERMINATED_MOUSE_COMPONENT, 0, 0);
1900   }
1901
1902   if (!is_hidden() && view_) {
1903     if (ack_result != INPUT_EVENT_ACK_STATE_CONSUMED &&
1904         delegate_->HandleWheelEvent(wheel_event.event)) {
1905       ack_result = INPUT_EVENT_ACK_STATE_CONSUMED;
1906     }
1907     view_->WheelEventAck(wheel_event.event, ack_result);
1908   }
1909 }
1910
1911 void RenderWidgetHostImpl::OnGestureEventAck(
1912     const GestureEventWithLatencyInfo& event,
1913     InputEventAckState ack_result) {
1914   if (!event.latency.FindLatency(
1915           ui::INPUT_EVENT_LATENCY_RENDERING_SCHEDULED_COMPONENT, 0, NULL)) {
1916     // GestureEvent latency ends when it is acked but does not cause any
1917     // rendering scheduled.
1918     ui::LatencyInfo latency = event.latency;
1919     latency.AddLatencyNumber(
1920         ui::INPUT_EVENT_LATENCY_TERMINATED_GESTURE_COMPONENT, 0 ,0);
1921   }
1922
1923   if (ack_result != INPUT_EVENT_ACK_STATE_CONSUMED) {
1924     if (delegate_->HandleGestureEvent(event.event))
1925       ack_result = INPUT_EVENT_ACK_STATE_CONSUMED;
1926   }
1927
1928   if (view_)
1929     view_->GestureEventAck(event.event, ack_result);
1930 }
1931
1932 void RenderWidgetHostImpl::OnTouchEventAck(
1933     const TouchEventWithLatencyInfo& event,
1934     InputEventAckState ack_result) {
1935   TouchEventWithLatencyInfo touch_event = event;
1936   touch_event.latency.AddLatencyNumber(
1937       ui::INPUT_EVENT_LATENCY_ACKED_TOUCH_COMPONENT, 0, 0);
1938   // TouchEvent latency ends at ack if it didn't cause any rendering.
1939   if (!touch_event.latency.FindLatency(
1940           ui::INPUT_EVENT_LATENCY_RENDERING_SCHEDULED_COMPONENT, 0, NULL)) {
1941     touch_event.latency.AddLatencyNumber(
1942         ui::INPUT_EVENT_LATENCY_TERMINATED_TOUCH_COMPONENT, 0, 0);
1943   }
1944   ComputeTouchLatency(touch_event.latency);
1945
1946   if (touch_emulator_ &&
1947       touch_emulator_->HandleTouchEventAck(event.event, ack_result)) {
1948     return;
1949   }
1950
1951   if (view_)
1952     view_->ProcessAckedTouchEvent(touch_event, ack_result);
1953 }
1954
1955 void RenderWidgetHostImpl::OnUnexpectedEventAck(UnexpectedEventAckType type) {
1956   if (type == BAD_ACK_MESSAGE) {
1957     RecordAction(base::UserMetricsAction("BadMessageTerminate_RWH2"));
1958     process_->ReceivedBadMessage();
1959   } else if (type == UNEXPECTED_EVENT_TYPE) {
1960     suppress_next_char_events_ = false;
1961   }
1962 }
1963
1964 void RenderWidgetHostImpl::OnSyntheticGestureCompleted(
1965     SyntheticGesture::Result result) {
1966   Send(new InputMsg_SyntheticGestureCompleted(GetRoutingID()));
1967 }
1968
1969 bool RenderWidgetHostImpl::IgnoreInputEvents() const {
1970   return ignore_input_events_ || process_->IgnoreInputEvents();
1971 }
1972
1973 bool RenderWidgetHostImpl::ShouldForwardTouchEvent() const {
1974   // It's important that the emulator sees a complete native touch stream,
1975   // allowing it to perform touch filtering as appropriate.
1976   // TODO(dgozman): Remove when touch stream forwarding issues resolved, see
1977   // crbug.com/375940.
1978   if (touch_emulator_ && touch_emulator_->enabled())
1979     return true;
1980
1981   return input_router_->ShouldForwardTouchEvent();
1982 }
1983
1984 void RenderWidgetHostImpl::StartUserGesture() {
1985   OnUserGesture();
1986 }
1987
1988 void RenderWidgetHostImpl::SetBackgroundOpaque(bool opaque) {
1989   Send(new ViewMsg_SetBackgroundOpaque(GetRoutingID(), opaque));
1990 }
1991
1992 void RenderWidgetHostImpl::SetEditCommandsForNextKeyEvent(
1993     const std::vector<EditCommand>& commands) {
1994   Send(new InputMsg_SetEditCommandsForNextKeyEvent(GetRoutingID(), commands));
1995 }
1996
1997 void RenderWidgetHostImpl::ExecuteEditCommand(const std::string& command,
1998                                               const std::string& value) {
1999   Send(new InputMsg_ExecuteEditCommand(GetRoutingID(), command, value));
2000 }
2001
2002 void RenderWidgetHostImpl::ScrollFocusedEditableNodeIntoRect(
2003     const gfx::Rect& rect) {
2004   Send(new InputMsg_ScrollFocusedEditableNodeIntoRect(GetRoutingID(), rect));
2005 }
2006
2007 void RenderWidgetHostImpl::MoveCaret(const gfx::Point& point) {
2008   Send(new InputMsg_MoveCaret(GetRoutingID(), point));
2009 }
2010
2011 bool RenderWidgetHostImpl::GotResponseToLockMouseRequest(bool allowed) {
2012   if (!allowed) {
2013     RejectMouseLockOrUnlockIfNecessary();
2014     return false;
2015   } else {
2016     if (!pending_mouse_lock_request_) {
2017       // This is possible, e.g., the plugin sends us an unlock request before
2018       // the user allows to lock to mouse.
2019       return false;
2020     }
2021
2022     pending_mouse_lock_request_ = false;
2023     if (!view_ || !view_->HasFocus()|| !view_->LockMouse()) {
2024       Send(new ViewMsg_LockMouse_ACK(routing_id_, false));
2025       return false;
2026     } else {
2027       Send(new ViewMsg_LockMouse_ACK(routing_id_, true));
2028       return true;
2029     }
2030   }
2031 }
2032
2033 // static
2034 void RenderWidgetHostImpl::AcknowledgeBufferPresent(
2035     int32 route_id, int gpu_host_id,
2036     const AcceleratedSurfaceMsg_BufferPresented_Params& params) {
2037   GpuProcessHostUIShim* ui_shim = GpuProcessHostUIShim::FromID(gpu_host_id);
2038   if (ui_shim) {
2039     ui_shim->Send(new AcceleratedSurfaceMsg_BufferPresented(route_id,
2040                                                             params));
2041   }
2042 }
2043
2044 // static
2045 void RenderWidgetHostImpl::SendSwapCompositorFrameAck(
2046     int32 route_id,
2047     uint32 output_surface_id,
2048     int renderer_host_id,
2049     const cc::CompositorFrameAck& ack) {
2050   RenderProcessHost* host = RenderProcessHost::FromID(renderer_host_id);
2051   if (!host)
2052     return;
2053   host->Send(new ViewMsg_SwapCompositorFrameAck(
2054       route_id, output_surface_id, ack));
2055 }
2056
2057 // static
2058 void RenderWidgetHostImpl::SendReclaimCompositorResources(
2059     int32 route_id,
2060     uint32 output_surface_id,
2061     int renderer_host_id,
2062     const cc::CompositorFrameAck& ack) {
2063   RenderProcessHost* host = RenderProcessHost::FromID(renderer_host_id);
2064   if (!host)
2065     return;
2066   host->Send(
2067       new ViewMsg_ReclaimCompositorResources(route_id, output_surface_id, ack));
2068 }
2069
2070 void RenderWidgetHostImpl::DelayedAutoResized() {
2071   gfx::Size new_size = new_auto_size_;
2072   // Clear the new_auto_size_ since the empty value is used as a flag to
2073   // indicate that no callback is in progress (i.e. without this line
2074   // DelayedAutoResized will not get called again).
2075   new_auto_size_.SetSize(0, 0);
2076   if (!should_auto_resize_)
2077     return;
2078
2079   OnRenderAutoResized(new_size);
2080 }
2081
2082 void RenderWidgetHostImpl::DetachDelegate() {
2083   delegate_ = NULL;
2084 }
2085
2086 void RenderWidgetHostImpl::ComputeTouchLatency(
2087     const ui::LatencyInfo& latency_info) {
2088   ui::LatencyInfo::LatencyComponent ui_component;
2089   ui::LatencyInfo::LatencyComponent rwh_component;
2090   ui::LatencyInfo::LatencyComponent acked_component;
2091
2092   if (!latency_info.FindLatency(ui::INPUT_EVENT_LATENCY_UI_COMPONENT,
2093                                 0,
2094                                 &ui_component) ||
2095       !latency_info.FindLatency(ui::INPUT_EVENT_LATENCY_BEGIN_RWH_COMPONENT,
2096                                 GetLatencyComponentId(),
2097                                 &rwh_component))
2098     return;
2099
2100   DCHECK(ui_component.event_count == 1);
2101   DCHECK(rwh_component.event_count == 1);
2102
2103   base::TimeDelta ui_delta =
2104       rwh_component.event_time - ui_component.event_time;
2105   UMA_HISTOGRAM_CUSTOM_COUNTS(
2106       "Event.Latency.Browser.TouchUI",
2107       ui_delta.InMicroseconds(),
2108       1,
2109       20000,
2110       100);
2111
2112   if (latency_info.FindLatency(ui::INPUT_EVENT_LATENCY_ACKED_TOUCH_COMPONENT,
2113                                0,
2114                                &acked_component)) {
2115     DCHECK(acked_component.event_count == 1);
2116     base::TimeDelta acked_delta =
2117         acked_component.event_time - rwh_component.event_time;
2118     UMA_HISTOGRAM_CUSTOM_COUNTS(
2119         "Event.Latency.Browser.TouchAcked",
2120         acked_delta.InMicroseconds(),
2121         1,
2122         1000000,
2123         100);
2124   }
2125 }
2126
2127 void RenderWidgetHostImpl::FrameSwapped(const ui::LatencyInfo& latency_info) {
2128   ui::LatencyInfo::LatencyComponent window_snapshot_component;
2129   if (latency_info.FindLatency(ui::WINDOW_OLD_SNAPSHOT_FRAME_NUMBER_COMPONENT,
2130                                GetLatencyComponentId(),
2131                                &window_snapshot_component)) {
2132     WindowOldSnapshotReachedScreen(
2133         static_cast<int>(window_snapshot_component.sequence_number));
2134   }
2135   if (latency_info.FindLatency(ui::WINDOW_SNAPSHOT_FRAME_NUMBER_COMPONENT,
2136                                GetLatencyComponentId(),
2137                                &window_snapshot_component)) {
2138     int sequence_number = static_cast<int>(
2139         window_snapshot_component.sequence_number);
2140 #if defined(OS_MACOSX)
2141     // On Mac, when using CoreAnmation, there is a delay between when content
2142     // is drawn to the screen, and when the snapshot will actually pick up
2143     // that content. Insert a manual delay of 1/6th of a second (to simulate
2144     // 10 frames at 60 fps) before actually taking the snapshot.
2145     base::MessageLoop::current()->PostDelayedTask(
2146         FROM_HERE,
2147         base::Bind(&RenderWidgetHostImpl::WindowSnapshotReachedScreen,
2148                    weak_factory_.GetWeakPtr(),
2149                    sequence_number),
2150         base::TimeDelta::FromSecondsD(1. / 6));
2151 #else
2152     WindowSnapshotReachedScreen(sequence_number);
2153 #endif
2154   }
2155
2156   ui::LatencyInfo::LatencyComponent swap_component;
2157   if (!latency_info.FindLatency(
2158           ui::INPUT_EVENT_LATENCY_TERMINATED_FRAME_SWAP_COMPONENT,
2159           0,
2160           &swap_component)) {
2161     return;
2162   }
2163   ui::LatencyInfo::LatencyComponent tab_switch_component;
2164   if (latency_info.FindLatency(ui::TAB_SHOW_COMPONENT,
2165                                GetLatencyComponentId(),
2166                                &tab_switch_component)) {
2167     base::TimeDelta delta =
2168         swap_component.event_time - tab_switch_component.event_time;
2169     for (size_t i = 0; i < tab_switch_component.event_count; i++) {
2170       UMA_HISTOGRAM_TIMES("MPArch.RWH_TabSwitchPaintDuration", delta);
2171     }
2172   }
2173
2174   ui::LatencyInfo::LatencyComponent rwh_component;
2175   if (!latency_info.FindLatency(ui::INPUT_EVENT_LATENCY_BEGIN_RWH_COMPONENT,
2176                                 GetLatencyComponentId(),
2177                                 &rwh_component)) {
2178     return;
2179   }
2180
2181   ui::LatencyInfo::LatencyComponent original_component;
2182   if (latency_info.FindLatency(
2183           ui::INPUT_EVENT_LATENCY_SCROLL_UPDATE_ORIGINAL_COMPONENT,
2184           GetLatencyComponentId(),
2185           &original_component)) {
2186     // This UMA metric tracks the time from when the original touch event is
2187     // created (averaged if there are multiple) to when the scroll gesture
2188     // results in final frame swap.
2189     base::TimeDelta delta =
2190         swap_component.event_time - original_component.event_time;
2191     for (size_t i = 0; i < original_component.event_count; i++) {
2192       UMA_HISTOGRAM_CUSTOM_COUNTS(
2193           "Event.Latency.TouchToScrollUpdateSwap",
2194           delta.InMicroseconds(),
2195           1,
2196           1000000,
2197           100);
2198     }
2199   }
2200 }
2201
2202 void RenderWidgetHostImpl::DidReceiveRendererFrame() {
2203   view_->DidReceiveRendererFrame();
2204 }
2205
2206 void RenderWidgetHostImpl::WindowSnapshotAsyncCallback(
2207     int routing_id,
2208     int snapshot_id,
2209     gfx::Size snapshot_size,
2210     scoped_refptr<base::RefCountedBytes> png_data) {
2211   if (!png_data.get()) {
2212     std::vector<unsigned char> png_vector;
2213     Send(new ViewMsg_WindowSnapshotCompleted(
2214         routing_id, snapshot_id, gfx::Size(), png_vector));
2215     return;
2216   }
2217
2218   Send(new ViewMsg_WindowSnapshotCompleted(
2219       routing_id, snapshot_id, snapshot_size, png_data->data()));
2220 }
2221
2222 void RenderWidgetHostImpl::WindowOldSnapshotReachedScreen(int snapshot_id) {
2223   DCHECK(base::MessageLoopForUI::IsCurrent());
2224
2225   std::vector<unsigned char> png;
2226
2227   // This feature is behind the kEnableGpuBenchmarking command line switch
2228   // because it poses security concerns and should only be used for testing.
2229   const base::CommandLine& command_line =
2230       *base::CommandLine::ForCurrentProcess();
2231   if (!command_line.HasSwitch(cc::switches::kEnableGpuBenchmarking)) {
2232     Send(new ViewMsg_WindowSnapshotCompleted(
2233         GetRoutingID(), snapshot_id, gfx::Size(), png));
2234     return;
2235   }
2236
2237   gfx::Rect view_bounds = GetView()->GetViewBounds();
2238   gfx::Rect snapshot_bounds(view_bounds.size());
2239   gfx::Size snapshot_size = snapshot_bounds.size();
2240
2241   if (ui::GrabViewSnapshot(
2242           GetView()->GetNativeView(), &png, snapshot_bounds)) {
2243     Send(new ViewMsg_WindowSnapshotCompleted(
2244         GetRoutingID(), snapshot_id, snapshot_size, png));
2245     return;
2246   }
2247
2248   ui::GrabViewSnapshotAsync(
2249       GetView()->GetNativeView(),
2250       snapshot_bounds,
2251       base::ThreadTaskRunnerHandle::Get(),
2252       base::Bind(&RenderWidgetHostImpl::WindowSnapshotAsyncCallback,
2253                  weak_factory_.GetWeakPtr(),
2254                  GetRoutingID(),
2255                  snapshot_id,
2256                  snapshot_size));
2257 }
2258
2259 void RenderWidgetHostImpl::WindowSnapshotReachedScreen(int snapshot_id) {
2260   DCHECK(base::MessageLoopForUI::IsCurrent());
2261
2262   gfx::Rect view_bounds = GetView()->GetViewBounds();
2263   gfx::Rect snapshot_bounds(view_bounds.size());
2264
2265   std::vector<unsigned char> png;
2266   if (ui::GrabViewSnapshot(
2267       GetView()->GetNativeView(), &png, snapshot_bounds)) {
2268     OnSnapshotDataReceived(snapshot_id, &png.front(), png.size());
2269     return;
2270   }
2271
2272   ui::GrabViewSnapshotAsync(
2273       GetView()->GetNativeView(),
2274       snapshot_bounds,
2275       base::ThreadTaskRunnerHandle::Get(),
2276       base::Bind(&RenderWidgetHostImpl::OnSnapshotDataReceivedAsync,
2277                  weak_factory_.GetWeakPtr(),
2278                  snapshot_id));
2279 }
2280
2281 void RenderWidgetHostImpl::OnSnapshotDataReceived(int snapshot_id,
2282                                                   const unsigned char* data,
2283                                                   size_t size) {
2284   // Any pending snapshots with a lower ID than the one received are considered
2285   // to be implicitly complete, and returned the same snapshot data.
2286   PendingSnapshotMap::iterator it = pending_browser_snapshots_.begin();
2287   while(it != pending_browser_snapshots_.end()) {
2288       if (it->first <= snapshot_id) {
2289         it->second.Run(data, size);
2290         pending_browser_snapshots_.erase(it++);
2291       } else {
2292         ++it;
2293       }
2294   }
2295 }
2296
2297 void RenderWidgetHostImpl::OnSnapshotDataReceivedAsync(
2298     int snapshot_id,
2299     scoped_refptr<base::RefCountedBytes> png_data) {
2300   if (png_data.get())
2301     OnSnapshotDataReceived(snapshot_id, png_data->front(), png_data->size());
2302   else
2303     OnSnapshotDataReceived(snapshot_id, NULL, 0);
2304 }
2305
2306 // static
2307 void RenderWidgetHostImpl::CompositorFrameDrawn(
2308     const std::vector<ui::LatencyInfo>& latency_info) {
2309   for (size_t i = 0; i < latency_info.size(); i++) {
2310     std::set<RenderWidgetHostImpl*> rwhi_set;
2311     for (ui::LatencyInfo::LatencyMap::const_iterator b =
2312              latency_info[i].latency_components.begin();
2313          b != latency_info[i].latency_components.end();
2314          ++b) {
2315       if (b->first.first == ui::INPUT_EVENT_LATENCY_BEGIN_RWH_COMPONENT ||
2316           b->first.first == ui::WINDOW_SNAPSHOT_FRAME_NUMBER_COMPONENT ||
2317           b->first.first == ui::WINDOW_OLD_SNAPSHOT_FRAME_NUMBER_COMPONENT ||
2318           b->first.first == ui::TAB_SHOW_COMPONENT) {
2319         // Matches with GetLatencyComponentId
2320         int routing_id = b->first.second & 0xffffffff;
2321         int process_id = (b->first.second >> 32) & 0xffffffff;
2322         RenderWidgetHost* rwh =
2323             RenderWidgetHost::FromID(process_id, routing_id);
2324         if (!rwh) {
2325           continue;
2326         }
2327         RenderWidgetHostImpl* rwhi = RenderWidgetHostImpl::From(rwh);
2328         if (rwhi_set.insert(rwhi).second)
2329           rwhi->FrameSwapped(latency_info[i]);
2330       }
2331     }
2332   }
2333 }
2334
2335 void RenderWidgetHostImpl::AddLatencyInfoComponentIds(
2336     ui::LatencyInfo* latency_info) {
2337   ui::LatencyInfo::LatencyMap new_components;
2338   ui::LatencyInfo::LatencyMap::iterator lc =
2339       latency_info->latency_components.begin();
2340   while (lc != latency_info->latency_components.end()) {
2341     ui::LatencyComponentType component_type = lc->first.first;
2342     if (component_type == ui::WINDOW_SNAPSHOT_FRAME_NUMBER_COMPONENT ||
2343         component_type == ui::WINDOW_OLD_SNAPSHOT_FRAME_NUMBER_COMPONENT) {
2344       // Generate a new component entry with the correct component ID
2345       ui::LatencyInfo::LatencyMap::key_type key =
2346           std::make_pair(component_type, GetLatencyComponentId());
2347       new_components[key] = lc->second;
2348
2349       // Remove the old entry
2350       latency_info->latency_components.erase(lc++);
2351     } else {
2352       ++lc;
2353     }
2354   }
2355
2356   // Add newly generated components into the latency info
2357   for (lc = new_components.begin(); lc != new_components.end(); ++lc) {
2358     latency_info->latency_components[lc->first] = lc->second;
2359   }
2360 }
2361
2362 BrowserAccessibilityManager*
2363     RenderWidgetHostImpl::GetRootBrowserAccessibilityManager() {
2364   return delegate_ ? delegate_->GetRootBrowserAccessibilityManager() : NULL;
2365 }
2366
2367 BrowserAccessibilityManager*
2368     RenderWidgetHostImpl::GetOrCreateRootBrowserAccessibilityManager() {
2369   return delegate_ ?
2370       delegate_->GetOrCreateRootBrowserAccessibilityManager() : NULL;
2371 }
2372
2373 #if defined(OS_WIN)
2374 gfx::NativeViewAccessible
2375     RenderWidgetHostImpl::GetParentNativeViewAccessible() {
2376   return delegate_ ? delegate_->GetParentNativeViewAccessible() : NULL;
2377 }
2378 #endif
2379
2380 SkColorType RenderWidgetHostImpl::PreferredReadbackFormat() {
2381   if (view_)
2382     return view_->PreferredReadbackFormat();
2383   return kN32_SkColorType;
2384 }
2385
2386 }  // namespace content