chrome/browser/extensions: Remove use of MessageLoopProxy and deprecated MessageLoop...
[chromium-blink-merge.git] / content / browser / renderer_host / render_widget_host_impl.cc
blob74f7ff429f0981741087139b96656c2297e6fbcd
1 // Copyright (c) 2012 The Chromium Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
5 #include "content/browser/renderer_host/render_widget_host_impl.h"
7 #include <math.h>
8 #include <set>
9 #include <utility>
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/i18n/rtl.h"
16 #include "base/lazy_instance.h"
17 #include "base/location.h"
18 #include "base/metrics/field_trial.h"
19 #include "base/metrics/histogram.h"
20 #include "base/single_thread_task_runner.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 "base/trace_event/trace_event.h"
25 #include "cc/base/switches.h"
26 #include "cc/output/compositor_frame.h"
27 #include "cc/output/compositor_frame_ack.h"
28 #include "content/browser/accessibility/accessibility_mode_helper.h"
29 #include "content/browser/accessibility/browser_accessibility_state_impl.h"
30 #include "content/browser/bad_message.h"
31 #include "content/browser/browser_plugin/browser_plugin_guest.h"
32 #include "content/browser/gpu/compositor_util.h"
33 #include "content/browser/gpu/gpu_process_host.h"
34 #include "content/browser/gpu/gpu_process_host_ui_shim.h"
35 #include "content/browser/gpu/gpu_surface_tracker.h"
36 #include "content/browser/renderer_host/dip_util.h"
37 #include "content/browser/renderer_host/frame_metadata_util.h"
38 #include "content/browser/renderer_host/input/input_router_config_helper.h"
39 #include "content/browser/renderer_host/input/input_router_impl.h"
40 #include "content/browser/renderer_host/input/synthetic_gesture.h"
41 #include "content/browser/renderer_host/input/synthetic_gesture_controller.h"
42 #include "content/browser/renderer_host/input/synthetic_gesture_target.h"
43 #include "content/browser/renderer_host/input/timeout_monitor.h"
44 #include "content/browser/renderer_host/input/touch_emulator.h"
45 #include "content/browser/renderer_host/render_process_host_impl.h"
46 #include "content/browser/renderer_host/render_view_host_impl.h"
47 #include "content/browser/renderer_host/render_widget_helper.h"
48 #include "content/browser/renderer_host/render_widget_host_delegate.h"
49 #include "content/browser/renderer_host/render_widget_host_view_base.h"
50 #include "content/browser/renderer_host/render_widget_resize_helper.h"
51 #include "content/common/content_constants_internal.h"
52 #include "content/common/cursors/webcursor.h"
53 #include "content/common/frame_messages.h"
54 #include "content/common/gpu/gpu_messages.h"
55 #include "content/common/host_shared_bitmap_manager.h"
56 #include "content/common/input_messages.h"
57 #include "content/common/view_messages.h"
58 #include "content/public/browser/native_web_keyboard_event.h"
59 #include "content/public/browser/notification_service.h"
60 #include "content/public/browser/notification_types.h"
61 #include "content/public/browser/render_widget_host_iterator.h"
62 #include "content/public/common/content_constants.h"
63 #include "content/public/common/content_switches.h"
64 #include "content/public/common/result_codes.h"
65 #include "content/public/common/web_preferences.h"
66 #include "gpu/GLES2/gl2extchromium.h"
67 #include "gpu/command_buffer/service/gpu_switches.h"
68 #include "skia/ext/image_operations.h"
69 #include "skia/ext/platform_canvas.h"
70 #include "third_party/WebKit/public/web/WebCompositionUnderline.h"
71 #include "ui/events/event.h"
72 #include "ui/events/keycodes/keyboard_codes.h"
73 #include "ui/gfx/geometry/size_conversions.h"
74 #include "ui/gfx/geometry/vector2d_conversions.h"
75 #include "ui/gfx/skbitmap_operations.h"
76 #include "ui/snapshot/snapshot.h"
78 #if defined(OS_WIN)
79 #include "content/common/plugin_constants_win.h"
80 #endif
82 using base::Time;
83 using base::TimeDelta;
84 using base::TimeTicks;
85 using blink::WebGestureEvent;
86 using blink::WebInputEvent;
87 using blink::WebKeyboardEvent;
88 using blink::WebMouseEvent;
89 using blink::WebMouseWheelEvent;
90 using blink::WebTextDirection;
92 namespace content {
93 namespace {
95 bool g_check_for_pending_resize_ack = true;
97 typedef std::pair<int32, int32> RenderWidgetHostID;
98 typedef base::hash_map<RenderWidgetHostID, RenderWidgetHostImpl*>
99 RoutingIDWidgetMap;
100 base::LazyInstance<RoutingIDWidgetMap> g_routing_id_widget_map =
101 LAZY_INSTANCE_INITIALIZER;
103 int GetInputRouterViewFlagsFromCompositorFrameMetadata(
104 const cc::CompositorFrameMetadata metadata) {
105 int view_flags = InputRouter::VIEW_FLAGS_NONE;
107 if (metadata.min_page_scale_factor == metadata.max_page_scale_factor)
108 view_flags |= InputRouter::FIXED_PAGE_SCALE;
110 const float window_width_dip = std::ceil(
111 metadata.page_scale_factor * metadata.scrollable_viewport_size.width());
112 const float content_width_css = metadata.root_layer_size.width();
113 if (content_width_css <= window_width_dip)
114 view_flags |= InputRouter::MOBILE_VIEWPORT;
116 return view_flags;
119 // Implements the RenderWidgetHostIterator interface. It keeps a list of
120 // RenderWidgetHosts, and makes sure it returns a live RenderWidgetHost at each
121 // iteration (or NULL if there isn't any left).
122 class RenderWidgetHostIteratorImpl : public RenderWidgetHostIterator {
123 public:
124 RenderWidgetHostIteratorImpl()
125 : current_index_(0) {
128 ~RenderWidgetHostIteratorImpl() override {}
130 void Add(RenderWidgetHost* host) {
131 hosts_.push_back(RenderWidgetHostID(host->GetProcess()->GetID(),
132 host->GetRoutingID()));
135 // RenderWidgetHostIterator:
136 RenderWidgetHost* GetNextHost() override {
137 RenderWidgetHost* host = NULL;
138 while (current_index_ < hosts_.size() && !host) {
139 RenderWidgetHostID id = hosts_[current_index_];
140 host = RenderWidgetHost::FromID(id.first, id.second);
141 ++current_index_;
143 return host;
146 private:
147 std::vector<RenderWidgetHostID> hosts_;
148 size_t current_index_;
150 DISALLOW_COPY_AND_ASSIGN(RenderWidgetHostIteratorImpl);
153 } // namespace
155 ///////////////////////////////////////////////////////////////////////////////
156 // RenderWidgetHostImpl
158 RenderWidgetHostImpl::RenderWidgetHostImpl(RenderWidgetHostDelegate* delegate,
159 RenderProcessHost* process,
160 int routing_id,
161 bool hidden)
162 : view_(NULL),
163 hung_renderer_delay_(
164 base::TimeDelta::FromMilliseconds(kHungRendererDelayMs)),
165 renderer_initialized_(false),
166 delegate_(delegate),
167 process_(process),
168 routing_id_(routing_id),
169 surface_id_(0),
170 is_loading_(false),
171 is_hidden_(hidden),
172 repaint_ack_pending_(false),
173 resize_ack_pending_(false),
174 auto_resize_enabled_(false),
175 waiting_for_screen_rects_ack_(false),
176 needs_repainting_on_restore_(false),
177 is_unresponsive_(false),
178 in_flight_event_count_(0),
179 in_get_backing_store_(false),
180 ignore_input_events_(false),
181 input_method_active_(false),
182 text_direction_updated_(false),
183 text_direction_(blink::WebTextDirectionLeftToRight),
184 text_direction_canceled_(false),
185 suppress_next_char_events_(false),
186 pending_mouse_lock_request_(false),
187 allow_privileged_mouse_lock_(false),
188 has_touch_handler_(false),
189 next_browser_snapshot_id_(1),
190 owned_by_render_frame_host_(false),
191 is_focused_(false),
192 weak_factory_(this) {
193 CHECK(delegate_);
194 if (routing_id_ == MSG_ROUTING_NONE) {
195 routing_id_ = process_->GetNextRoutingID();
196 surface_id_ = GpuSurfaceTracker::Get()->AddSurfaceForRenderer(
197 process_->GetID(),
198 routing_id_);
199 } else {
200 // TODO(piman): This is a O(N) lookup, where we could forward the
201 // information from the RenderWidgetHelper. The problem is that doing so
202 // currently leaks outside of content all the way to chrome classes, and
203 // would be a layering violation. Since we don't expect more than a few
204 // hundreds of RWH, this seems acceptable. Revisit if performance become a
205 // problem, for example by tracking in the RenderWidgetHelper the routing id
206 // (and surface id) that have been created, but whose RWH haven't yet.
207 surface_id_ = GpuSurfaceTracker::Get()->LookupSurfaceForRenderer(
208 process_->GetID(),
209 routing_id_);
210 DCHECK(surface_id_);
213 std::pair<RoutingIDWidgetMap::iterator, bool> result =
214 g_routing_id_widget_map.Get().insert(std::make_pair(
215 RenderWidgetHostID(process->GetID(), routing_id_), this));
216 CHECK(result.second) << "Inserting a duplicate item!";
217 process_->AddRoute(routing_id_, this);
219 // If we're initially visible, tell the process host that we're alive.
220 // Otherwise we'll notify the process host when we are first shown.
221 if (!hidden)
222 process_->WidgetRestored();
224 latency_tracker_.Initialize(routing_id_, GetProcess()->GetID());
226 input_router_.reset(new InputRouterImpl(
227 process_, this, this, routing_id_, GetInputRouterConfigForPlatform()));
229 touch_emulator_.reset();
231 RenderViewHostImpl* rvh = static_cast<RenderViewHostImpl*>(
232 IsRenderView() ? RenderViewHost::From(this) : NULL);
233 if (BrowserPluginGuest::IsGuest(rvh) ||
234 !base::CommandLine::ForCurrentProcess()->HasSwitch(
235 switches::kDisableHangMonitor)) {
236 hang_monitor_timeout_.reset(new TimeoutMonitor(
237 base::Bind(&RenderWidgetHostImpl::RendererIsUnresponsive,
238 weak_factory_.GetWeakPtr())));
242 RenderWidgetHostImpl::~RenderWidgetHostImpl() {
243 if (view_weak_)
244 view_weak_->RenderWidgetHostGone();
245 SetView(NULL);
247 GpuSurfaceTracker::Get()->RemoveSurface(surface_id_);
248 surface_id_ = 0;
250 process_->RemoveRoute(routing_id_);
251 g_routing_id_widget_map.Get().erase(
252 RenderWidgetHostID(process_->GetID(), routing_id_));
254 if (delegate_)
255 delegate_->RenderWidgetDeleted(this);
258 // static
259 RenderWidgetHost* RenderWidgetHost::FromID(
260 int32 process_id,
261 int32 routing_id) {
262 return RenderWidgetHostImpl::FromID(process_id, routing_id);
265 // static
266 RenderWidgetHostImpl* RenderWidgetHostImpl::FromID(
267 int32 process_id,
268 int32 routing_id) {
269 DCHECK_CURRENTLY_ON(BrowserThread::UI);
270 RoutingIDWidgetMap* widgets = g_routing_id_widget_map.Pointer();
271 RoutingIDWidgetMap::iterator it = widgets->find(
272 RenderWidgetHostID(process_id, routing_id));
273 return it == widgets->end() ? NULL : it->second;
276 // static
277 scoped_ptr<RenderWidgetHostIterator> RenderWidgetHost::GetRenderWidgetHosts() {
278 RenderWidgetHostIteratorImpl* hosts = new RenderWidgetHostIteratorImpl();
279 RoutingIDWidgetMap* widgets = g_routing_id_widget_map.Pointer();
280 for (RoutingIDWidgetMap::const_iterator it = widgets->begin();
281 it != widgets->end();
282 ++it) {
283 RenderWidgetHost* widget = it->second;
285 if (!widget->IsRenderView()) {
286 hosts->Add(widget);
287 continue;
290 // Add only active RenderViewHosts.
291 RenderViewHost* rvh = RenderViewHost::From(widget);
292 if (static_cast<RenderViewHostImpl*>(rvh)->is_active())
293 hosts->Add(widget);
296 return scoped_ptr<RenderWidgetHostIterator>(hosts);
299 // static
300 scoped_ptr<RenderWidgetHostIterator>
301 RenderWidgetHostImpl::GetAllRenderWidgetHosts() {
302 RenderWidgetHostIteratorImpl* hosts = new RenderWidgetHostIteratorImpl();
303 RoutingIDWidgetMap* widgets = g_routing_id_widget_map.Pointer();
304 for (RoutingIDWidgetMap::const_iterator it = widgets->begin();
305 it != widgets->end();
306 ++it) {
307 hosts->Add(it->second);
310 return scoped_ptr<RenderWidgetHostIterator>(hosts);
313 // static
314 RenderWidgetHostImpl* RenderWidgetHostImpl::From(RenderWidgetHost* rwh) {
315 return rwh->AsRenderWidgetHostImpl();
318 void RenderWidgetHostImpl::SetView(RenderWidgetHostViewBase* view) {
319 if (view)
320 view_weak_ = view->GetWeakPtr();
321 else
322 view_weak_.reset();
323 view_ = view;
325 // If the renderer has not yet been initialized, then the surface ID
326 // namespace will be sent during initialization.
327 if (view_ && renderer_initialized_) {
328 Send(new ViewMsg_SetSurfaceIdNamespace(routing_id_,
329 view_->GetSurfaceIdNamespace()));
332 GpuSurfaceTracker::Get()->SetSurfaceHandle(
333 surface_id_, GetCompositingSurface());
335 synthetic_gesture_controller_.reset();
338 RenderProcessHost* RenderWidgetHostImpl::GetProcess() const {
339 return process_;
342 int RenderWidgetHostImpl::GetRoutingID() const {
343 return routing_id_;
346 RenderWidgetHostView* RenderWidgetHostImpl::GetView() const {
347 return view_;
350 RenderWidgetHostImpl* RenderWidgetHostImpl::AsRenderWidgetHostImpl() {
351 return this;
354 gfx::NativeViewId RenderWidgetHostImpl::GetNativeViewId() const {
355 if (view_)
356 return view_->GetNativeViewId();
357 return 0;
360 gfx::GLSurfaceHandle RenderWidgetHostImpl::GetCompositingSurface() {
361 if (view_)
362 return view_->GetCompositingSurface();
363 return gfx::GLSurfaceHandle();
366 void RenderWidgetHostImpl::ResetSizeAndRepaintPendingFlags() {
367 resize_ack_pending_ = false;
368 if (repaint_ack_pending_) {
369 TRACE_EVENT_ASYNC_END0(
370 "renderer_host", "RenderWidgetHostImpl::repaint_ack_pending_", this);
372 repaint_ack_pending_ = false;
373 if (old_resize_params_)
374 old_resize_params_->new_size = gfx::Size();
377 void RenderWidgetHostImpl::SendScreenRects() {
378 if (!renderer_initialized_ || waiting_for_screen_rects_ack_)
379 return;
381 if (is_hidden_) {
382 // On GTK, this comes in for backgrounded tabs. Ignore, to match what
383 // happens on Win & Mac, and when the view is shown it'll call this again.
384 return;
387 if (!view_)
388 return;
390 last_view_screen_rect_ = view_->GetViewBounds();
391 last_window_screen_rect_ = view_->GetBoundsInRootWindow();
392 Send(new ViewMsg_UpdateScreenRects(
393 GetRoutingID(), last_view_screen_rect_, last_window_screen_rect_));
394 if (delegate_)
395 delegate_->DidSendScreenRects(this);
396 waiting_for_screen_rects_ack_ = true;
399 void RenderWidgetHostImpl::SuppressNextCharEvents() {
400 suppress_next_char_events_ = true;
403 void RenderWidgetHostImpl::FlushInput() {
404 input_router_->RequestNotificationWhenFlushed();
405 if (synthetic_gesture_controller_)
406 synthetic_gesture_controller_->Flush(base::TimeTicks::Now());
409 void RenderWidgetHostImpl::SetNeedsFlush() {
410 if (view_)
411 view_->OnSetNeedsFlushInput();
414 void RenderWidgetHostImpl::Init() {
415 DCHECK(process_->HasConnection());
417 renderer_initialized_ = true;
419 GpuSurfaceTracker::Get()->SetSurfaceHandle(
420 surface_id_, GetCompositingSurface());
422 // Send the ack along with the information on placement.
423 Send(new ViewMsg_CreatingNew_ACK(routing_id_));
424 GetProcess()->ResumeRequestsForView(routing_id_);
426 // If the RWHV has not yet been set, the surface ID namespace will get
427 // passed down by the call to SetView().
428 if (view_) {
429 Send(new ViewMsg_SetSurfaceIdNamespace(routing_id_,
430 view_->GetSurfaceIdNamespace()));
433 WasResized();
436 void RenderWidgetHostImpl::InitForFrame() {
437 DCHECK(process_->HasConnection());
438 renderer_initialized_ = true;
441 void RenderWidgetHostImpl::Shutdown() {
442 RejectMouseLockOrUnlockIfNecessary();
444 if (process_->HasConnection()) {
445 // Tell the renderer object to close.
446 bool rv = Send(new ViewMsg_Close(routing_id_));
447 DCHECK(rv);
450 Destroy();
453 bool RenderWidgetHostImpl::IsLoading() const {
454 return is_loading_;
457 bool RenderWidgetHostImpl::IsRenderView() const {
458 return false;
461 bool RenderWidgetHostImpl::OnMessageReceived(const IPC::Message &msg) {
462 bool handled = true;
463 IPC_BEGIN_MESSAGE_MAP(RenderWidgetHostImpl, msg)
464 IPC_MESSAGE_HANDLER(FrameHostMsg_RenderProcessGone, OnRenderProcessGone)
465 IPC_MESSAGE_HANDLER(InputHostMsg_QueueSyntheticGesture,
466 OnQueueSyntheticGesture)
467 IPC_MESSAGE_HANDLER(InputHostMsg_ImeCancelComposition,
468 OnImeCancelComposition)
469 IPC_MESSAGE_HANDLER(ViewHostMsg_RenderViewReady, OnRenderViewReady)
470 IPC_MESSAGE_HANDLER(ViewHostMsg_Close, OnClose)
471 IPC_MESSAGE_HANDLER(ViewHostMsg_UpdateScreenRects_ACK,
472 OnUpdateScreenRectsAck)
473 IPC_MESSAGE_HANDLER(ViewHostMsg_RequestMove, OnRequestMove)
474 IPC_MESSAGE_HANDLER(ViewHostMsg_SetTooltipText, OnSetTooltipText)
475 IPC_MESSAGE_HANDLER_GENERIC(ViewHostMsg_SwapCompositorFrame,
476 OnSwapCompositorFrame(msg))
477 IPC_MESSAGE_HANDLER(ViewHostMsg_UpdateRect, OnUpdateRect)
478 IPC_MESSAGE_HANDLER(ViewHostMsg_Focus, OnFocus)
479 IPC_MESSAGE_HANDLER(ViewHostMsg_Blur, OnBlur)
480 IPC_MESSAGE_HANDLER(ViewHostMsg_SetCursor, OnSetCursor)
481 IPC_MESSAGE_HANDLER(ViewHostMsg_TextInputTypeChanged,
482 OnTextInputTypeChanged)
483 IPC_MESSAGE_HANDLER(ViewHostMsg_LockMouse, OnLockMouse)
484 IPC_MESSAGE_HANDLER(ViewHostMsg_UnlockMouse, OnUnlockMouse)
485 IPC_MESSAGE_HANDLER(ViewHostMsg_ShowDisambiguationPopup,
486 OnShowDisambiguationPopup)
487 IPC_MESSAGE_HANDLER(ViewHostMsg_SelectionChanged, OnSelectionChanged)
488 IPC_MESSAGE_HANDLER(ViewHostMsg_SelectionBoundsChanged,
489 OnSelectionBoundsChanged)
490 #if defined(OS_WIN)
491 IPC_MESSAGE_HANDLER(ViewHostMsg_WindowlessPluginDummyWindowCreated,
492 OnWindowlessPluginDummyWindowCreated)
493 IPC_MESSAGE_HANDLER(ViewHostMsg_WindowlessPluginDummyWindowDestroyed,
494 OnWindowlessPluginDummyWindowDestroyed)
495 #endif
496 IPC_MESSAGE_HANDLER(InputHostMsg_ImeCompositionRangeChanged,
497 OnImeCompositionRangeChanged)
498 IPC_MESSAGE_UNHANDLED(handled = false)
499 IPC_END_MESSAGE_MAP()
501 if (!handled && input_router_ && input_router_->OnMessageReceived(msg))
502 return true;
504 if (!handled && view_ && view_->OnMessageReceived(msg))
505 return true;
507 return handled;
510 bool RenderWidgetHostImpl::Send(IPC::Message* msg) {
511 if (IPC_MESSAGE_ID_CLASS(msg->type()) == InputMsgStart)
512 return input_router_->SendInput(make_scoped_ptr(msg));
514 return process_->Send(msg);
517 void RenderWidgetHostImpl::SetIsLoading(bool is_loading) {
518 is_loading_ = is_loading;
519 if (!view_)
520 return;
521 view_->SetIsLoading(is_loading);
524 void RenderWidgetHostImpl::WasHidden() {
525 if (is_hidden_)
526 return;
528 TRACE_EVENT0("renderer_host", "RenderWidgetHostImpl::WasHidden");
529 is_hidden_ = true;
531 // Don't bother reporting hung state when we aren't active.
532 StopHangMonitorTimeout();
534 // If we have a renderer, then inform it that we are being hidden so it can
535 // reduce its resource utilization.
536 Send(new ViewMsg_WasHidden(routing_id_));
538 // Tell the RenderProcessHost we were hidden.
539 process_->WidgetHidden();
541 bool is_visible = false;
542 NotificationService::current()->Notify(
543 NOTIFICATION_RENDER_WIDGET_VISIBILITY_CHANGED,
544 Source<RenderWidgetHost>(this),
545 Details<bool>(&is_visible));
548 void RenderWidgetHostImpl::WasShown(const ui::LatencyInfo& latency_info) {
549 if (!is_hidden_)
550 return;
552 TRACE_EVENT0("renderer_host", "RenderWidgetHostImpl::WasShown");
553 is_hidden_ = false;
555 SendScreenRects();
557 // When hidden, timeout monitoring for input events is disabled. Restore it
558 // now to ensure consistent hang detection.
559 if (in_flight_event_count_)
560 RestartHangMonitorTimeout();
562 // Always repaint on restore.
563 bool needs_repainting = true;
564 needs_repainting_on_restore_ = false;
565 Send(new ViewMsg_WasShown(routing_id_, needs_repainting, latency_info));
567 process_->WidgetRestored();
569 bool is_visible = true;
570 NotificationService::current()->Notify(
571 NOTIFICATION_RENDER_WIDGET_VISIBILITY_CHANGED,
572 Source<RenderWidgetHost>(this),
573 Details<bool>(&is_visible));
575 // It's possible for our size to be out of sync with the renderer. The
576 // following is one case that leads to this:
577 // 1. WasResized -> Send ViewMsg_Resize to render
578 // 2. WasResized -> do nothing as resize_ack_pending_ is true
579 // 3. WasHidden
580 // 4. OnUpdateRect from (1) processed. Does NOT invoke WasResized as view
581 // is hidden. Now renderer/browser out of sync with what they think size
582 // is.
583 // By invoking WasResized the renderer is updated as necessary. WasResized
584 // does nothing if the sizes are already in sync.
586 // TODO: ideally ViewMsg_WasShown would take a size. This way, the renderer
587 // could handle both the restore and resize at once. This isn't that big a
588 // deal as RenderWidget::WasShown delays updating, so that the resize from
589 // WasResized is usually processed before the renderer is painted.
590 WasResized();
593 bool RenderWidgetHostImpl::GetResizeParams(
594 ViewMsg_Resize_Params* resize_params) {
595 *resize_params = ViewMsg_Resize_Params();
597 GetWebScreenInfo(&resize_params->screen_info);
598 resize_params->resizer_rect = GetRootWindowResizerRect();
600 if (view_) {
601 resize_params->new_size = view_->GetRequestedRendererSize();
602 resize_params->physical_backing_size = view_->GetPhysicalBackingSize();
603 resize_params->top_controls_height = view_->GetTopControlsHeight();
604 resize_params->top_controls_shrink_blink_size =
605 view_->DoTopControlsShrinkBlinkSize();
606 resize_params->visible_viewport_size = view_->GetVisibleViewportSize();
607 resize_params->is_fullscreen_granted = IsFullscreenGranted();
608 resize_params->display_mode = GetDisplayMode();
611 const bool size_changed =
612 !old_resize_params_ ||
613 old_resize_params_->new_size != resize_params->new_size ||
614 (old_resize_params_->physical_backing_size.IsEmpty() &&
615 !resize_params->physical_backing_size.IsEmpty());
616 bool dirty = size_changed ||
617 old_resize_params_->screen_info != resize_params->screen_info ||
618 old_resize_params_->physical_backing_size !=
619 resize_params->physical_backing_size ||
620 old_resize_params_->is_fullscreen_granted !=
621 resize_params->is_fullscreen_granted ||
622 old_resize_params_->display_mode != resize_params->display_mode ||
623 old_resize_params_->top_controls_height !=
624 resize_params->top_controls_height ||
625 old_resize_params_->top_controls_shrink_blink_size !=
626 resize_params->top_controls_shrink_blink_size ||
627 old_resize_params_->visible_viewport_size !=
628 resize_params->visible_viewport_size;
630 // We don't expect to receive an ACK when the requested size or the physical
631 // backing size is empty, or when the main viewport size didn't change.
632 resize_params->needs_resize_ack =
633 g_check_for_pending_resize_ack && !resize_params->new_size.IsEmpty() &&
634 !resize_params->physical_backing_size.IsEmpty() && size_changed;
636 return dirty;
639 void RenderWidgetHostImpl::SetInitialRenderSizeParams(
640 const ViewMsg_Resize_Params& resize_params) {
641 resize_ack_pending_ = resize_params.needs_resize_ack;
643 old_resize_params_ =
644 make_scoped_ptr(new ViewMsg_Resize_Params(resize_params));
647 void RenderWidgetHostImpl::WasResized() {
648 // Skip if the |delegate_| has already been detached because
649 // it's web contents is being deleted.
650 if (resize_ack_pending_ || !process_->HasConnection() || !view_ ||
651 !renderer_initialized_ || auto_resize_enabled_ || !delegate_) {
652 return;
655 scoped_ptr<ViewMsg_Resize_Params> params(new ViewMsg_Resize_Params);
656 if (!GetResizeParams(params.get()))
657 return;
659 bool width_changed =
660 !old_resize_params_ ||
661 old_resize_params_->new_size.width() != params->new_size.width();
662 if (Send(new ViewMsg_Resize(routing_id_, *params))) {
663 resize_ack_pending_ = params->needs_resize_ack;
664 old_resize_params_.swap(params);
667 if (delegate_)
668 delegate_->RenderWidgetWasResized(this, width_changed);
671 void RenderWidgetHostImpl::ResizeRectChanged(const gfx::Rect& new_rect) {
672 Send(new ViewMsg_ChangeResizeRect(routing_id_, new_rect));
675 void RenderWidgetHostImpl::GotFocus() {
676 Focus();
677 if (delegate_)
678 delegate_->RenderWidgetGotFocus(this);
681 void RenderWidgetHostImpl::Focus() {
682 is_focused_ = true;
684 Send(new InputMsg_SetFocus(routing_id_, true));
687 void RenderWidgetHostImpl::Blur() {
688 is_focused_ = false;
690 // If there is a pending mouse lock request, we don't want to reject it at
691 // this point. The user can switch focus back to this view and approve the
692 // request later.
693 if (IsMouseLocked())
694 view_->UnlockMouse();
696 if (touch_emulator_)
697 touch_emulator_->CancelTouch();
699 Send(new InputMsg_SetFocus(routing_id_, false));
702 void RenderWidgetHostImpl::LostCapture() {
703 if (touch_emulator_)
704 touch_emulator_->CancelTouch();
706 Send(new InputMsg_MouseCaptureLost(routing_id_));
709 void RenderWidgetHostImpl::SetActive(bool active) {
710 Send(new ViewMsg_SetActive(routing_id_, active));
713 void RenderWidgetHostImpl::LostMouseLock() {
714 Send(new ViewMsg_MouseLockLost(routing_id_));
717 void RenderWidgetHostImpl::ViewDestroyed() {
718 RejectMouseLockOrUnlockIfNecessary();
720 // TODO(evanm): tracking this may no longer be necessary;
721 // eliminate this function if so.
722 SetView(NULL);
725 void RenderWidgetHostImpl::CopyFromBackingStore(
726 const gfx::Rect& src_subrect,
727 const gfx::Size& accelerated_dst_size,
728 ReadbackRequestCallback& callback,
729 const SkColorType preferred_color_type) {
730 if (view_) {
731 TRACE_EVENT0("browser",
732 "RenderWidgetHostImpl::CopyFromBackingStore::FromCompositingSurface");
733 gfx::Rect accelerated_copy_rect = src_subrect.IsEmpty() ?
734 gfx::Rect(view_->GetViewBounds().size()) : src_subrect;
735 view_->CopyFromCompositingSurface(accelerated_copy_rect,
736 accelerated_dst_size, callback,
737 preferred_color_type);
738 return;
741 callback.Run(SkBitmap(), content::READBACK_FAILED);
744 bool RenderWidgetHostImpl::CanCopyFromBackingStore() {
745 if (view_)
746 return view_->IsSurfaceAvailableForCopy();
747 return false;
750 #if defined(OS_ANDROID)
751 void RenderWidgetHostImpl::LockBackingStore() {
752 if (view_)
753 view_->LockCompositingSurface();
756 void RenderWidgetHostImpl::UnlockBackingStore() {
757 if (view_)
758 view_->UnlockCompositingSurface();
760 #endif
762 #if defined(OS_MACOSX)
763 void RenderWidgetHostImpl::PauseForPendingResizeOrRepaints() {
764 TRACE_EVENT0("browser",
765 "RenderWidgetHostImpl::PauseForPendingResizeOrRepaints");
767 if (!CanPauseForPendingResizeOrRepaints())
768 return;
770 WaitForSurface();
773 bool RenderWidgetHostImpl::CanPauseForPendingResizeOrRepaints() {
774 // Do not pause if the view is hidden.
775 if (is_hidden())
776 return false;
778 // Do not pause if there is not a paint or resize already coming.
779 if (!repaint_ack_pending_ && !resize_ack_pending_)
780 return false;
782 return true;
785 void RenderWidgetHostImpl::WaitForSurface() {
786 // How long to (synchronously) wait for the renderer to respond with a
787 // new frame when our current frame doesn't exist or is the wrong size.
788 // This timeout impacts the "choppiness" of our window resize.
789 const int kPaintMsgTimeoutMS = 50;
791 if (!view_)
792 return;
794 // The view_size will be current_size_ for auto-sized views and otherwise the
795 // size of the view_. (For auto-sized views, current_size_ is updated during
796 // UpdateRect messages.)
797 gfx::Size view_size = current_size_;
798 if (!auto_resize_enabled_) {
799 // Get the desired size from the current view bounds.
800 gfx::Rect view_rect = view_->GetViewBounds();
801 if (view_rect.IsEmpty())
802 return;
803 view_size = view_rect.size();
806 TRACE_EVENT2("renderer_host",
807 "RenderWidgetHostImpl::WaitForSurface",
808 "width",
809 base::IntToString(view_size.width()),
810 "height",
811 base::IntToString(view_size.height()));
813 // We should not be asked to paint while we are hidden. If we are hidden,
814 // then it means that our consumer failed to call WasShown.
815 DCHECK(!is_hidden_) << "WaitForSurface called while hidden!";
817 // We should never be called recursively; this can theoretically lead to
818 // infinite recursion and almost certainly leads to lower performance.
819 DCHECK(!in_get_backing_store_) << "WaitForSurface called recursively!";
820 base::AutoReset<bool> auto_reset_in_get_backing_store(
821 &in_get_backing_store_, true);
823 // We might have a surface that we can use already.
824 if (view_->HasAcceleratedSurface(view_size))
825 return;
827 // Request that the renderer produce a frame of the right size, if it
828 // hasn't been requested already.
829 if (!repaint_ack_pending_ && !resize_ack_pending_) {
830 repaint_start_time_ = TimeTicks::Now();
831 repaint_ack_pending_ = true;
832 TRACE_EVENT_ASYNC_BEGIN0(
833 "renderer_host", "RenderWidgetHostImpl::repaint_ack_pending_", this);
834 Send(new ViewMsg_Repaint(routing_id_, view_size));
837 // Pump a nested message loop until we time out or get a frame of the right
838 // size.
839 TimeTicks start_time = TimeTicks::Now();
840 TimeDelta time_left = TimeDelta::FromMilliseconds(kPaintMsgTimeoutMS);
841 TimeTicks timeout_time = start_time + time_left;
842 while (1) {
843 TRACE_EVENT0("renderer_host", "WaitForSurface::WaitForSingleTaskToRun");
844 if (RenderWidgetResizeHelper::Get()->WaitForSingleTaskToRun(time_left)) {
845 // For auto-resized views, current_size_ determines the view_size and it
846 // may have changed during the handling of an UpdateRect message.
847 if (auto_resize_enabled_)
848 view_size = current_size_;
849 if (view_->HasAcceleratedSurface(view_size))
850 break;
852 time_left = timeout_time - TimeTicks::Now();
853 if (time_left <= TimeDelta::FromSeconds(0)) {
854 TRACE_EVENT0("renderer_host", "WaitForSurface::Timeout");
855 break;
859 UMA_HISTOGRAM_CUSTOM_TIMES("OSX.RendererHost.SurfaceWaitTime",
860 TimeTicks::Now() - start_time,
861 TimeDelta::FromMilliseconds(1),
862 TimeDelta::FromMilliseconds(200), 50);
864 #endif
866 bool RenderWidgetHostImpl::ScheduleComposite() {
867 if (is_hidden_ || current_size_.IsEmpty() || repaint_ack_pending_ ||
868 resize_ack_pending_) {
869 return false;
872 // Send out a request to the renderer to paint the view if required.
873 repaint_start_time_ = TimeTicks::Now();
874 repaint_ack_pending_ = true;
875 TRACE_EVENT_ASYNC_BEGIN0(
876 "renderer_host", "RenderWidgetHostImpl::repaint_ack_pending_", this);
877 Send(new ViewMsg_Repaint(routing_id_, current_size_));
878 return true;
881 void RenderWidgetHostImpl::StartHangMonitorTimeout(base::TimeDelta delay) {
882 if (hang_monitor_timeout_)
883 hang_monitor_timeout_->Start(delay);
886 void RenderWidgetHostImpl::RestartHangMonitorTimeout() {
887 if (hang_monitor_timeout_)
888 hang_monitor_timeout_->Restart(hung_renderer_delay_);
891 void RenderWidgetHostImpl::StopHangMonitorTimeout() {
892 if (hang_monitor_timeout_)
893 hang_monitor_timeout_->Stop();
894 RendererIsResponsive();
897 void RenderWidgetHostImpl::ForwardMouseEvent(const WebMouseEvent& mouse_event) {
898 ForwardMouseEventWithLatencyInfo(mouse_event, ui::LatencyInfo());
901 void RenderWidgetHostImpl::ForwardMouseEventWithLatencyInfo(
902 const blink::WebMouseEvent& mouse_event,
903 const ui::LatencyInfo& ui_latency) {
904 TRACE_EVENT2("input", "RenderWidgetHostImpl::ForwardMouseEvent",
905 "x", mouse_event.x, "y", mouse_event.y);
907 for (size_t i = 0; i < mouse_event_callbacks_.size(); ++i) {
908 if (mouse_event_callbacks_[i].Run(mouse_event))
909 return;
912 if (IgnoreInputEvents())
913 return;
915 if (touch_emulator_ && touch_emulator_->HandleMouseEvent(mouse_event))
916 return;
918 MouseEventWithLatencyInfo mouse_with_latency(mouse_event, ui_latency);
919 latency_tracker_.OnInputEvent(mouse_event, &mouse_with_latency.latency);
920 input_router_->SendMouseEvent(mouse_with_latency);
922 // Pass mouse state to gpu service if the subscribe uniform
923 // extension is enabled.
924 if (process_->SubscribeUniformEnabled()) {
925 gpu::ValueState state;
926 state.int_value[0] = mouse_event.x;
927 state.int_value[1] = mouse_event.y;
928 // TODO(orglofch) Separate the mapping of pending value states to the
929 // Gpu Service to be per RWH not per process
930 process_->SendUpdateValueState(GL_MOUSE_POSITION_CHROMIUM, state);
934 void RenderWidgetHostImpl::ForwardWheelEvent(
935 const WebMouseWheelEvent& wheel_event) {
936 ForwardWheelEventWithLatencyInfo(wheel_event, ui::LatencyInfo());
939 void RenderWidgetHostImpl::ForwardWheelEventWithLatencyInfo(
940 const blink::WebMouseWheelEvent& wheel_event,
941 const ui::LatencyInfo& ui_latency) {
942 TRACE_EVENT0("input", "RenderWidgetHostImpl::ForwardWheelEvent");
944 if (IgnoreInputEvents())
945 return;
947 if (touch_emulator_ && touch_emulator_->HandleMouseWheelEvent(wheel_event))
948 return;
950 MouseWheelEventWithLatencyInfo wheel_with_latency(wheel_event, ui_latency);
951 latency_tracker_.OnInputEvent(wheel_event, &wheel_with_latency.latency);
952 input_router_->SendWheelEvent(wheel_with_latency);
955 void RenderWidgetHostImpl::ForwardGestureEvent(
956 const blink::WebGestureEvent& gesture_event) {
957 ForwardGestureEventWithLatencyInfo(gesture_event, ui::LatencyInfo());
960 void RenderWidgetHostImpl::ForwardGestureEventWithLatencyInfo(
961 const blink::WebGestureEvent& gesture_event,
962 const ui::LatencyInfo& ui_latency) {
963 TRACE_EVENT0("input", "RenderWidgetHostImpl::ForwardGestureEvent");
964 // Early out if necessary, prior to performing latency logic.
965 if (IgnoreInputEvents())
966 return;
968 if (delegate_->PreHandleGestureEvent(gesture_event))
969 return;
971 GestureEventWithLatencyInfo gesture_with_latency(gesture_event, ui_latency);
972 latency_tracker_.OnInputEvent(gesture_event, &gesture_with_latency.latency);
973 input_router_->SendGestureEvent(gesture_with_latency);
976 void RenderWidgetHostImpl::ForwardEmulatedTouchEvent(
977 const blink::WebTouchEvent& touch_event) {
978 TRACE_EVENT0("input", "RenderWidgetHostImpl::ForwardEmulatedTouchEvent");
980 TouchEventWithLatencyInfo touch_with_latency(touch_event);
981 latency_tracker_.OnInputEvent(touch_event, &touch_with_latency.latency);
982 input_router_->SendTouchEvent(touch_with_latency);
985 void RenderWidgetHostImpl::ForwardTouchEventWithLatencyInfo(
986 const blink::WebTouchEvent& touch_event,
987 const ui::LatencyInfo& ui_latency) {
988 TRACE_EVENT0("input", "RenderWidgetHostImpl::ForwardTouchEvent");
990 // Always forward TouchEvents for touch stream consistency. They will be
991 // ignored if appropriate in FilterInputEvent().
993 TouchEventWithLatencyInfo touch_with_latency(touch_event, ui_latency);
994 if (touch_emulator_ &&
995 touch_emulator_->HandleTouchEvent(touch_with_latency.event)) {
996 if (view_) {
997 view_->ProcessAckedTouchEvent(
998 touch_with_latency, INPUT_EVENT_ACK_STATE_CONSUMED);
1000 return;
1003 latency_tracker_.OnInputEvent(touch_event, &touch_with_latency.latency);
1004 input_router_->SendTouchEvent(touch_with_latency);
1007 void RenderWidgetHostImpl::ForwardKeyboardEvent(
1008 const NativeWebKeyboardEvent& key_event) {
1009 TRACE_EVENT0("input", "RenderWidgetHostImpl::ForwardKeyboardEvent");
1010 if (IgnoreInputEvents())
1011 return;
1013 if (!process_->HasConnection())
1014 return;
1016 // First, let keypress listeners take a shot at handling the event. If a
1017 // listener handles the event, it should not be propagated to the renderer.
1018 if (KeyPressListenersHandleEvent(key_event)) {
1019 // Some keypresses that are accepted by the listener might have follow up
1020 // char events, which should be ignored.
1021 if (key_event.type == WebKeyboardEvent::RawKeyDown)
1022 suppress_next_char_events_ = true;
1023 return;
1026 if (key_event.type == WebKeyboardEvent::Char &&
1027 (key_event.windowsKeyCode == ui::VKEY_RETURN ||
1028 key_event.windowsKeyCode == ui::VKEY_SPACE)) {
1029 OnUserGesture();
1032 // Double check the type to make sure caller hasn't sent us nonsense that
1033 // will mess up our key queue.
1034 if (!WebInputEvent::isKeyboardEventType(key_event.type))
1035 return;
1037 if (suppress_next_char_events_) {
1038 // If preceding RawKeyDown event was handled by the browser, then we need
1039 // suppress all Char events generated by it. Please note that, one
1040 // RawKeyDown event may generate multiple Char events, so we can't reset
1041 // |suppress_next_char_events_| until we get a KeyUp or a RawKeyDown.
1042 if (key_event.type == WebKeyboardEvent::Char)
1043 return;
1044 // We get a KeyUp or a RawKeyDown event.
1045 suppress_next_char_events_ = false;
1048 bool is_shortcut = false;
1050 // Only pre-handle the key event if it's not handled by the input method.
1051 if (delegate_ && !key_event.skip_in_browser) {
1052 // We need to set |suppress_next_char_events_| to true if
1053 // PreHandleKeyboardEvent() returns true, but |this| may already be
1054 // destroyed at that time. So set |suppress_next_char_events_| true here,
1055 // then revert it afterwards when necessary.
1056 if (key_event.type == WebKeyboardEvent::RawKeyDown)
1057 suppress_next_char_events_ = true;
1059 // Tab switching/closing accelerators aren't sent to the renderer to avoid
1060 // a hung/malicious renderer from interfering.
1061 if (delegate_->PreHandleKeyboardEvent(key_event, &is_shortcut))
1062 return;
1064 if (key_event.type == WebKeyboardEvent::RawKeyDown)
1065 suppress_next_char_events_ = false;
1068 if (touch_emulator_ && touch_emulator_->HandleKeyboardEvent(key_event))
1069 return;
1071 ui::LatencyInfo latency;
1072 latency_tracker_.OnInputEvent(key_event, &latency);
1073 input_router_->SendKeyboardEvent(key_event, latency, is_shortcut);
1076 void RenderWidgetHostImpl::QueueSyntheticGesture(
1077 scoped_ptr<SyntheticGesture> synthetic_gesture,
1078 const base::Callback<void(SyntheticGesture::Result)>& on_complete) {
1079 if (!synthetic_gesture_controller_ && view_) {
1080 synthetic_gesture_controller_.reset(
1081 new SyntheticGestureController(
1082 view_->CreateSyntheticGestureTarget().Pass()));
1084 if (synthetic_gesture_controller_) {
1085 synthetic_gesture_controller_->QueueSyntheticGesture(
1086 synthetic_gesture.Pass(), on_complete);
1090 void RenderWidgetHostImpl::SetCursor(const WebCursor& cursor) {
1091 if (!view_)
1092 return;
1093 view_->UpdateCursor(cursor);
1096 void RenderWidgetHostImpl::ShowContextMenuAtPoint(const gfx::Point& point) {
1097 Send(new ViewMsg_ShowContextMenu(
1098 GetRoutingID(), ui::MENU_SOURCE_MOUSE, point));
1101 void RenderWidgetHostImpl::SendCursorVisibilityState(bool is_visible) {
1102 Send(new InputMsg_CursorVisibilityChange(GetRoutingID(), is_visible));
1105 int64 RenderWidgetHostImpl::GetLatencyComponentId() const {
1106 return latency_tracker_.latency_component_id();
1109 // static
1110 void RenderWidgetHostImpl::DisableResizeAckCheckForTesting() {
1111 g_check_for_pending_resize_ack = false;
1114 void RenderWidgetHostImpl::AddKeyPressEventCallback(
1115 const KeyPressEventCallback& callback) {
1116 key_press_event_callbacks_.push_back(callback);
1119 void RenderWidgetHostImpl::RemoveKeyPressEventCallback(
1120 const KeyPressEventCallback& callback) {
1121 for (size_t i = 0; i < key_press_event_callbacks_.size(); ++i) {
1122 if (key_press_event_callbacks_[i].Equals(callback)) {
1123 key_press_event_callbacks_.erase(
1124 key_press_event_callbacks_.begin() + i);
1125 return;
1130 void RenderWidgetHostImpl::AddMouseEventCallback(
1131 const MouseEventCallback& callback) {
1132 mouse_event_callbacks_.push_back(callback);
1135 void RenderWidgetHostImpl::RemoveMouseEventCallback(
1136 const MouseEventCallback& callback) {
1137 for (size_t i = 0; i < mouse_event_callbacks_.size(); ++i) {
1138 if (mouse_event_callbacks_[i].Equals(callback)) {
1139 mouse_event_callbacks_.erase(mouse_event_callbacks_.begin() + i);
1140 return;
1145 void RenderWidgetHostImpl::GetWebScreenInfo(blink::WebScreenInfo* result) {
1146 TRACE_EVENT0("renderer_host", "RenderWidgetHostImpl::GetWebScreenInfo");
1147 if (view_)
1148 view_->GetScreenInfo(result);
1149 else
1150 RenderWidgetHostViewBase::GetDefaultScreenInfo(result);
1151 // TODO(sievers): find a way to make this done another way so the method
1152 // can be const.
1153 latency_tracker_.set_device_scale_factor(result->deviceScaleFactor);
1156 const NativeWebKeyboardEvent*
1157 RenderWidgetHostImpl::GetLastKeyboardEvent() const {
1158 return input_router_->GetLastKeyboardEvent();
1161 void RenderWidgetHostImpl::NotifyScreenInfoChanged() {
1162 if (delegate_)
1163 delegate_->ScreenInfoChanged();
1165 // The resize message (which may not happen immediately) will carry with it
1166 // the screen info as well as the new size (if the screen has changed scale
1167 // factor).
1168 WasResized();
1171 void RenderWidgetHostImpl::GetSnapshotFromBrowser(
1172 const base::Callback<void(const unsigned char*,size_t)> callback) {
1173 int id = next_browser_snapshot_id_++;
1174 pending_browser_snapshots_.insert(std::make_pair(id, callback));
1175 Send(new ViewMsg_ForceRedraw(GetRoutingID(), id));
1178 void RenderWidgetHostImpl::OnSelectionChanged(const base::string16& text,
1179 size_t offset,
1180 const gfx::Range& range) {
1181 if (view_)
1182 view_->SelectionChanged(text, offset, range);
1185 void RenderWidgetHostImpl::OnSelectionBoundsChanged(
1186 const ViewHostMsg_SelectionBounds_Params& params) {
1187 if (view_) {
1188 view_->SelectionBoundsChanged(params);
1192 void RenderWidgetHostImpl::UpdateVSyncParameters(base::TimeTicks timebase,
1193 base::TimeDelta interval) {
1194 Send(new ViewMsg_UpdateVSyncParameters(GetRoutingID(), timebase, interval));
1197 void RenderWidgetHostImpl::RendererExited(base::TerminationStatus status,
1198 int exit_code) {
1199 if (!renderer_initialized_)
1200 return;
1202 // Clearing this flag causes us to re-create the renderer when recovering
1203 // from a crashed renderer.
1204 renderer_initialized_ = false;
1206 waiting_for_screen_rects_ack_ = false;
1208 // Must reset these to ensure that keyboard events work with a new renderer.
1209 suppress_next_char_events_ = false;
1211 // Reset some fields in preparation for recovering from a crash.
1212 ResetSizeAndRepaintPendingFlags();
1213 current_size_.SetSize(0, 0);
1214 // After the renderer crashes, the view is destroyed and so the
1215 // RenderWidgetHost cannot track its visibility anymore. We assume such
1216 // RenderWidgetHost to be visible for the sake of internal accounting - be
1217 // careful about changing this - see http://crbug.com/401859.
1219 // We need to at least make sure that the RenderProcessHost is notified about
1220 // the |is_hidden_| change, so that the renderer will have correct visibility
1221 // set when respawned.
1222 if (is_hidden_) {
1223 process_->WidgetRestored();
1224 is_hidden_ = false;
1227 // Reset this to ensure the hung renderer mechanism is working properly.
1228 in_flight_event_count_ = 0;
1229 StopHangMonitorTimeout();
1231 if (view_) {
1232 GpuSurfaceTracker::Get()->SetSurfaceHandle(surface_id_,
1233 gfx::GLSurfaceHandle());
1234 view_->RenderProcessGone(status, exit_code);
1235 view_ = NULL; // The View should be deleted by RenderProcessGone.
1236 view_weak_.reset();
1239 // Reconstruct the input router to ensure that it has fresh state for a new
1240 // renderer. Otherwise it may be stuck waiting for the old renderer to ack an
1241 // event. (In particular, the above call to view_->RenderProcessGone will
1242 // destroy the aura window, which may dispatch a synthetic mouse move.)
1243 input_router_.reset(new InputRouterImpl(
1244 process_, this, this, routing_id_, GetInputRouterConfigForPlatform()));
1246 synthetic_gesture_controller_.reset();
1249 void RenderWidgetHostImpl::UpdateTextDirection(WebTextDirection direction) {
1250 text_direction_updated_ = true;
1251 text_direction_ = direction;
1254 void RenderWidgetHostImpl::CancelUpdateTextDirection() {
1255 if (text_direction_updated_)
1256 text_direction_canceled_ = true;
1259 void RenderWidgetHostImpl::NotifyTextDirection() {
1260 if (text_direction_updated_) {
1261 if (!text_direction_canceled_)
1262 Send(new ViewMsg_SetTextDirection(GetRoutingID(), text_direction_));
1263 text_direction_updated_ = false;
1264 text_direction_canceled_ = false;
1268 void RenderWidgetHostImpl::SetInputMethodActive(bool activate) {
1269 input_method_active_ = activate;
1270 Send(new ViewMsg_SetInputMethodActive(GetRoutingID(), activate));
1273 void RenderWidgetHostImpl::ImeSetComposition(
1274 const base::string16& text,
1275 const std::vector<blink::WebCompositionUnderline>& underlines,
1276 int selection_start,
1277 int selection_end) {
1278 Send(new InputMsg_ImeSetComposition(
1279 GetRoutingID(), text, underlines, selection_start, selection_end));
1282 void RenderWidgetHostImpl::ImeConfirmComposition(
1283 const base::string16& text,
1284 const gfx::Range& replacement_range,
1285 bool keep_selection) {
1286 Send(new InputMsg_ImeConfirmComposition(
1287 GetRoutingID(), text, replacement_range, keep_selection));
1290 void RenderWidgetHostImpl::ImeCancelComposition() {
1291 Send(new InputMsg_ImeSetComposition(GetRoutingID(), base::string16(),
1292 std::vector<blink::WebCompositionUnderline>(), 0, 0));
1295 gfx::Rect RenderWidgetHostImpl::GetRootWindowResizerRect() const {
1296 return gfx::Rect();
1299 void RenderWidgetHostImpl::RequestToLockMouse(bool user_gesture,
1300 bool last_unlocked_by_target) {
1301 // Directly reject to lock the mouse. Subclass can override this method to
1302 // decide whether to allow mouse lock or not.
1303 GotResponseToLockMouseRequest(false);
1306 void RenderWidgetHostImpl::RejectMouseLockOrUnlockIfNecessary() {
1307 DCHECK(!pending_mouse_lock_request_ || !IsMouseLocked());
1308 if (pending_mouse_lock_request_) {
1309 pending_mouse_lock_request_ = false;
1310 Send(new ViewMsg_LockMouse_ACK(routing_id_, false));
1311 } else if (IsMouseLocked()) {
1312 view_->UnlockMouse();
1316 bool RenderWidgetHostImpl::IsMouseLocked() const {
1317 return view_ ? view_->IsMouseLocked() : false;
1320 bool RenderWidgetHostImpl::IsFullscreenGranted() const {
1321 return false;
1324 blink::WebDisplayMode RenderWidgetHostImpl::GetDisplayMode() const {
1325 return blink::WebDisplayModeBrowser;
1328 void RenderWidgetHostImpl::SetAutoResize(bool enable,
1329 const gfx::Size& min_size,
1330 const gfx::Size& max_size) {
1331 auto_resize_enabled_ = enable;
1332 min_size_for_auto_resize_ = min_size;
1333 max_size_for_auto_resize_ = max_size;
1336 void RenderWidgetHostImpl::Destroy() {
1337 NotificationService::current()->Notify(
1338 NOTIFICATION_RENDER_WIDGET_HOST_DESTROYED,
1339 Source<RenderWidgetHost>(this),
1340 NotificationService::NoDetails());
1342 // Tell the view to die.
1343 // Note that in the process of the view shutting down, it can call a ton
1344 // of other messages on us. So if you do any other deinitialization here,
1345 // do it after this call to view_->Destroy().
1346 if (view_) {
1347 view_->Destroy();
1348 view_ = nullptr;
1351 delete this;
1354 void RenderWidgetHostImpl::RendererIsUnresponsive() {
1355 NotificationService::current()->Notify(
1356 NOTIFICATION_RENDER_WIDGET_HOST_HANG,
1357 Source<RenderWidgetHost>(this),
1358 NotificationService::NoDetails());
1359 is_unresponsive_ = true;
1360 NotifyRendererUnresponsive();
1363 void RenderWidgetHostImpl::RendererIsResponsive() {
1364 if (is_unresponsive_) {
1365 is_unresponsive_ = false;
1366 NotifyRendererResponsive();
1370 void RenderWidgetHostImpl::OnRenderViewReady() {
1371 SendScreenRects();
1372 WasResized();
1375 void RenderWidgetHostImpl::OnRenderProcessGone(int status, int exit_code) {
1376 // RenderFrameHost owns a RenderWidgetHost when it needs one, in which case
1377 // it handles destruction.
1378 if (!owned_by_render_frame_host_) {
1379 // TODO(evanm): This synchronously ends up calling "delete this".
1380 // Is that really what we want in response to this message? I'm matching
1381 // previous behavior of the code here.
1382 Destroy();
1383 } else {
1384 RendererExited(static_cast<base::TerminationStatus>(status), exit_code);
1388 void RenderWidgetHostImpl::OnClose() {
1389 Shutdown();
1392 void RenderWidgetHostImpl::OnSetTooltipText(
1393 const base::string16& tooltip_text,
1394 WebTextDirection text_direction_hint) {
1395 // First, add directionality marks around tooltip text if necessary.
1396 // A naive solution would be to simply always wrap the text. However, on
1397 // windows, Unicode directional embedding characters can't be displayed on
1398 // systems that lack RTL fonts and are instead displayed as empty squares.
1400 // To get around this we only wrap the string when we deem it necessary i.e.
1401 // when the locale direction is different than the tooltip direction hint.
1403 // Currently, we use element's directionality as the tooltip direction hint.
1404 // An alternate solution would be to set the overall directionality based on
1405 // trying to detect the directionality from the tooltip text rather than the
1406 // element direction. One could argue that would be a preferable solution
1407 // but we use the current approach to match Fx & IE's behavior.
1408 base::string16 wrapped_tooltip_text = tooltip_text;
1409 if (!tooltip_text.empty()) {
1410 if (text_direction_hint == blink::WebTextDirectionLeftToRight) {
1411 // Force the tooltip to have LTR directionality.
1412 wrapped_tooltip_text =
1413 base::i18n::GetDisplayStringInLTRDirectionality(wrapped_tooltip_text);
1414 } else if (text_direction_hint == blink::WebTextDirectionRightToLeft &&
1415 !base::i18n::IsRTL()) {
1416 // Force the tooltip to have RTL directionality.
1417 base::i18n::WrapStringWithRTLFormatting(&wrapped_tooltip_text);
1420 if (GetView())
1421 view_->SetTooltipText(wrapped_tooltip_text);
1424 void RenderWidgetHostImpl::OnUpdateScreenRectsAck() {
1425 waiting_for_screen_rects_ack_ = false;
1426 if (!view_)
1427 return;
1429 if (view_->GetViewBounds() == last_view_screen_rect_ &&
1430 view_->GetBoundsInRootWindow() == last_window_screen_rect_) {
1431 return;
1434 SendScreenRects();
1437 void RenderWidgetHostImpl::OnRequestMove(const gfx::Rect& pos) {
1438 if (view_) {
1439 view_->SetBounds(pos);
1440 Send(new ViewMsg_Move_ACK(routing_id_));
1444 bool RenderWidgetHostImpl::OnSwapCompositorFrame(
1445 const IPC::Message& message) {
1446 // This trace event is used in
1447 // chrome/browser/extensions/api/cast_streaming/performance_test.cc
1448 TRACE_EVENT0("test_fps,benchmark", "OnSwapCompositorFrame");
1449 ViewHostMsg_SwapCompositorFrame::Param param;
1450 if (!ViewHostMsg_SwapCompositorFrame::Read(&message, &param))
1451 return false;
1452 scoped_ptr<cc::CompositorFrame> frame(new cc::CompositorFrame);
1453 uint32 output_surface_id = base::get<0>(param);
1454 base::get<1>(param).AssignTo(frame.get());
1455 std::vector<IPC::Message> messages_to_deliver_with_frame;
1456 messages_to_deliver_with_frame.swap(base::get<2>(param));
1458 latency_tracker_.OnSwapCompositorFrame(&frame->metadata.latency_info);
1460 input_router_->OnViewUpdated(
1461 GetInputRouterViewFlagsFromCompositorFrameMetadata(frame->metadata));
1463 if (touch_emulator_) {
1464 touch_emulator_->SetDoubleTapSupportForPageEnabled(
1465 !IsMobileOptimizedFrame(frame->metadata));
1468 if (view_) {
1469 view_->OnSwapCompositorFrame(output_surface_id, frame.Pass());
1470 view_->DidReceiveRendererFrame();
1471 } else {
1472 cc::CompositorFrameAck ack;
1473 if (frame->gl_frame_data) {
1474 ack.gl_frame_data = frame->gl_frame_data.Pass();
1475 ack.gl_frame_data->sync_point = 0;
1476 } else if (frame->delegated_frame_data) {
1477 cc::TransferableResource::ReturnResources(
1478 frame->delegated_frame_data->resource_list,
1479 &ack.resources);
1480 } else if (frame->software_frame_data) {
1481 ack.last_software_frame_id = frame->software_frame_data->id;
1483 SendSwapCompositorFrameAck(routing_id_, output_surface_id,
1484 process_->GetID(), ack);
1487 RenderProcessHost* rph = GetProcess();
1488 for (std::vector<IPC::Message>::const_iterator i =
1489 messages_to_deliver_with_frame.begin();
1490 i != messages_to_deliver_with_frame.end();
1491 ++i) {
1492 rph->OnMessageReceived(*i);
1493 if (i->dispatch_error())
1494 rph->OnBadMessageReceived(*i);
1496 messages_to_deliver_with_frame.clear();
1498 return true;
1501 void RenderWidgetHostImpl::OnUpdateRect(
1502 const ViewHostMsg_UpdateRect_Params& params) {
1503 TRACE_EVENT0("renderer_host", "RenderWidgetHostImpl::OnUpdateRect");
1504 TimeTicks paint_start = TimeTicks::Now();
1506 // Update our knowledge of the RenderWidget's size.
1507 current_size_ = params.view_size;
1509 bool is_resize_ack =
1510 ViewHostMsg_UpdateRect_Flags::is_resize_ack(params.flags);
1512 // resize_ack_pending_ needs to be cleared before we call DidPaintRect, since
1513 // that will end up reaching GetBackingStore.
1514 if (is_resize_ack) {
1515 DCHECK(!g_check_for_pending_resize_ack || resize_ack_pending_);
1516 resize_ack_pending_ = false;
1519 bool is_repaint_ack =
1520 ViewHostMsg_UpdateRect_Flags::is_repaint_ack(params.flags);
1521 if (is_repaint_ack) {
1522 DCHECK(repaint_ack_pending_);
1523 TRACE_EVENT_ASYNC_END0(
1524 "renderer_host", "RenderWidgetHostImpl::repaint_ack_pending_", this);
1525 repaint_ack_pending_ = false;
1526 TimeDelta delta = TimeTicks::Now() - repaint_start_time_;
1527 UMA_HISTOGRAM_TIMES("MPArch.RWH_RepaintDelta", delta);
1530 DCHECK(!params.view_size.IsEmpty());
1532 DidUpdateBackingStore(params, paint_start);
1534 if (auto_resize_enabled_) {
1535 bool post_callback = new_auto_size_.IsEmpty();
1536 new_auto_size_ = params.view_size;
1537 if (post_callback) {
1538 base::ThreadTaskRunnerHandle::Get()->PostTask(
1539 FROM_HERE, base::Bind(&RenderWidgetHostImpl::DelayedAutoResized,
1540 weak_factory_.GetWeakPtr()));
1544 // Log the time delta for processing a paint message. On platforms that don't
1545 // support asynchronous painting, this is equivalent to
1546 // MPArch.RWH_TotalPaintTime.
1547 TimeDelta delta = TimeTicks::Now() - paint_start;
1548 UMA_HISTOGRAM_TIMES("MPArch.RWH_OnMsgUpdateRect", delta);
1551 void RenderWidgetHostImpl::DidUpdateBackingStore(
1552 const ViewHostMsg_UpdateRect_Params& params,
1553 const TimeTicks& paint_start) {
1554 TRACE_EVENT0("renderer_host", "RenderWidgetHostImpl::DidUpdateBackingStore");
1555 TimeTicks update_start = TimeTicks::Now();
1557 // Move the plugins if the view hasn't already been destroyed. Plugin moves
1558 // will not be re-issued, so must move them now, regardless of whether we
1559 // paint or not. MovePluginWindows attempts to move the plugin windows and
1560 // in the process could dispatch other window messages which could cause the
1561 // view to be destroyed.
1562 if (view_)
1563 view_->MovePluginWindows(params.plugin_window_moves);
1565 NotificationService::current()->Notify(
1566 NOTIFICATION_RENDER_WIDGET_HOST_DID_UPDATE_BACKING_STORE,
1567 Source<RenderWidgetHost>(this),
1568 NotificationService::NoDetails());
1570 // We don't need to update the view if the view is hidden. We must do this
1571 // early return after the ACK is sent, however, or the renderer will not send
1572 // us more data.
1573 if (is_hidden_)
1574 return;
1576 // If we got a resize ack, then perhaps we have another resize to send?
1577 bool is_resize_ack =
1578 ViewHostMsg_UpdateRect_Flags::is_resize_ack(params.flags);
1579 if (is_resize_ack)
1580 WasResized();
1582 // Log the time delta for processing a paint message.
1583 TimeTicks now = TimeTicks::Now();
1584 TimeDelta delta = now - update_start;
1585 UMA_HISTOGRAM_TIMES("MPArch.RWH_DidUpdateBackingStore", delta);
1588 void RenderWidgetHostImpl::OnQueueSyntheticGesture(
1589 const SyntheticGesturePacket& gesture_packet) {
1590 // Only allow untrustworthy gestures if explicitly enabled.
1591 if (!base::CommandLine::ForCurrentProcess()->HasSwitch(
1592 cc::switches::kEnableGpuBenchmarking)) {
1593 bad_message::ReceivedBadMessage(GetProcess(),
1594 bad_message::RWH_SYNTHETIC_GESTURE);
1595 return;
1598 QueueSyntheticGesture(
1599 SyntheticGesture::Create(*gesture_packet.gesture_params()),
1600 base::Bind(&RenderWidgetHostImpl::OnSyntheticGestureCompleted,
1601 weak_factory_.GetWeakPtr()));
1604 void RenderWidgetHostImpl::OnFocus() {
1605 // Only RenderViewHost can deal with that message.
1606 bad_message::ReceivedBadMessage(GetProcess(), bad_message::RWH_FOCUS);
1609 void RenderWidgetHostImpl::OnBlur() {
1610 // Only RenderViewHost can deal with that message.
1611 bad_message::ReceivedBadMessage(GetProcess(), bad_message::RWH_BLUR);
1614 void RenderWidgetHostImpl::OnSetCursor(const WebCursor& cursor) {
1615 SetCursor(cursor);
1618 void RenderWidgetHostImpl::SetTouchEventEmulationEnabled(
1619 bool enabled, ui::GestureProviderConfigType config_type) {
1620 if (enabled) {
1621 if (!touch_emulator_)
1622 touch_emulator_.reset(new TouchEmulator(this));
1623 touch_emulator_->Enable(config_type);
1624 } else {
1625 if (touch_emulator_)
1626 touch_emulator_->Disable();
1630 void RenderWidgetHostImpl::OnTextInputTypeChanged(
1631 ui::TextInputType type,
1632 ui::TextInputMode input_mode,
1633 bool can_compose_inline,
1634 int flags) {
1635 if (view_)
1636 view_->TextInputTypeChanged(type, input_mode, can_compose_inline, flags);
1639 void RenderWidgetHostImpl::OnImeCompositionRangeChanged(
1640 const gfx::Range& range,
1641 const std::vector<gfx::Rect>& character_bounds) {
1642 if (view_)
1643 view_->ImeCompositionRangeChanged(range, character_bounds);
1646 void RenderWidgetHostImpl::OnImeCancelComposition() {
1647 if (view_)
1648 view_->ImeCancelComposition();
1651 void RenderWidgetHostImpl::OnLockMouse(bool user_gesture,
1652 bool last_unlocked_by_target,
1653 bool privileged) {
1655 if (pending_mouse_lock_request_) {
1656 Send(new ViewMsg_LockMouse_ACK(routing_id_, false));
1657 return;
1658 } else if (IsMouseLocked()) {
1659 Send(new ViewMsg_LockMouse_ACK(routing_id_, true));
1660 return;
1663 pending_mouse_lock_request_ = true;
1664 if (privileged && allow_privileged_mouse_lock_) {
1665 // Directly approve to lock the mouse.
1666 GotResponseToLockMouseRequest(true);
1667 } else {
1668 RequestToLockMouse(user_gesture, last_unlocked_by_target);
1672 void RenderWidgetHostImpl::OnUnlockMouse() {
1673 RejectMouseLockOrUnlockIfNecessary();
1676 void RenderWidgetHostImpl::OnShowDisambiguationPopup(
1677 const gfx::Rect& rect_pixels,
1678 const gfx::Size& size,
1679 const cc::SharedBitmapId& id) {
1680 DCHECK(!rect_pixels.IsEmpty());
1681 DCHECK(!size.IsEmpty());
1683 scoped_ptr<cc::SharedBitmap> bitmap =
1684 HostSharedBitmapManager::current()->GetSharedBitmapFromId(size, id);
1685 if (!bitmap) {
1686 bad_message::ReceivedBadMessage(GetProcess(),
1687 bad_message::RWH_SHARED_BITMAP);
1688 return;
1691 DCHECK(bitmap->pixels());
1693 SkImageInfo info = SkImageInfo::MakeN32Premul(size.width(), size.height());
1694 SkBitmap zoomed_bitmap;
1695 zoomed_bitmap.installPixels(info, bitmap->pixels(), info.minRowBytes());
1697 // Note that |rect| is in coordinates of pixels relative to the window origin.
1698 // Aura-based systems will want to convert this to DIPs.
1699 if (view_)
1700 view_->ShowDisambiguationPopup(rect_pixels, zoomed_bitmap);
1702 // It is assumed that the disambiguation popup will make a copy of the
1703 // provided zoomed image, so we delete this one.
1704 zoomed_bitmap.setPixels(0);
1705 Send(new ViewMsg_ReleaseDisambiguationPopupBitmap(GetRoutingID(), id));
1708 #if defined(OS_WIN)
1709 void RenderWidgetHostImpl::OnWindowlessPluginDummyWindowCreated(
1710 gfx::NativeViewId dummy_activation_window) {
1711 HWND hwnd = reinterpret_cast<HWND>(dummy_activation_window);
1713 // This may happen as a result of a race condition when the plugin is going
1714 // away.
1715 wchar_t window_title[MAX_PATH + 1] = {0};
1716 if (!IsWindow(hwnd) ||
1717 !GetWindowText(hwnd, window_title, arraysize(window_title)) ||
1718 lstrcmpiW(window_title, kDummyActivationWindowName) != 0) {
1719 return;
1722 #if defined(USE_AURA)
1723 SetParent(hwnd,
1724 reinterpret_cast<HWND>(view_->GetParentForWindowlessPlugin()));
1725 #else
1726 SetParent(hwnd, reinterpret_cast<HWND>(GetNativeViewId()));
1727 #endif
1728 dummy_windows_for_activation_.push_back(hwnd);
1731 void RenderWidgetHostImpl::OnWindowlessPluginDummyWindowDestroyed(
1732 gfx::NativeViewId dummy_activation_window) {
1733 HWND hwnd = reinterpret_cast<HWND>(dummy_activation_window);
1734 std::list<HWND>::iterator i = dummy_windows_for_activation_.begin();
1735 for (; i != dummy_windows_for_activation_.end(); ++i) {
1736 if ((*i) == hwnd) {
1737 dummy_windows_for_activation_.erase(i);
1738 return;
1741 NOTREACHED() << "Unknown dummy window";
1743 #endif
1745 void RenderWidgetHostImpl::SetIgnoreInputEvents(bool ignore_input_events) {
1746 ignore_input_events_ = ignore_input_events;
1749 bool RenderWidgetHostImpl::KeyPressListenersHandleEvent(
1750 const NativeWebKeyboardEvent& event) {
1751 if (event.skip_in_browser || event.type != WebKeyboardEvent::RawKeyDown)
1752 return false;
1754 for (size_t i = 0; i < key_press_event_callbacks_.size(); i++) {
1755 size_t original_size = key_press_event_callbacks_.size();
1756 if (key_press_event_callbacks_[i].Run(event))
1757 return true;
1759 // Check whether the callback that just ran removed itself, in which case
1760 // the iterator needs to be decremented to properly account for the removal.
1761 size_t current_size = key_press_event_callbacks_.size();
1762 if (current_size != original_size) {
1763 DCHECK_EQ(original_size - 1, current_size);
1764 --i;
1768 return false;
1771 InputEventAckState RenderWidgetHostImpl::FilterInputEvent(
1772 const blink::WebInputEvent& event, const ui::LatencyInfo& latency_info) {
1773 // Don't ignore touch cancel events, since they may be sent while input
1774 // events are being ignored in order to keep the renderer from getting
1775 // confused about how many touches are active.
1776 if (IgnoreInputEvents() && event.type != WebInputEvent::TouchCancel)
1777 return INPUT_EVENT_ACK_STATE_NO_CONSUMER_EXISTS;
1779 if (!process_->HasConnection())
1780 return INPUT_EVENT_ACK_STATE_UNKNOWN;
1782 if (event.type == WebInputEvent::MouseDown ||
1783 event.type == WebInputEvent::GestureTapDown) {
1784 OnUserGesture();
1787 return view_ ? view_->FilterInputEvent(event)
1788 : INPUT_EVENT_ACK_STATE_NOT_CONSUMED;
1791 void RenderWidgetHostImpl::IncrementInFlightEventCount() {
1792 increment_in_flight_event_count();
1793 if (!is_hidden_)
1794 StartHangMonitorTimeout(hung_renderer_delay_);
1797 void RenderWidgetHostImpl::DecrementInFlightEventCount() {
1798 if (decrement_in_flight_event_count() <= 0) {
1799 // Cancel pending hung renderer checks since the renderer is responsive.
1800 StopHangMonitorTimeout();
1801 } else {
1802 // The renderer is responsive, but there are in-flight events to wait for.
1803 if (!is_hidden_)
1804 RestartHangMonitorTimeout();
1808 void RenderWidgetHostImpl::OnHasTouchEventHandlers(bool has_handlers) {
1809 has_touch_handler_ = has_handlers;
1812 void RenderWidgetHostImpl::DidFlush() {
1813 if (synthetic_gesture_controller_)
1814 synthetic_gesture_controller_->OnDidFlushInput();
1817 void RenderWidgetHostImpl::DidOverscroll(const DidOverscrollParams& params) {
1818 if (view_)
1819 view_->DidOverscroll(params);
1822 void RenderWidgetHostImpl::DidStopFlinging() {
1823 if (view_)
1824 view_->DidStopFlinging();
1827 void RenderWidgetHostImpl::OnKeyboardEventAck(
1828 const NativeWebKeyboardEvent& event,
1829 InputEventAckState ack_result) {
1830 #if defined(OS_MACOSX)
1831 if (!is_hidden() && view_ && view_->PostProcessEventForPluginIme(event))
1832 return;
1833 #endif
1835 // We only send unprocessed key event upwards if we are not hidden,
1836 // because the user has moved away from us and no longer expect any effect
1837 // of this key event.
1838 const bool processed = (INPUT_EVENT_ACK_STATE_CONSUMED == ack_result);
1839 if (delegate_ && !processed && !is_hidden() && !event.skip_in_browser) {
1840 delegate_->HandleKeyboardEvent(event);
1842 // WARNING: This RenderWidgetHostImpl can be deallocated at this point
1843 // (i.e. in the case of Ctrl+W, where the call to
1844 // HandleKeyboardEvent destroys this RenderWidgetHostImpl).
1848 void RenderWidgetHostImpl::OnWheelEventAck(
1849 const MouseWheelEventWithLatencyInfo& wheel_event,
1850 InputEventAckState ack_result) {
1851 latency_tracker_.OnInputEventAck(wheel_event.event, &wheel_event.latency);
1853 if (!is_hidden() && view_) {
1854 if (ack_result != INPUT_EVENT_ACK_STATE_CONSUMED &&
1855 delegate_->HandleWheelEvent(wheel_event.event)) {
1856 ack_result = INPUT_EVENT_ACK_STATE_CONSUMED;
1858 view_->WheelEventAck(wheel_event.event, ack_result);
1862 void RenderWidgetHostImpl::OnGestureEventAck(
1863 const GestureEventWithLatencyInfo& event,
1864 InputEventAckState ack_result) {
1865 latency_tracker_.OnInputEventAck(event.event, &event.latency);
1867 if (view_)
1868 view_->GestureEventAck(event.event, ack_result);
1871 void RenderWidgetHostImpl::OnTouchEventAck(
1872 const TouchEventWithLatencyInfo& event,
1873 InputEventAckState ack_result) {
1874 latency_tracker_.OnInputEventAck(event.event, &event.latency);
1876 if (touch_emulator_ &&
1877 touch_emulator_->HandleTouchEventAck(event.event, ack_result)) {
1878 return;
1881 if (view_)
1882 view_->ProcessAckedTouchEvent(event, ack_result);
1885 void RenderWidgetHostImpl::OnUnexpectedEventAck(UnexpectedEventAckType type) {
1886 if (type == BAD_ACK_MESSAGE) {
1887 bad_message::ReceivedBadMessage(process_, bad_message::RWH_BAD_ACK_MESSAGE);
1888 } else if (type == UNEXPECTED_EVENT_TYPE) {
1889 suppress_next_char_events_ = false;
1893 void RenderWidgetHostImpl::OnSyntheticGestureCompleted(
1894 SyntheticGesture::Result result) {
1895 Send(new InputMsg_SyntheticGestureCompleted(GetRoutingID()));
1898 bool RenderWidgetHostImpl::IgnoreInputEvents() const {
1899 return ignore_input_events_ || process_->IgnoreInputEvents();
1902 void RenderWidgetHostImpl::StartUserGesture() {
1903 OnUserGesture();
1906 void RenderWidgetHostImpl::SetBackgroundOpaque(bool opaque) {
1907 Send(new ViewMsg_SetBackgroundOpaque(GetRoutingID(), opaque));
1910 void RenderWidgetHostImpl::SetEditCommandsForNextKeyEvent(
1911 const std::vector<EditCommand>& commands) {
1912 Send(new InputMsg_SetEditCommandsForNextKeyEvent(GetRoutingID(), commands));
1915 void RenderWidgetHostImpl::ExecuteEditCommand(const std::string& command,
1916 const std::string& value) {
1917 Send(new InputMsg_ExecuteEditCommand(GetRoutingID(), command, value));
1920 void RenderWidgetHostImpl::ScrollFocusedEditableNodeIntoRect(
1921 const gfx::Rect& rect) {
1922 Send(new InputMsg_ScrollFocusedEditableNodeIntoRect(GetRoutingID(), rect));
1925 void RenderWidgetHostImpl::MoveCaret(const gfx::Point& point) {
1926 Send(new InputMsg_MoveCaret(GetRoutingID(), point));
1929 bool RenderWidgetHostImpl::GotResponseToLockMouseRequest(bool allowed) {
1930 if (!allowed) {
1931 RejectMouseLockOrUnlockIfNecessary();
1932 return false;
1933 } else {
1934 if (!pending_mouse_lock_request_) {
1935 // This is possible, e.g., the plugin sends us an unlock request before
1936 // the user allows to lock to mouse.
1937 return false;
1940 pending_mouse_lock_request_ = false;
1941 if (!view_ || !view_->HasFocus()|| !view_->LockMouse()) {
1942 Send(new ViewMsg_LockMouse_ACK(routing_id_, false));
1943 return false;
1944 } else {
1945 Send(new ViewMsg_LockMouse_ACK(routing_id_, true));
1946 return true;
1951 // static
1952 void RenderWidgetHostImpl::SendSwapCompositorFrameAck(
1953 int32 route_id,
1954 uint32 output_surface_id,
1955 int renderer_host_id,
1956 const cc::CompositorFrameAck& ack) {
1957 RenderProcessHost* host = RenderProcessHost::FromID(renderer_host_id);
1958 if (!host)
1959 return;
1960 host->Send(new ViewMsg_SwapCompositorFrameAck(
1961 route_id, output_surface_id, ack));
1964 // static
1965 void RenderWidgetHostImpl::SendReclaimCompositorResources(
1966 int32 route_id,
1967 uint32 output_surface_id,
1968 int renderer_host_id,
1969 const cc::CompositorFrameAck& ack) {
1970 RenderProcessHost* host = RenderProcessHost::FromID(renderer_host_id);
1971 if (!host)
1972 return;
1973 host->Send(
1974 new ViewMsg_ReclaimCompositorResources(route_id, output_surface_id, ack));
1977 void RenderWidgetHostImpl::DelayedAutoResized() {
1978 gfx::Size new_size = new_auto_size_;
1979 // Clear the new_auto_size_ since the empty value is used as a flag to
1980 // indicate that no callback is in progress (i.e. without this line
1981 // DelayedAutoResized will not get called again).
1982 new_auto_size_.SetSize(0, 0);
1983 if (!auto_resize_enabled_)
1984 return;
1986 OnRenderAutoResized(new_size);
1989 void RenderWidgetHostImpl::DetachDelegate() {
1990 delegate_ = NULL;
1993 void RenderWidgetHostImpl::FrameSwapped(const ui::LatencyInfo& latency_info) {
1994 ui::LatencyInfo::LatencyComponent window_snapshot_component;
1995 if (latency_info.FindLatency(ui::WINDOW_SNAPSHOT_FRAME_NUMBER_COMPONENT,
1996 GetLatencyComponentId(),
1997 &window_snapshot_component)) {
1998 int sequence_number = static_cast<int>(
1999 window_snapshot_component.sequence_number);
2000 #if defined(OS_MACOSX)
2001 // On Mac, when using CoreAnmation, there is a delay between when content
2002 // is drawn to the screen, and when the snapshot will actually pick up
2003 // that content. Insert a manual delay of 1/6th of a second (to simulate
2004 // 10 frames at 60 fps) before actually taking the snapshot.
2005 base::MessageLoop::current()->PostDelayedTask(
2006 FROM_HERE,
2007 base::Bind(&RenderWidgetHostImpl::WindowSnapshotReachedScreen,
2008 weak_factory_.GetWeakPtr(),
2009 sequence_number),
2010 base::TimeDelta::FromSecondsD(1. / 6));
2011 #else
2012 WindowSnapshotReachedScreen(sequence_number);
2013 #endif
2016 latency_tracker_.OnFrameSwapped(latency_info);
2019 void RenderWidgetHostImpl::DidReceiveRendererFrame() {
2020 view_->DidReceiveRendererFrame();
2023 void RenderWidgetHostImpl::WindowSnapshotReachedScreen(int snapshot_id) {
2024 DCHECK(base::MessageLoopForUI::IsCurrent());
2026 gfx::Rect view_bounds = GetView()->GetViewBounds();
2027 gfx::Rect snapshot_bounds(view_bounds.size());
2029 std::vector<unsigned char> png;
2030 if (ui::GrabViewSnapshot(
2031 GetView()->GetNativeView(), &png, snapshot_bounds)) {
2032 OnSnapshotDataReceived(snapshot_id, &png.front(), png.size());
2033 return;
2036 ui::GrabViewSnapshotAsync(
2037 GetView()->GetNativeView(),
2038 snapshot_bounds,
2039 base::ThreadTaskRunnerHandle::Get(),
2040 base::Bind(&RenderWidgetHostImpl::OnSnapshotDataReceivedAsync,
2041 weak_factory_.GetWeakPtr(),
2042 snapshot_id));
2045 void RenderWidgetHostImpl::OnSnapshotDataReceived(int snapshot_id,
2046 const unsigned char* data,
2047 size_t size) {
2048 // Any pending snapshots with a lower ID than the one received are considered
2049 // to be implicitly complete, and returned the same snapshot data.
2050 PendingSnapshotMap::iterator it = pending_browser_snapshots_.begin();
2051 while(it != pending_browser_snapshots_.end()) {
2052 if (it->first <= snapshot_id) {
2053 it->second.Run(data, size);
2054 pending_browser_snapshots_.erase(it++);
2055 } else {
2056 ++it;
2061 void RenderWidgetHostImpl::OnSnapshotDataReceivedAsync(
2062 int snapshot_id,
2063 scoped_refptr<base::RefCountedBytes> png_data) {
2064 if (png_data.get())
2065 OnSnapshotDataReceived(snapshot_id, png_data->front(), png_data->size());
2066 else
2067 OnSnapshotDataReceived(snapshot_id, NULL, 0);
2070 // static
2071 void RenderWidgetHostImpl::CompositorFrameDrawn(
2072 const std::vector<ui::LatencyInfo>& latency_info) {
2073 for (size_t i = 0; i < latency_info.size(); i++) {
2074 std::set<RenderWidgetHostImpl*> rwhi_set;
2075 for (ui::LatencyInfo::LatencyMap::const_iterator b =
2076 latency_info[i].latency_components.begin();
2077 b != latency_info[i].latency_components.end();
2078 ++b) {
2079 if (b->first.first == ui::INPUT_EVENT_LATENCY_BEGIN_RWH_COMPONENT ||
2080 b->first.first == ui::WINDOW_SNAPSHOT_FRAME_NUMBER_COMPONENT ||
2081 b->first.first == ui::TAB_SHOW_COMPONENT) {
2082 // Matches with GetLatencyComponentId
2083 int routing_id = b->first.second & 0xffffffff;
2084 int process_id = (b->first.second >> 32) & 0xffffffff;
2085 RenderWidgetHost* rwh =
2086 RenderWidgetHost::FromID(process_id, routing_id);
2087 if (!rwh) {
2088 continue;
2090 RenderWidgetHostImpl* rwhi = RenderWidgetHostImpl::From(rwh);
2091 if (rwhi_set.insert(rwhi).second)
2092 rwhi->FrameSwapped(latency_info[i]);
2098 BrowserAccessibilityManager*
2099 RenderWidgetHostImpl::GetRootBrowserAccessibilityManager() {
2100 return delegate_ ? delegate_->GetRootBrowserAccessibilityManager() : NULL;
2103 BrowserAccessibilityManager*
2104 RenderWidgetHostImpl::GetOrCreateRootBrowserAccessibilityManager() {
2105 return delegate_ ?
2106 delegate_->GetOrCreateRootBrowserAccessibilityManager() : NULL;
2109 base::TimeDelta RenderWidgetHostImpl::GetEstimatedBrowserCompositeTime() const {
2110 return latency_tracker_.GetEstimatedBrowserCompositeTime();
2113 #if defined(OS_WIN)
2114 gfx::NativeViewAccessible
2115 RenderWidgetHostImpl::GetParentNativeViewAccessible() {
2116 return delegate_ ? delegate_->GetParentNativeViewAccessible() : NULL;
2118 #endif
2120 } // namespace content