cygprofile: increase timeouts to allow showing web contents
[chromium-blink-merge.git] / content / browser / renderer_host / render_widget_host_impl.cc
blob53d0a1517baa0fddce256d97954d54310f7aa5d3
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 // <process id, routing id>
98 using RenderWidgetHostID = std::pair<int32_t, int32_t>;
99 using RoutingIDWidgetMap =
100 base::hash_map<RenderWidgetHostID, RenderWidgetHostImpl*>;
101 base::LazyInstance<RoutingIDWidgetMap> g_routing_id_widget_map =
102 LAZY_INSTANCE_INITIALIZER;
104 // Implements the RenderWidgetHostIterator interface. It keeps a list of
105 // RenderWidgetHosts, and makes sure it returns a live RenderWidgetHost at each
106 // iteration (or NULL if there isn't any left).
107 class RenderWidgetHostIteratorImpl : public RenderWidgetHostIterator {
108 public:
109 RenderWidgetHostIteratorImpl()
110 : current_index_(0) {
113 ~RenderWidgetHostIteratorImpl() override {}
115 void Add(RenderWidgetHost* host) {
116 hosts_.push_back(RenderWidgetHostID(host->GetProcess()->GetID(),
117 host->GetRoutingID()));
120 // RenderWidgetHostIterator:
121 RenderWidgetHost* GetNextHost() override {
122 RenderWidgetHost* host = NULL;
123 while (current_index_ < hosts_.size() && !host) {
124 RenderWidgetHostID id = hosts_[current_index_];
125 host = RenderWidgetHost::FromID(id.first, id.second);
126 ++current_index_;
128 return host;
131 private:
132 std::vector<RenderWidgetHostID> hosts_;
133 size_t current_index_;
135 DISALLOW_COPY_AND_ASSIGN(RenderWidgetHostIteratorImpl);
138 } // namespace
140 ///////////////////////////////////////////////////////////////////////////////
141 // RenderWidgetHostImpl
143 RenderWidgetHostImpl::RenderWidgetHostImpl(RenderWidgetHostDelegate* delegate,
144 RenderProcessHost* process,
145 int32_t routing_id,
146 int32_t surface_id,
147 bool hidden)
148 : view_(NULL),
149 hung_renderer_delay_(
150 base::TimeDelta::FromMilliseconds(kHungRendererDelayMs)),
151 renderer_initialized_(false),
152 delegate_(delegate),
153 process_(process),
154 routing_id_(routing_id),
155 surface_id_(surface_id),
156 is_loading_(false),
157 is_hidden_(hidden),
158 repaint_ack_pending_(false),
159 resize_ack_pending_(false),
160 color_profile_out_of_date_(false),
161 auto_resize_enabled_(false),
162 waiting_for_screen_rects_ack_(false),
163 needs_repainting_on_restore_(false),
164 is_unresponsive_(false),
165 in_flight_event_count_(0),
166 in_get_backing_store_(false),
167 ignore_input_events_(false),
168 text_direction_updated_(false),
169 text_direction_(blink::WebTextDirectionLeftToRight),
170 text_direction_canceled_(false),
171 suppress_next_char_events_(false),
172 pending_mouse_lock_request_(false),
173 allow_privileged_mouse_lock_(false),
174 has_touch_handler_(false),
175 next_browser_snapshot_id_(1),
176 owned_by_render_frame_host_(false),
177 is_focused_(false),
178 weak_factory_(this) {
179 CHECK(delegate_);
180 CHECK_NE(MSG_ROUTING_NONE, routing_id_);
181 DCHECK_EQ(surface_id_, GpuSurfaceTracker::Get()->LookupSurfaceForRenderer(
182 process_->GetID(), routing_id_));
184 std::pair<RoutingIDWidgetMap::iterator, bool> result =
185 g_routing_id_widget_map.Get().insert(std::make_pair(
186 RenderWidgetHostID(process->GetID(), routing_id_), this));
187 CHECK(result.second) << "Inserting a duplicate item!";
188 process_->AddRoute(routing_id_, this);
190 // If we're initially visible, tell the process host that we're alive.
191 // Otherwise we'll notify the process host when we are first shown.
192 if (!hidden)
193 process_->WidgetRestored();
195 latency_tracker_.Initialize(routing_id_, GetProcess()->GetID());
197 input_router_.reset(new InputRouterImpl(
198 process_, this, this, routing_id_, GetInputRouterConfigForPlatform()));
200 touch_emulator_.reset();
202 RenderViewHostImpl* rvh = static_cast<RenderViewHostImpl*>(
203 IsRenderView() ? RenderViewHost::From(this) : NULL);
204 if (BrowserPluginGuest::IsGuest(rvh) ||
205 !base::CommandLine::ForCurrentProcess()->HasSwitch(
206 switches::kDisableHangMonitor)) {
207 hang_monitor_timeout_.reset(new TimeoutMonitor(
208 base::Bind(&RenderWidgetHostImpl::RendererIsUnresponsive,
209 weak_factory_.GetWeakPtr())));
213 RenderWidgetHostImpl::~RenderWidgetHostImpl() {
214 if (view_weak_)
215 view_weak_->RenderWidgetHostGone();
216 SetView(NULL);
218 GpuSurfaceTracker::Get()->RemoveSurface(surface_id_);
219 surface_id_ = 0;
221 process_->RemoveRoute(routing_id_);
222 g_routing_id_widget_map.Get().erase(
223 RenderWidgetHostID(process_->GetID(), routing_id_));
225 if (delegate_)
226 delegate_->RenderWidgetDeleted(this);
229 // static
230 RenderWidgetHost* RenderWidgetHost::FromID(
231 int32_t process_id,
232 int32_t routing_id) {
233 return RenderWidgetHostImpl::FromID(process_id, routing_id);
236 // static
237 RenderWidgetHostImpl* RenderWidgetHostImpl::FromID(
238 int32_t process_id,
239 int32_t routing_id) {
240 DCHECK_CURRENTLY_ON(BrowserThread::UI);
241 RoutingIDWidgetMap* widgets = g_routing_id_widget_map.Pointer();
242 RoutingIDWidgetMap::iterator it = widgets->find(
243 RenderWidgetHostID(process_id, routing_id));
244 return it == widgets->end() ? NULL : it->second;
247 // static
248 scoped_ptr<RenderWidgetHostIterator> RenderWidgetHost::GetRenderWidgetHosts() {
249 RenderWidgetHostIteratorImpl* hosts = new RenderWidgetHostIteratorImpl();
250 RoutingIDWidgetMap* widgets = g_routing_id_widget_map.Pointer();
251 for (RoutingIDWidgetMap::const_iterator it = widgets->begin();
252 it != widgets->end();
253 ++it) {
254 RenderWidgetHost* widget = it->second;
256 if (!widget->IsRenderView()) {
257 hosts->Add(widget);
258 continue;
261 // Add only active RenderViewHosts.
262 RenderViewHost* rvh = RenderViewHost::From(widget);
263 if (static_cast<RenderViewHostImpl*>(rvh)->is_active())
264 hosts->Add(widget);
267 return scoped_ptr<RenderWidgetHostIterator>(hosts);
270 // static
271 scoped_ptr<RenderWidgetHostIterator>
272 RenderWidgetHostImpl::GetAllRenderWidgetHosts() {
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 hosts->Add(it->second);
281 return scoped_ptr<RenderWidgetHostIterator>(hosts);
284 // static
285 RenderWidgetHostImpl* RenderWidgetHostImpl::From(RenderWidgetHost* rwh) {
286 return rwh->AsRenderWidgetHostImpl();
289 void RenderWidgetHostImpl::SetView(RenderWidgetHostViewBase* view) {
290 if (view)
291 view_weak_ = view->GetWeakPtr();
292 else
293 view_weak_.reset();
294 view_ = view;
296 // If the renderer has not yet been initialized, then the surface ID
297 // namespace will be sent during initialization.
298 if (view_ && renderer_initialized_) {
299 Send(new ViewMsg_SetSurfaceIdNamespace(routing_id_,
300 view_->GetSurfaceIdNamespace()));
303 GpuSurfaceTracker::Get()->SetSurfaceHandle(
304 surface_id_, GetCompositingSurface());
306 synthetic_gesture_controller_.reset();
309 RenderProcessHost* RenderWidgetHostImpl::GetProcess() const {
310 return process_;
313 int RenderWidgetHostImpl::GetRoutingID() const {
314 return routing_id_;
317 RenderWidgetHostView* RenderWidgetHostImpl::GetView() const {
318 return view_;
321 RenderWidgetHostImpl* RenderWidgetHostImpl::AsRenderWidgetHostImpl() {
322 return this;
325 gfx::NativeViewId RenderWidgetHostImpl::GetNativeViewId() const {
326 if (view_)
327 return view_->GetNativeViewId();
328 return 0;
331 gfx::GLSurfaceHandle RenderWidgetHostImpl::GetCompositingSurface() {
332 if (view_)
333 return view_->GetCompositingSurface();
334 return gfx::GLSurfaceHandle();
337 void RenderWidgetHostImpl::ResetSizeAndRepaintPendingFlags() {
338 resize_ack_pending_ = false;
339 if (repaint_ack_pending_) {
340 TRACE_EVENT_ASYNC_END0(
341 "renderer_host", "RenderWidgetHostImpl::repaint_ack_pending_", this);
343 repaint_ack_pending_ = false;
344 if (old_resize_params_)
345 old_resize_params_->new_size = gfx::Size();
348 void RenderWidgetHostImpl::SendScreenRects() {
349 if (!renderer_initialized_ || waiting_for_screen_rects_ack_)
350 return;
352 if (is_hidden_) {
353 // On GTK, this comes in for backgrounded tabs. Ignore, to match what
354 // happens on Win & Mac, and when the view is shown it'll call this again.
355 return;
358 if (!view_)
359 return;
361 last_view_screen_rect_ = view_->GetViewBounds();
362 last_window_screen_rect_ = view_->GetBoundsInRootWindow();
363 Send(new ViewMsg_UpdateScreenRects(
364 GetRoutingID(), last_view_screen_rect_, last_window_screen_rect_));
365 if (delegate_)
366 delegate_->DidSendScreenRects(this);
367 waiting_for_screen_rects_ack_ = true;
370 void RenderWidgetHostImpl::SuppressNextCharEvents() {
371 suppress_next_char_events_ = true;
374 void RenderWidgetHostImpl::FlushInput() {
375 input_router_->RequestNotificationWhenFlushed();
376 if (synthetic_gesture_controller_)
377 synthetic_gesture_controller_->Flush(base::TimeTicks::Now());
380 void RenderWidgetHostImpl::SetNeedsFlush() {
381 if (view_)
382 view_->OnSetNeedsFlushInput();
385 void RenderWidgetHostImpl::Init() {
386 DCHECK(process_->HasConnection());
388 renderer_initialized_ = true;
390 GpuSurfaceTracker::Get()->SetSurfaceHandle(
391 surface_id_, GetCompositingSurface());
393 // Send the ack along with the information on placement.
394 Send(new ViewMsg_CreatingNew_ACK(routing_id_));
395 GetProcess()->ResumeRequestsForView(routing_id_);
397 // If the RWHV has not yet been set, the surface ID namespace will get
398 // passed down by the call to SetView().
399 if (view_) {
400 Send(new ViewMsg_SetSurfaceIdNamespace(routing_id_,
401 view_->GetSurfaceIdNamespace()));
404 WasResized();
407 void RenderWidgetHostImpl::InitForFrame() {
408 DCHECK(process_->HasConnection());
409 renderer_initialized_ = true;
412 void RenderWidgetHostImpl::Shutdown() {
413 RejectMouseLockOrUnlockIfNecessary();
415 if (process_->HasConnection()) {
416 // Tell the renderer object to close.
417 bool rv = Send(new ViewMsg_Close(routing_id_));
418 DCHECK(rv);
421 Destroy();
424 bool RenderWidgetHostImpl::IsLoading() const {
425 return is_loading_;
428 bool RenderWidgetHostImpl::IsRenderView() const {
429 return false;
432 bool RenderWidgetHostImpl::OnMessageReceived(const IPC::Message &msg) {
433 bool handled = true;
434 IPC_BEGIN_MESSAGE_MAP(RenderWidgetHostImpl, msg)
435 IPC_MESSAGE_HANDLER(FrameHostMsg_RenderProcessGone, OnRenderProcessGone)
436 IPC_MESSAGE_HANDLER(InputHostMsg_QueueSyntheticGesture,
437 OnQueueSyntheticGesture)
438 IPC_MESSAGE_HANDLER(InputHostMsg_ImeCancelComposition,
439 OnImeCancelComposition)
440 IPC_MESSAGE_HANDLER(ViewHostMsg_RenderViewReady, OnRenderViewReady)
441 IPC_MESSAGE_HANDLER(ViewHostMsg_Close, OnClose)
442 IPC_MESSAGE_HANDLER(ViewHostMsg_UpdateScreenRects_ACK,
443 OnUpdateScreenRectsAck)
444 IPC_MESSAGE_HANDLER(ViewHostMsg_RequestMove, OnRequestMove)
445 IPC_MESSAGE_HANDLER(ViewHostMsg_SetTooltipText, OnSetTooltipText)
446 IPC_MESSAGE_HANDLER_GENERIC(ViewHostMsg_SwapCompositorFrame,
447 OnSwapCompositorFrame(msg))
448 IPC_MESSAGE_HANDLER(ViewHostMsg_UpdateRect, OnUpdateRect)
449 IPC_MESSAGE_HANDLER(ViewHostMsg_Focus, OnFocus)
450 IPC_MESSAGE_HANDLER(ViewHostMsg_Blur, OnBlur)
451 IPC_MESSAGE_HANDLER(ViewHostMsg_SetCursor, OnSetCursor)
452 IPC_MESSAGE_HANDLER(ViewHostMsg_TextInputStateChanged,
453 OnTextInputStateChanged)
454 IPC_MESSAGE_HANDLER(ViewHostMsg_LockMouse, OnLockMouse)
455 IPC_MESSAGE_HANDLER(ViewHostMsg_UnlockMouse, OnUnlockMouse)
456 IPC_MESSAGE_HANDLER(ViewHostMsg_ShowDisambiguationPopup,
457 OnShowDisambiguationPopup)
458 IPC_MESSAGE_HANDLER(ViewHostMsg_SelectionChanged, OnSelectionChanged)
459 IPC_MESSAGE_HANDLER(ViewHostMsg_SelectionBoundsChanged,
460 OnSelectionBoundsChanged)
461 #if defined(OS_WIN)
462 IPC_MESSAGE_HANDLER(ViewHostMsg_WindowlessPluginDummyWindowCreated,
463 OnWindowlessPluginDummyWindowCreated)
464 IPC_MESSAGE_HANDLER(ViewHostMsg_WindowlessPluginDummyWindowDestroyed,
465 OnWindowlessPluginDummyWindowDestroyed)
466 #endif
467 IPC_MESSAGE_HANDLER(InputHostMsg_ImeCompositionRangeChanged,
468 OnImeCompositionRangeChanged)
469 IPC_MESSAGE_UNHANDLED(handled = false)
470 IPC_END_MESSAGE_MAP()
472 if (!handled && input_router_ && input_router_->OnMessageReceived(msg))
473 return true;
475 if (!handled && view_ && view_->OnMessageReceived(msg))
476 return true;
478 return handled;
481 bool RenderWidgetHostImpl::Send(IPC::Message* msg) {
482 if (IPC_MESSAGE_ID_CLASS(msg->type()) == InputMsgStart)
483 return input_router_->SendInput(make_scoped_ptr(msg));
485 return process_->Send(msg);
488 void RenderWidgetHostImpl::SetIsLoading(bool is_loading) {
489 is_loading_ = is_loading;
490 if (!view_)
491 return;
492 view_->SetIsLoading(is_loading);
495 void RenderWidgetHostImpl::WasHidden() {
496 if (is_hidden_)
497 return;
499 TRACE_EVENT0("renderer_host", "RenderWidgetHostImpl::WasHidden");
500 is_hidden_ = true;
502 // Don't bother reporting hung state when we aren't active.
503 StopHangMonitorTimeout();
505 // If we have a renderer, then inform it that we are being hidden so it can
506 // reduce its resource utilization.
507 Send(new ViewMsg_WasHidden(routing_id_));
509 // Tell the RenderProcessHost we were hidden.
510 process_->WidgetHidden();
512 bool is_visible = false;
513 NotificationService::current()->Notify(
514 NOTIFICATION_RENDER_WIDGET_VISIBILITY_CHANGED,
515 Source<RenderWidgetHost>(this),
516 Details<bool>(&is_visible));
519 void RenderWidgetHostImpl::WasShown(const ui::LatencyInfo& latency_info) {
520 if (!is_hidden_)
521 return;
523 TRACE_EVENT0("renderer_host", "RenderWidgetHostImpl::WasShown");
524 is_hidden_ = false;
526 SendScreenRects();
528 // When hidden, timeout monitoring for input events is disabled. Restore it
529 // now to ensure consistent hang detection.
530 if (in_flight_event_count_)
531 RestartHangMonitorTimeout();
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));
538 process_->WidgetRestored();
540 bool is_visible = true;
541 NotificationService::current()->Notify(
542 NOTIFICATION_RENDER_WIDGET_VISIBILITY_CHANGED,
543 Source<RenderWidgetHost>(this),
544 Details<bool>(&is_visible));
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.
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();
564 bool RenderWidgetHostImpl::GetResizeParams(
565 ViewMsg_Resize_Params* resize_params) {
566 *resize_params = ViewMsg_Resize_Params();
568 GetWebScreenInfo(&resize_params->screen_info);
569 resize_params->resizer_rect = GetRootWindowResizerRect();
571 if (view_) {
572 resize_params->new_size = view_->GetRequestedRendererSize();
573 resize_params->physical_backing_size = view_->GetPhysicalBackingSize();
574 resize_params->top_controls_height = view_->GetTopControlsHeight();
575 resize_params->top_controls_shrink_blink_size =
576 view_->DoTopControlsShrinkBlinkSize();
577 resize_params->visible_viewport_size = view_->GetVisibleViewportSize();
578 resize_params->is_fullscreen_granted = IsFullscreenGranted();
579 resize_params->display_mode = GetDisplayMode();
582 const bool size_changed =
583 !old_resize_params_ ||
584 old_resize_params_->new_size != resize_params->new_size ||
585 (old_resize_params_->physical_backing_size.IsEmpty() &&
586 !resize_params->physical_backing_size.IsEmpty());
587 bool dirty = size_changed ||
588 old_resize_params_->screen_info != resize_params->screen_info ||
589 old_resize_params_->physical_backing_size !=
590 resize_params->physical_backing_size ||
591 old_resize_params_->is_fullscreen_granted !=
592 resize_params->is_fullscreen_granted ||
593 old_resize_params_->display_mode != resize_params->display_mode ||
594 old_resize_params_->top_controls_height !=
595 resize_params->top_controls_height ||
596 old_resize_params_->top_controls_shrink_blink_size !=
597 resize_params->top_controls_shrink_blink_size ||
598 old_resize_params_->visible_viewport_size !=
599 resize_params->visible_viewport_size;
601 // We don't expect to receive an ACK when the requested size or the physical
602 // backing size is empty, or when the main viewport size didn't change.
603 resize_params->needs_resize_ack =
604 g_check_for_pending_resize_ack && !resize_params->new_size.IsEmpty() &&
605 !resize_params->physical_backing_size.IsEmpty() && size_changed;
607 return dirty;
610 void RenderWidgetHostImpl::SetInitialRenderSizeParams(
611 const ViewMsg_Resize_Params& resize_params) {
612 resize_ack_pending_ = resize_params.needs_resize_ack;
614 old_resize_params_ =
615 make_scoped_ptr(new ViewMsg_Resize_Params(resize_params));
618 void RenderWidgetHostImpl::WasResized() {
619 // Skip if the |delegate_| has already been detached because
620 // it's web contents is being deleted.
621 if (resize_ack_pending_ || !process_->HasConnection() || !view_ ||
622 !renderer_initialized_ || auto_resize_enabled_ || !delegate_) {
623 if (resize_ack_pending_ && color_profile_out_of_date_)
624 DispatchColorProfile();
625 return;
628 scoped_ptr<ViewMsg_Resize_Params> params(new ViewMsg_Resize_Params);
629 if (color_profile_out_of_date_)
630 DispatchColorProfile();
631 if (!GetResizeParams(params.get()))
632 return;
634 bool width_changed =
635 !old_resize_params_ ||
636 old_resize_params_->new_size.width() != params->new_size.width();
637 if (Send(new ViewMsg_Resize(routing_id_, *params))) {
638 resize_ack_pending_ = params->needs_resize_ack;
639 old_resize_params_.swap(params);
642 if (delegate_)
643 delegate_->RenderWidgetWasResized(this, width_changed);
646 void RenderWidgetHostImpl::DispatchColorProfile() {
647 #if defined(OS_WIN) || defined(OS_MACOSX) || defined(OS_LINUX)
648 static bool image_profiles = base::CommandLine::ForCurrentProcess()->
649 HasSwitch(switches::kEnableImageColorProfiles);
650 if (!image_profiles)
651 return;
652 #if defined(OS_WIN)
653 // Windows will read disk to get the color profile data if needed, so
654 // dispatch the SendColorProfile() work off the UI thread.
655 BrowserThread::PostBlockingPoolTask(
656 FROM_HERE,
657 base::Bind(&RenderWidgetHostImpl::SendColorProfile,
658 weak_factory_.GetWeakPtr()));
659 #elif !defined(OS_CHROMEOS) && !defined(OS_IOS) && !defined(OS_ANDROID)
660 // Only support desktop Mac and Linux at this time.
661 SendColorProfile();
662 #endif
663 #endif
666 void RenderWidgetHostImpl::SendColorProfile() {
667 if (!view_ || !delegate_)
668 return;
669 DCHECK(!view_->GetRequestedRendererSize().IsEmpty());
670 #if defined(OS_WIN)
671 DCHECK(!BrowserThread::CurrentlyOn(BrowserThread::UI));
672 DCHECK(!BrowserThread::CurrentlyOn(BrowserThread::IO));
673 #endif
674 std::vector<char> color_profile;
675 if (!GetScreenColorProfile(&color_profile))
676 return;
677 if (!renderer_initialized_ || !process_->HasConnection())
678 return;
679 if (!Send(new ViewMsg_ColorProfile(routing_id_, color_profile)))
680 return;
681 color_profile_out_of_date_ = false;
684 void RenderWidgetHostImpl::ResizeRectChanged(const gfx::Rect& new_rect) {
685 Send(new ViewMsg_ChangeResizeRect(routing_id_, new_rect));
688 void RenderWidgetHostImpl::GotFocus() {
689 Focus();
690 if (delegate_)
691 delegate_->RenderWidgetGotFocus(this);
694 void RenderWidgetHostImpl::Focus() {
695 is_focused_ = true;
697 Send(new InputMsg_SetFocus(routing_id_, true));
700 void RenderWidgetHostImpl::Blur() {
701 is_focused_ = false;
703 // If there is a pending mouse lock request, we don't want to reject it at
704 // this point. The user can switch focus back to this view and approve the
705 // request later.
706 if (IsMouseLocked())
707 view_->UnlockMouse();
709 if (touch_emulator_)
710 touch_emulator_->CancelTouch();
712 Send(new InputMsg_SetFocus(routing_id_, false));
715 void RenderWidgetHostImpl::LostCapture() {
716 if (touch_emulator_)
717 touch_emulator_->CancelTouch();
719 Send(new InputMsg_MouseCaptureLost(routing_id_));
722 void RenderWidgetHostImpl::SetActive(bool active) {
723 Send(new ViewMsg_SetActive(routing_id_, active));
726 void RenderWidgetHostImpl::LostMouseLock() {
727 Send(new ViewMsg_MouseLockLost(routing_id_));
730 void RenderWidgetHostImpl::ViewDestroyed() {
731 RejectMouseLockOrUnlockIfNecessary();
733 // TODO(evanm): tracking this may no longer be necessary;
734 // eliminate this function if so.
735 SetView(NULL);
738 void RenderWidgetHostImpl::CopyFromBackingStore(
739 const gfx::Rect& src_subrect,
740 const gfx::Size& accelerated_dst_size,
741 ReadbackRequestCallback& callback,
742 const SkColorType preferred_color_type) {
743 if (view_) {
744 TRACE_EVENT0("browser",
745 "RenderWidgetHostImpl::CopyFromBackingStore::FromCompositingSurface");
746 gfx::Rect accelerated_copy_rect = src_subrect.IsEmpty() ?
747 gfx::Rect(view_->GetViewBounds().size()) : src_subrect;
748 view_->CopyFromCompositingSurface(accelerated_copy_rect,
749 accelerated_dst_size, callback,
750 preferred_color_type);
751 return;
754 callback.Run(SkBitmap(), content::READBACK_FAILED);
757 bool RenderWidgetHostImpl::CanCopyFromBackingStore() {
758 if (view_)
759 return view_->IsSurfaceAvailableForCopy();
760 return false;
763 #if defined(OS_ANDROID)
764 void RenderWidgetHostImpl::LockBackingStore() {
765 if (view_)
766 view_->LockCompositingSurface();
769 void RenderWidgetHostImpl::UnlockBackingStore() {
770 if (view_)
771 view_->UnlockCompositingSurface();
773 #endif
775 #if defined(OS_MACOSX)
776 void RenderWidgetHostImpl::PauseForPendingResizeOrRepaints() {
777 TRACE_EVENT0("browser",
778 "RenderWidgetHostImpl::PauseForPendingResizeOrRepaints");
780 if (!CanPauseForPendingResizeOrRepaints())
781 return;
783 WaitForSurface();
786 bool RenderWidgetHostImpl::CanPauseForPendingResizeOrRepaints() {
787 // Do not pause if the view is hidden.
788 if (is_hidden())
789 return false;
791 // Do not pause if there is not a paint or resize already coming.
792 if (!repaint_ack_pending_ && !resize_ack_pending_)
793 return false;
795 return true;
798 void RenderWidgetHostImpl::WaitForSurface() {
799 // How long to (synchronously) wait for the renderer to respond with a
800 // new frame when our current frame doesn't exist or is the wrong size.
801 // This timeout impacts the "choppiness" of our window resize.
802 const int kPaintMsgTimeoutMS = 50;
804 if (!view_)
805 return;
807 // The view_size will be current_size_ for auto-sized views and otherwise the
808 // size of the view_. (For auto-sized views, current_size_ is updated during
809 // UpdateRect messages.)
810 gfx::Size view_size = current_size_;
811 if (!auto_resize_enabled_) {
812 // Get the desired size from the current view bounds.
813 gfx::Rect view_rect = view_->GetViewBounds();
814 if (view_rect.IsEmpty())
815 return;
816 view_size = view_rect.size();
819 TRACE_EVENT2("renderer_host",
820 "RenderWidgetHostImpl::WaitForSurface",
821 "width",
822 base::IntToString(view_size.width()),
823 "height",
824 base::IntToString(view_size.height()));
826 // We should not be asked to paint while we are hidden. If we are hidden,
827 // then it means that our consumer failed to call WasShown.
828 DCHECK(!is_hidden_) << "WaitForSurface called while hidden!";
830 // We should never be called recursively; this can theoretically lead to
831 // infinite recursion and almost certainly leads to lower performance.
832 DCHECK(!in_get_backing_store_) << "WaitForSurface called recursively!";
833 base::AutoReset<bool> auto_reset_in_get_backing_store(
834 &in_get_backing_store_, true);
836 // We might have a surface that we can use already.
837 if (view_->HasAcceleratedSurface(view_size))
838 return;
840 // Request that the renderer produce a frame of the right size, if it
841 // hasn't been requested already.
842 if (!repaint_ack_pending_ && !resize_ack_pending_) {
843 repaint_start_time_ = TimeTicks::Now();
844 repaint_ack_pending_ = true;
845 TRACE_EVENT_ASYNC_BEGIN0(
846 "renderer_host", "RenderWidgetHostImpl::repaint_ack_pending_", this);
847 Send(new ViewMsg_Repaint(routing_id_, view_size));
850 // Pump a nested message loop until we time out or get a frame of the right
851 // size.
852 TimeTicks start_time = TimeTicks::Now();
853 TimeDelta time_left = TimeDelta::FromMilliseconds(kPaintMsgTimeoutMS);
854 TimeTicks timeout_time = start_time + time_left;
855 while (1) {
856 TRACE_EVENT0("renderer_host", "WaitForSurface::WaitForSingleTaskToRun");
857 if (RenderWidgetResizeHelper::Get()->WaitForSingleTaskToRun(time_left)) {
858 // For auto-resized views, current_size_ determines the view_size and it
859 // may have changed during the handling of an UpdateRect message.
860 if (auto_resize_enabled_)
861 view_size = current_size_;
862 if (view_->HasAcceleratedSurface(view_size))
863 break;
865 time_left = timeout_time - TimeTicks::Now();
866 if (time_left <= TimeDelta::FromSeconds(0)) {
867 TRACE_EVENT0("renderer_host", "WaitForSurface::Timeout");
868 break;
872 UMA_HISTOGRAM_CUSTOM_TIMES("OSX.RendererHost.SurfaceWaitTime",
873 TimeTicks::Now() - start_time,
874 TimeDelta::FromMilliseconds(1),
875 TimeDelta::FromMilliseconds(200), 50);
877 #endif
879 bool RenderWidgetHostImpl::ScheduleComposite() {
880 if (is_hidden_ || current_size_.IsEmpty() || repaint_ack_pending_ ||
881 resize_ack_pending_) {
882 return false;
885 // Send out a request to the renderer to paint the view if required.
886 repaint_start_time_ = TimeTicks::Now();
887 repaint_ack_pending_ = true;
888 TRACE_EVENT_ASYNC_BEGIN0(
889 "renderer_host", "RenderWidgetHostImpl::repaint_ack_pending_", this);
890 Send(new ViewMsg_Repaint(routing_id_, current_size_));
891 return true;
894 void RenderWidgetHostImpl::StartHangMonitorTimeout(base::TimeDelta delay) {
895 if (hang_monitor_timeout_)
896 hang_monitor_timeout_->Start(delay);
899 void RenderWidgetHostImpl::RestartHangMonitorTimeout() {
900 if (hang_monitor_timeout_)
901 hang_monitor_timeout_->Restart(hung_renderer_delay_);
904 void RenderWidgetHostImpl::StopHangMonitorTimeout() {
905 if (hang_monitor_timeout_)
906 hang_monitor_timeout_->Stop();
907 RendererIsResponsive();
910 void RenderWidgetHostImpl::ForwardMouseEvent(const WebMouseEvent& mouse_event) {
911 ForwardMouseEventWithLatencyInfo(mouse_event, ui::LatencyInfo());
914 void RenderWidgetHostImpl::ForwardMouseEventWithLatencyInfo(
915 const blink::WebMouseEvent& mouse_event,
916 const ui::LatencyInfo& ui_latency) {
917 TRACE_EVENT2("input", "RenderWidgetHostImpl::ForwardMouseEvent",
918 "x", mouse_event.x, "y", mouse_event.y);
920 for (size_t i = 0; i < mouse_event_callbacks_.size(); ++i) {
921 if (mouse_event_callbacks_[i].Run(mouse_event))
922 return;
925 if (IgnoreInputEvents())
926 return;
928 if (touch_emulator_ && touch_emulator_->HandleMouseEvent(mouse_event))
929 return;
931 MouseEventWithLatencyInfo mouse_with_latency(mouse_event, ui_latency);
932 latency_tracker_.OnInputEvent(mouse_event, &mouse_with_latency.latency);
933 input_router_->SendMouseEvent(mouse_with_latency);
935 // Pass mouse state to gpu service if the subscribe uniform
936 // extension is enabled.
937 if (process_->SubscribeUniformEnabled()) {
938 gpu::ValueState state;
939 state.int_value[0] = mouse_event.x;
940 state.int_value[1] = mouse_event.y;
941 // TODO(orglofch) Separate the mapping of pending value states to the
942 // Gpu Service to be per RWH not per process
943 process_->SendUpdateValueState(GL_MOUSE_POSITION_CHROMIUM, state);
947 void RenderWidgetHostImpl::ForwardWheelEvent(
948 const WebMouseWheelEvent& wheel_event) {
949 ForwardWheelEventWithLatencyInfo(wheel_event, ui::LatencyInfo());
952 void RenderWidgetHostImpl::ForwardWheelEventWithLatencyInfo(
953 const blink::WebMouseWheelEvent& wheel_event,
954 const ui::LatencyInfo& ui_latency) {
955 TRACE_EVENT2("input", "RenderWidgetHostImpl::ForwardWheelEvent",
956 "dx", wheel_event.deltaX, "dy", wheel_event.deltaY);
958 if (IgnoreInputEvents())
959 return;
961 if (touch_emulator_ && touch_emulator_->HandleMouseWheelEvent(wheel_event))
962 return;
964 MouseWheelEventWithLatencyInfo wheel_with_latency(wheel_event, ui_latency);
965 latency_tracker_.OnInputEvent(wheel_event, &wheel_with_latency.latency);
966 input_router_->SendWheelEvent(wheel_with_latency);
969 void RenderWidgetHostImpl::ForwardGestureEvent(
970 const blink::WebGestureEvent& gesture_event) {
971 ForwardGestureEventWithLatencyInfo(gesture_event, ui::LatencyInfo());
974 void RenderWidgetHostImpl::ForwardGestureEventWithLatencyInfo(
975 const blink::WebGestureEvent& gesture_event,
976 const ui::LatencyInfo& ui_latency) {
977 TRACE_EVENT0("input", "RenderWidgetHostImpl::ForwardGestureEvent");
978 // Early out if necessary, prior to performing latency logic.
979 if (IgnoreInputEvents())
980 return;
982 if (delegate_->PreHandleGestureEvent(gesture_event))
983 return;
985 GestureEventWithLatencyInfo gesture_with_latency(gesture_event, ui_latency);
986 latency_tracker_.OnInputEvent(gesture_event, &gesture_with_latency.latency);
987 input_router_->SendGestureEvent(gesture_with_latency);
990 void RenderWidgetHostImpl::ForwardEmulatedTouchEvent(
991 const blink::WebTouchEvent& touch_event) {
992 TRACE_EVENT0("input", "RenderWidgetHostImpl::ForwardEmulatedTouchEvent");
994 TouchEventWithLatencyInfo touch_with_latency(touch_event);
995 latency_tracker_.OnInputEvent(touch_event, &touch_with_latency.latency);
996 input_router_->SendTouchEvent(touch_with_latency);
999 void RenderWidgetHostImpl::ForwardTouchEventWithLatencyInfo(
1000 const blink::WebTouchEvent& touch_event,
1001 const ui::LatencyInfo& ui_latency) {
1002 TRACE_EVENT0("input", "RenderWidgetHostImpl::ForwardTouchEvent");
1004 // Always forward TouchEvents for touch stream consistency. They will be
1005 // ignored if appropriate in FilterInputEvent().
1007 TouchEventWithLatencyInfo touch_with_latency(touch_event, ui_latency);
1008 if (touch_emulator_ &&
1009 touch_emulator_->HandleTouchEvent(touch_with_latency.event)) {
1010 if (view_) {
1011 view_->ProcessAckedTouchEvent(
1012 touch_with_latency, INPUT_EVENT_ACK_STATE_CONSUMED);
1014 return;
1017 latency_tracker_.OnInputEvent(touch_event, &touch_with_latency.latency);
1018 input_router_->SendTouchEvent(touch_with_latency);
1021 void RenderWidgetHostImpl::ForwardKeyboardEvent(
1022 const NativeWebKeyboardEvent& key_event) {
1023 TRACE_EVENT0("input", "RenderWidgetHostImpl::ForwardKeyboardEvent");
1024 if (IgnoreInputEvents())
1025 return;
1027 if (!process_->HasConnection())
1028 return;
1030 // First, let keypress listeners take a shot at handling the event. If a
1031 // listener handles the event, it should not be propagated to the renderer.
1032 if (KeyPressListenersHandleEvent(key_event)) {
1033 // Some keypresses that are accepted by the listener might have follow up
1034 // char events, which should be ignored.
1035 if (key_event.type == WebKeyboardEvent::RawKeyDown)
1036 suppress_next_char_events_ = true;
1037 return;
1040 if (key_event.type == WebKeyboardEvent::Char &&
1041 (key_event.windowsKeyCode == ui::VKEY_RETURN ||
1042 key_event.windowsKeyCode == ui::VKEY_SPACE)) {
1043 OnUserGesture();
1046 // Double check the type to make sure caller hasn't sent us nonsense that
1047 // will mess up our key queue.
1048 if (!WebInputEvent::isKeyboardEventType(key_event.type))
1049 return;
1051 if (suppress_next_char_events_) {
1052 // If preceding RawKeyDown event was handled by the browser, then we need
1053 // suppress all Char events generated by it. Please note that, one
1054 // RawKeyDown event may generate multiple Char events, so we can't reset
1055 // |suppress_next_char_events_| until we get a KeyUp or a RawKeyDown.
1056 if (key_event.type == WebKeyboardEvent::Char)
1057 return;
1058 // We get a KeyUp or a RawKeyDown event.
1059 suppress_next_char_events_ = false;
1062 bool is_shortcut = false;
1064 // Only pre-handle the key event if it's not handled by the input method.
1065 if (delegate_ && !key_event.skip_in_browser) {
1066 // We need to set |suppress_next_char_events_| to true if
1067 // PreHandleKeyboardEvent() returns true, but |this| may already be
1068 // destroyed at that time. So set |suppress_next_char_events_| true here,
1069 // then revert it afterwards when necessary.
1070 if (key_event.type == WebKeyboardEvent::RawKeyDown)
1071 suppress_next_char_events_ = true;
1073 // Tab switching/closing accelerators aren't sent to the renderer to avoid
1074 // a hung/malicious renderer from interfering.
1075 if (delegate_->PreHandleKeyboardEvent(key_event, &is_shortcut))
1076 return;
1078 if (key_event.type == WebKeyboardEvent::RawKeyDown)
1079 suppress_next_char_events_ = false;
1082 if (touch_emulator_ && touch_emulator_->HandleKeyboardEvent(key_event))
1083 return;
1085 NativeWebKeyboardEventWithLatencyInfo key_event_with_latency(key_event);
1086 latency_tracker_.OnInputEvent(key_event, &key_event_with_latency.latency);
1087 input_router_->SendKeyboardEvent(key_event_with_latency, is_shortcut);
1090 void RenderWidgetHostImpl::QueueSyntheticGesture(
1091 scoped_ptr<SyntheticGesture> synthetic_gesture,
1092 const base::Callback<void(SyntheticGesture::Result)>& on_complete) {
1093 if (!synthetic_gesture_controller_ && view_) {
1094 synthetic_gesture_controller_.reset(
1095 new SyntheticGestureController(
1096 view_->CreateSyntheticGestureTarget().Pass()));
1098 if (synthetic_gesture_controller_) {
1099 synthetic_gesture_controller_->QueueSyntheticGesture(
1100 synthetic_gesture.Pass(), on_complete);
1104 void RenderWidgetHostImpl::SetCursor(const WebCursor& cursor) {
1105 if (!view_)
1106 return;
1107 view_->UpdateCursor(cursor);
1110 void RenderWidgetHostImpl::ShowContextMenuAtPoint(const gfx::Point& point) {
1111 Send(new ViewMsg_ShowContextMenu(
1112 GetRoutingID(), ui::MENU_SOURCE_MOUSE, point));
1115 void RenderWidgetHostImpl::SendCursorVisibilityState(bool is_visible) {
1116 Send(new InputMsg_CursorVisibilityChange(GetRoutingID(), is_visible));
1119 int64_t RenderWidgetHostImpl::GetLatencyComponentId() const {
1120 return latency_tracker_.latency_component_id();
1123 // static
1124 void RenderWidgetHostImpl::DisableResizeAckCheckForTesting() {
1125 g_check_for_pending_resize_ack = false;
1128 void RenderWidgetHostImpl::AddKeyPressEventCallback(
1129 const KeyPressEventCallback& callback) {
1130 key_press_event_callbacks_.push_back(callback);
1133 void RenderWidgetHostImpl::RemoveKeyPressEventCallback(
1134 const KeyPressEventCallback& callback) {
1135 for (size_t i = 0; i < key_press_event_callbacks_.size(); ++i) {
1136 if (key_press_event_callbacks_[i].Equals(callback)) {
1137 key_press_event_callbacks_.erase(
1138 key_press_event_callbacks_.begin() + i);
1139 return;
1144 void RenderWidgetHostImpl::AddMouseEventCallback(
1145 const MouseEventCallback& callback) {
1146 mouse_event_callbacks_.push_back(callback);
1149 void RenderWidgetHostImpl::RemoveMouseEventCallback(
1150 const MouseEventCallback& callback) {
1151 for (size_t i = 0; i < mouse_event_callbacks_.size(); ++i) {
1152 if (mouse_event_callbacks_[i].Equals(callback)) {
1153 mouse_event_callbacks_.erase(mouse_event_callbacks_.begin() + i);
1154 return;
1159 void RenderWidgetHostImpl::GetWebScreenInfo(blink::WebScreenInfo* result) {
1160 TRACE_EVENT0("renderer_host", "RenderWidgetHostImpl::GetWebScreenInfo");
1161 if (view_)
1162 view_->GetScreenInfo(result);
1163 else
1164 RenderWidgetHostViewBase::GetDefaultScreenInfo(result);
1165 // TODO(sievers): find a way to make this done another way so the method
1166 // can be const.
1167 latency_tracker_.set_device_scale_factor(result->deviceScaleFactor);
1170 bool RenderWidgetHostImpl::GetScreenColorProfile(
1171 std::vector<char>* color_profile) {
1172 DCHECK(color_profile->empty());
1173 if (view_)
1174 return view_->GetScreenColorProfile(color_profile);
1175 return false;
1178 void RenderWidgetHostImpl::NotifyScreenInfoChanged() {
1179 color_profile_out_of_date_ = true;
1181 if (delegate_)
1182 delegate_->ScreenInfoChanged();
1184 // The resize message (which may not happen immediately) will carry with it
1185 // the screen info as well as the new size (if the screen has changed scale
1186 // factor).
1187 WasResized();
1190 void RenderWidgetHostImpl::GetSnapshotFromBrowser(
1191 const GetSnapshotFromBrowserCallback& callback) {
1192 int id = next_browser_snapshot_id_++;
1193 pending_browser_snapshots_.insert(std::make_pair(id, callback));
1194 Send(new ViewMsg_ForceRedraw(GetRoutingID(), id));
1197 const NativeWebKeyboardEvent*
1198 RenderWidgetHostImpl::GetLastKeyboardEvent() const {
1199 return input_router_->GetLastKeyboardEvent();
1202 void RenderWidgetHostImpl::OnSelectionChanged(const base::string16& text,
1203 size_t offset,
1204 const gfx::Range& range) {
1205 if (view_)
1206 view_->SelectionChanged(text, offset, range);
1209 void RenderWidgetHostImpl::OnSelectionBoundsChanged(
1210 const ViewHostMsg_SelectionBounds_Params& params) {
1211 if (view_) {
1212 view_->SelectionBoundsChanged(params);
1216 void RenderWidgetHostImpl::UpdateVSyncParameters(base::TimeTicks timebase,
1217 base::TimeDelta interval) {
1218 Send(new ViewMsg_UpdateVSyncParameters(GetRoutingID(), timebase, interval));
1221 void RenderWidgetHostImpl::RendererExited(base::TerminationStatus status,
1222 int exit_code) {
1223 if (!renderer_initialized_)
1224 return;
1226 // Clearing this flag causes us to re-create the renderer when recovering
1227 // from a crashed renderer.
1228 renderer_initialized_ = false;
1230 waiting_for_screen_rects_ack_ = false;
1232 // Must reset these to ensure that keyboard events work with a new renderer.
1233 suppress_next_char_events_ = false;
1235 // Reset some fields in preparation for recovering from a crash.
1236 ResetSizeAndRepaintPendingFlags();
1237 current_size_.SetSize(0, 0);
1238 // After the renderer crashes, the view is destroyed and so the
1239 // RenderWidgetHost cannot track its visibility anymore. We assume such
1240 // RenderWidgetHost to be invisible for the sake of internal accounting - be
1241 // careful about changing this - see http://crbug.com/401859 and
1242 // http://crbug.com/522795.
1244 // We need to at least make sure that the RenderProcessHost is notified about
1245 // the |is_hidden_| change, so that the renderer will have correct visibility
1246 // set when respawned.
1247 if (!is_hidden_) {
1248 process_->WidgetHidden();
1249 is_hidden_ = true;
1252 // Reset this to ensure the hung renderer mechanism is working properly.
1253 in_flight_event_count_ = 0;
1254 StopHangMonitorTimeout();
1256 if (view_) {
1257 GpuSurfaceTracker::Get()->SetSurfaceHandle(surface_id_,
1258 gfx::GLSurfaceHandle());
1259 view_->RenderProcessGone(status, exit_code);
1260 view_ = nullptr; // The View should be deleted by RenderProcessGone.
1261 view_weak_.reset();
1264 // Reconstruct the input router to ensure that it has fresh state for a new
1265 // renderer. Otherwise it may be stuck waiting for the old renderer to ack an
1266 // event. (In particular, the above call to view_->RenderProcessGone will
1267 // destroy the aura window, which may dispatch a synthetic mouse move.)
1268 input_router_.reset(new InputRouterImpl(
1269 process_, this, this, routing_id_, GetInputRouterConfigForPlatform()));
1271 synthetic_gesture_controller_.reset();
1274 void RenderWidgetHostImpl::UpdateTextDirection(WebTextDirection direction) {
1275 text_direction_updated_ = true;
1276 text_direction_ = direction;
1279 void RenderWidgetHostImpl::CancelUpdateTextDirection() {
1280 if (text_direction_updated_)
1281 text_direction_canceled_ = true;
1284 void RenderWidgetHostImpl::NotifyTextDirection() {
1285 if (text_direction_updated_) {
1286 if (!text_direction_canceled_)
1287 Send(new ViewMsg_SetTextDirection(GetRoutingID(), text_direction_));
1288 text_direction_updated_ = false;
1289 text_direction_canceled_ = false;
1293 void RenderWidgetHostImpl::ImeSetComposition(
1294 const base::string16& text,
1295 const std::vector<blink::WebCompositionUnderline>& underlines,
1296 int selection_start,
1297 int selection_end) {
1298 Send(new InputMsg_ImeSetComposition(
1299 GetRoutingID(), text, underlines, selection_start, selection_end));
1302 void RenderWidgetHostImpl::ImeConfirmComposition(
1303 const base::string16& text,
1304 const gfx::Range& replacement_range,
1305 bool keep_selection) {
1306 Send(new InputMsg_ImeConfirmComposition(
1307 GetRoutingID(), text, replacement_range, keep_selection));
1310 void RenderWidgetHostImpl::ImeCancelComposition() {
1311 Send(new InputMsg_ImeSetComposition(GetRoutingID(), base::string16(),
1312 std::vector<blink::WebCompositionUnderline>(), 0, 0));
1315 gfx::Rect RenderWidgetHostImpl::GetRootWindowResizerRect() const {
1316 return gfx::Rect();
1319 void RenderWidgetHostImpl::RequestToLockMouse(bool user_gesture,
1320 bool last_unlocked_by_target) {
1321 // Directly reject to lock the mouse. Subclass can override this method to
1322 // decide whether to allow mouse lock or not.
1323 GotResponseToLockMouseRequest(false);
1326 void RenderWidgetHostImpl::RejectMouseLockOrUnlockIfNecessary() {
1327 DCHECK(!pending_mouse_lock_request_ || !IsMouseLocked());
1328 if (pending_mouse_lock_request_) {
1329 pending_mouse_lock_request_ = false;
1330 Send(new ViewMsg_LockMouse_ACK(routing_id_, false));
1331 } else if (IsMouseLocked()) {
1332 view_->UnlockMouse();
1336 bool RenderWidgetHostImpl::IsMouseLocked() const {
1337 return view_ ? view_->IsMouseLocked() : false;
1340 bool RenderWidgetHostImpl::IsFullscreenGranted() const {
1341 return false;
1344 blink::WebDisplayMode RenderWidgetHostImpl::GetDisplayMode() const {
1345 return blink::WebDisplayModeBrowser;
1348 void RenderWidgetHostImpl::SetAutoResize(bool enable,
1349 const gfx::Size& min_size,
1350 const gfx::Size& max_size) {
1351 auto_resize_enabled_ = enable;
1352 min_size_for_auto_resize_ = min_size;
1353 max_size_for_auto_resize_ = max_size;
1356 void RenderWidgetHostImpl::Destroy() {
1357 NotificationService::current()->Notify(
1358 NOTIFICATION_RENDER_WIDGET_HOST_DESTROYED,
1359 Source<RenderWidgetHost>(this),
1360 NotificationService::NoDetails());
1362 // Tell the view to die.
1363 // Note that in the process of the view shutting down, it can call a ton
1364 // of other messages on us. So if you do any other deinitialization here,
1365 // do it after this call to view_->Destroy().
1366 if (view_) {
1367 view_->Destroy();
1368 view_ = nullptr;
1371 delete this;
1374 void RenderWidgetHostImpl::RendererIsUnresponsive() {
1375 NotificationService::current()->Notify(
1376 NOTIFICATION_RENDER_WIDGET_HOST_HANG,
1377 Source<RenderWidgetHost>(this),
1378 NotificationService::NoDetails());
1379 is_unresponsive_ = true;
1380 NotifyRendererUnresponsive();
1383 void RenderWidgetHostImpl::RendererIsResponsive() {
1384 if (is_unresponsive_) {
1385 is_unresponsive_ = false;
1386 NotifyRendererResponsive();
1390 void RenderWidgetHostImpl::OnRenderViewReady() {
1391 SendScreenRects();
1392 WasResized();
1395 void RenderWidgetHostImpl::OnRenderProcessGone(int status, int exit_code) {
1396 // RenderFrameHost owns a RenderWidgetHost when it needs one, in which case
1397 // it handles destruction.
1398 if (!owned_by_render_frame_host_) {
1399 // TODO(evanm): This synchronously ends up calling "delete this".
1400 // Is that really what we want in response to this message? I'm matching
1401 // previous behavior of the code here.
1402 Destroy();
1403 } else {
1404 RendererExited(static_cast<base::TerminationStatus>(status), exit_code);
1408 void RenderWidgetHostImpl::OnClose() {
1409 Shutdown();
1412 void RenderWidgetHostImpl::OnSetTooltipText(
1413 const base::string16& tooltip_text,
1414 WebTextDirection text_direction_hint) {
1415 // First, add directionality marks around tooltip text if necessary.
1416 // A naive solution would be to simply always wrap the text. However, on
1417 // windows, Unicode directional embedding characters can't be displayed on
1418 // systems that lack RTL fonts and are instead displayed as empty squares.
1420 // To get around this we only wrap the string when we deem it necessary i.e.
1421 // when the locale direction is different than the tooltip direction hint.
1423 // Currently, we use element's directionality as the tooltip direction hint.
1424 // An alternate solution would be to set the overall directionality based on
1425 // trying to detect the directionality from the tooltip text rather than the
1426 // element direction. One could argue that would be a preferable solution
1427 // but we use the current approach to match Fx & IE's behavior.
1428 base::string16 wrapped_tooltip_text = tooltip_text;
1429 if (!tooltip_text.empty()) {
1430 if (text_direction_hint == blink::WebTextDirectionLeftToRight) {
1431 // Force the tooltip to have LTR directionality.
1432 wrapped_tooltip_text =
1433 base::i18n::GetDisplayStringInLTRDirectionality(wrapped_tooltip_text);
1434 } else if (text_direction_hint == blink::WebTextDirectionRightToLeft &&
1435 !base::i18n::IsRTL()) {
1436 // Force the tooltip to have RTL directionality.
1437 base::i18n::WrapStringWithRTLFormatting(&wrapped_tooltip_text);
1440 if (GetView())
1441 view_->SetTooltipText(wrapped_tooltip_text);
1444 void RenderWidgetHostImpl::OnUpdateScreenRectsAck() {
1445 waiting_for_screen_rects_ack_ = false;
1446 if (!view_)
1447 return;
1449 if (view_->GetViewBounds() == last_view_screen_rect_ &&
1450 view_->GetBoundsInRootWindow() == last_window_screen_rect_) {
1451 return;
1454 SendScreenRects();
1457 void RenderWidgetHostImpl::OnRequestMove(const gfx::Rect& pos) {
1458 if (view_) {
1459 view_->SetBounds(pos);
1460 Send(new ViewMsg_Move_ACK(routing_id_));
1464 bool RenderWidgetHostImpl::OnSwapCompositorFrame(
1465 const IPC::Message& message) {
1466 // This trace event is used in
1467 // chrome/browser/extensions/api/cast_streaming/performance_test.cc
1468 TRACE_EVENT0("test_fps,benchmark", "OnSwapCompositorFrame");
1469 ViewHostMsg_SwapCompositorFrame::Param param;
1470 if (!ViewHostMsg_SwapCompositorFrame::Read(&message, &param))
1471 return false;
1472 scoped_ptr<cc::CompositorFrame> frame(new cc::CompositorFrame);
1473 uint32_t output_surface_id = base::get<0>(param);
1474 base::get<1>(param).AssignTo(frame.get());
1475 std::vector<IPC::Message> messages_to_deliver_with_frame;
1476 messages_to_deliver_with_frame.swap(base::get<2>(param));
1478 if (!ui::LatencyInfo::Verify(frame->metadata.latency_info,
1479 "RenderWidgetHostImpl::OnSwapCompositorFrame"))
1480 return false;
1482 latency_tracker_.OnSwapCompositorFrame(&frame->metadata.latency_info);
1484 bool is_mobile_optimized = IsMobileOptimizedFrame(frame->metadata);
1485 input_router_->NotifySiteIsMobileOptimized(is_mobile_optimized);
1486 if (touch_emulator_)
1487 touch_emulator_->SetDoubleTapSupportForPageEnabled(!is_mobile_optimized);
1489 if (view_) {
1490 view_->OnSwapCompositorFrame(output_surface_id, frame.Pass());
1491 view_->DidReceiveRendererFrame();
1492 } else {
1493 cc::CompositorFrameAck ack;
1494 if (frame->gl_frame_data) {
1495 ack.gl_frame_data = frame->gl_frame_data.Pass();
1496 ack.gl_frame_data->sync_point = 0;
1497 } else if (frame->delegated_frame_data) {
1498 cc::TransferableResource::ReturnResources(
1499 frame->delegated_frame_data->resource_list,
1500 &ack.resources);
1502 SendSwapCompositorFrameAck(routing_id_, output_surface_id,
1503 process_->GetID(), ack);
1506 RenderProcessHost* rph = GetProcess();
1507 for (std::vector<IPC::Message>::const_iterator i =
1508 messages_to_deliver_with_frame.begin();
1509 i != messages_to_deliver_with_frame.end();
1510 ++i) {
1511 rph->OnMessageReceived(*i);
1512 if (i->dispatch_error())
1513 rph->OnBadMessageReceived(*i);
1515 messages_to_deliver_with_frame.clear();
1517 return true;
1520 void RenderWidgetHostImpl::OnUpdateRect(
1521 const ViewHostMsg_UpdateRect_Params& params) {
1522 TRACE_EVENT0("renderer_host", "RenderWidgetHostImpl::OnUpdateRect");
1523 TimeTicks paint_start = TimeTicks::Now();
1525 // Update our knowledge of the RenderWidget's size.
1526 current_size_ = params.view_size;
1528 bool is_resize_ack =
1529 ViewHostMsg_UpdateRect_Flags::is_resize_ack(params.flags);
1531 // resize_ack_pending_ needs to be cleared before we call DidPaintRect, since
1532 // that will end up reaching GetBackingStore.
1533 if (is_resize_ack) {
1534 DCHECK(!g_check_for_pending_resize_ack || resize_ack_pending_);
1535 resize_ack_pending_ = false;
1538 bool is_repaint_ack =
1539 ViewHostMsg_UpdateRect_Flags::is_repaint_ack(params.flags);
1540 if (is_repaint_ack) {
1541 DCHECK(repaint_ack_pending_);
1542 TRACE_EVENT_ASYNC_END0(
1543 "renderer_host", "RenderWidgetHostImpl::repaint_ack_pending_", this);
1544 repaint_ack_pending_ = false;
1545 TimeDelta delta = TimeTicks::Now() - repaint_start_time_;
1546 UMA_HISTOGRAM_TIMES("MPArch.RWH_RepaintDelta", delta);
1549 DCHECK(!params.view_size.IsEmpty());
1551 DidUpdateBackingStore(params, paint_start);
1553 if (auto_resize_enabled_) {
1554 bool post_callback = new_auto_size_.IsEmpty();
1555 new_auto_size_ = params.view_size;
1556 if (post_callback) {
1557 base::ThreadTaskRunnerHandle::Get()->PostTask(
1558 FROM_HERE, base::Bind(&RenderWidgetHostImpl::DelayedAutoResized,
1559 weak_factory_.GetWeakPtr()));
1563 // Log the time delta for processing a paint message. On platforms that don't
1564 // support asynchronous painting, this is equivalent to
1565 // MPArch.RWH_TotalPaintTime.
1566 TimeDelta delta = TimeTicks::Now() - paint_start;
1567 UMA_HISTOGRAM_TIMES("MPArch.RWH_OnMsgUpdateRect", delta);
1570 void RenderWidgetHostImpl::DidUpdateBackingStore(
1571 const ViewHostMsg_UpdateRect_Params& params,
1572 const TimeTicks& paint_start) {
1573 TRACE_EVENT0("renderer_host", "RenderWidgetHostImpl::DidUpdateBackingStore");
1574 TimeTicks update_start = TimeTicks::Now();
1576 // Move the plugins if the view hasn't already been destroyed. Plugin moves
1577 // will not be re-issued, so must move them now, regardless of whether we
1578 // paint or not. MovePluginWindows attempts to move the plugin windows and
1579 // in the process could dispatch other window messages which could cause the
1580 // view to be destroyed.
1581 if (view_)
1582 view_->MovePluginWindows(params.plugin_window_moves);
1584 NotificationService::current()->Notify(
1585 NOTIFICATION_RENDER_WIDGET_HOST_DID_UPDATE_BACKING_STORE,
1586 Source<RenderWidgetHost>(this),
1587 NotificationService::NoDetails());
1589 // We don't need to update the view if the view is hidden. We must do this
1590 // early return after the ACK is sent, however, or the renderer will not send
1591 // us more data.
1592 if (is_hidden_)
1593 return;
1595 // If we got a resize ack, then perhaps we have another resize to send?
1596 bool is_resize_ack =
1597 ViewHostMsg_UpdateRect_Flags::is_resize_ack(params.flags);
1598 if (is_resize_ack)
1599 WasResized();
1601 // Log the time delta for processing a paint message.
1602 TimeTicks now = TimeTicks::Now();
1603 TimeDelta delta = now - update_start;
1604 UMA_HISTOGRAM_TIMES("MPArch.RWH_DidUpdateBackingStore", delta);
1607 void RenderWidgetHostImpl::OnQueueSyntheticGesture(
1608 const SyntheticGesturePacket& gesture_packet) {
1609 // Only allow untrustworthy gestures if explicitly enabled.
1610 if (!base::CommandLine::ForCurrentProcess()->HasSwitch(
1611 cc::switches::kEnableGpuBenchmarking)) {
1612 bad_message::ReceivedBadMessage(GetProcess(),
1613 bad_message::RWH_SYNTHETIC_GESTURE);
1614 return;
1617 QueueSyntheticGesture(
1618 SyntheticGesture::Create(*gesture_packet.gesture_params()),
1619 base::Bind(&RenderWidgetHostImpl::OnSyntheticGestureCompleted,
1620 weak_factory_.GetWeakPtr()));
1623 void RenderWidgetHostImpl::OnFocus() {
1624 // Only RenderViewHost can deal with that message.
1625 bad_message::ReceivedBadMessage(GetProcess(), bad_message::RWH_FOCUS);
1628 void RenderWidgetHostImpl::OnBlur() {
1629 // Only RenderViewHost can deal with that message.
1630 bad_message::ReceivedBadMessage(GetProcess(), bad_message::RWH_BLUR);
1633 void RenderWidgetHostImpl::OnSetCursor(const WebCursor& cursor) {
1634 SetCursor(cursor);
1637 void RenderWidgetHostImpl::SetTouchEventEmulationEnabled(
1638 bool enabled, ui::GestureProviderConfigType config_type) {
1639 if (enabled) {
1640 if (!touch_emulator_) {
1641 touch_emulator_.reset(new TouchEmulator(
1642 this, view_ ? content::GetScaleFactorForView(view_) : 1.0f));
1644 touch_emulator_->Enable(config_type);
1645 } else {
1646 if (touch_emulator_)
1647 touch_emulator_->Disable();
1651 void RenderWidgetHostImpl::OnTextInputStateChanged(
1652 const ViewHostMsg_TextInputState_Params& params) {
1653 if (view_)
1654 view_->TextInputStateChanged(params);
1657 void RenderWidgetHostImpl::OnImeCompositionRangeChanged(
1658 const gfx::Range& range,
1659 const std::vector<gfx::Rect>& character_bounds) {
1660 if (view_)
1661 view_->ImeCompositionRangeChanged(range, character_bounds);
1664 void RenderWidgetHostImpl::OnImeCancelComposition() {
1665 if (view_)
1666 view_->ImeCancelComposition();
1669 void RenderWidgetHostImpl::OnLockMouse(bool user_gesture,
1670 bool last_unlocked_by_target,
1671 bool privileged) {
1672 if (pending_mouse_lock_request_) {
1673 Send(new ViewMsg_LockMouse_ACK(routing_id_, false));
1674 return;
1676 if (IsMouseLocked()) {
1677 Send(new ViewMsg_LockMouse_ACK(routing_id_, true));
1678 return;
1681 pending_mouse_lock_request_ = true;
1682 if (privileged && allow_privileged_mouse_lock_) {
1683 // Directly approve to lock the mouse.
1684 GotResponseToLockMouseRequest(true);
1685 } else {
1686 RequestToLockMouse(user_gesture, last_unlocked_by_target);
1690 void RenderWidgetHostImpl::OnUnlockMouse() {
1691 RejectMouseLockOrUnlockIfNecessary();
1694 void RenderWidgetHostImpl::OnShowDisambiguationPopup(
1695 const gfx::Rect& rect_pixels,
1696 const gfx::Size& size,
1697 const cc::SharedBitmapId& id) {
1698 DCHECK(!rect_pixels.IsEmpty());
1699 DCHECK(!size.IsEmpty());
1701 scoped_ptr<cc::SharedBitmap> bitmap =
1702 HostSharedBitmapManager::current()->GetSharedBitmapFromId(size, id);
1703 if (!bitmap) {
1704 bad_message::ReceivedBadMessage(GetProcess(),
1705 bad_message::RWH_SHARED_BITMAP);
1706 return;
1709 DCHECK(bitmap->pixels());
1711 SkImageInfo info = SkImageInfo::MakeN32Premul(size.width(), size.height());
1712 SkBitmap zoomed_bitmap;
1713 zoomed_bitmap.installPixels(info, bitmap->pixels(), info.minRowBytes());
1715 // Note that |rect| is in coordinates of pixels relative to the window origin.
1716 // Aura-based systems will want to convert this to DIPs.
1717 if (view_)
1718 view_->ShowDisambiguationPopup(rect_pixels, zoomed_bitmap);
1720 // It is assumed that the disambiguation popup will make a copy of the
1721 // provided zoomed image, so we delete this one.
1722 zoomed_bitmap.setPixels(0);
1723 Send(new ViewMsg_ReleaseDisambiguationPopupBitmap(GetRoutingID(), id));
1726 #if defined(OS_WIN)
1727 void RenderWidgetHostImpl::OnWindowlessPluginDummyWindowCreated(
1728 gfx::NativeViewId dummy_activation_window) {
1729 HWND hwnd = reinterpret_cast<HWND>(dummy_activation_window);
1731 // This may happen as a result of a race condition when the plugin is going
1732 // away.
1733 wchar_t window_title[MAX_PATH + 1] = {0};
1734 if (!IsWindow(hwnd) ||
1735 !GetWindowText(hwnd, window_title, arraysize(window_title)) ||
1736 lstrcmpiW(window_title, kDummyActivationWindowName) != 0) {
1737 return;
1740 #if defined(USE_AURA)
1741 SetParent(hwnd,
1742 reinterpret_cast<HWND>(view_->GetParentForWindowlessPlugin()));
1743 #else
1744 SetParent(hwnd, reinterpret_cast<HWND>(GetNativeViewId()));
1745 #endif
1746 dummy_windows_for_activation_.push_back(hwnd);
1749 void RenderWidgetHostImpl::OnWindowlessPluginDummyWindowDestroyed(
1750 gfx::NativeViewId dummy_activation_window) {
1751 HWND hwnd = reinterpret_cast<HWND>(dummy_activation_window);
1752 std::list<HWND>::iterator i = dummy_windows_for_activation_.begin();
1753 for (; i != dummy_windows_for_activation_.end(); ++i) {
1754 if ((*i) == hwnd) {
1755 dummy_windows_for_activation_.erase(i);
1756 return;
1759 NOTREACHED() << "Unknown dummy window";
1761 #endif
1763 void RenderWidgetHostImpl::SetIgnoreInputEvents(bool ignore_input_events) {
1764 ignore_input_events_ = ignore_input_events;
1767 bool RenderWidgetHostImpl::KeyPressListenersHandleEvent(
1768 const NativeWebKeyboardEvent& event) {
1769 if (event.skip_in_browser || event.type != WebKeyboardEvent::RawKeyDown)
1770 return false;
1772 for (size_t i = 0; i < key_press_event_callbacks_.size(); i++) {
1773 size_t original_size = key_press_event_callbacks_.size();
1774 if (key_press_event_callbacks_[i].Run(event))
1775 return true;
1777 // Check whether the callback that just ran removed itself, in which case
1778 // the iterator needs to be decremented to properly account for the removal.
1779 size_t current_size = key_press_event_callbacks_.size();
1780 if (current_size != original_size) {
1781 DCHECK_EQ(original_size - 1, current_size);
1782 --i;
1786 return false;
1789 InputEventAckState RenderWidgetHostImpl::FilterInputEvent(
1790 const blink::WebInputEvent& event, const ui::LatencyInfo& latency_info) {
1791 // Don't ignore touch cancel events, since they may be sent while input
1792 // events are being ignored in order to keep the renderer from getting
1793 // confused about how many touches are active.
1794 if (IgnoreInputEvents() && event.type != WebInputEvent::TouchCancel)
1795 return INPUT_EVENT_ACK_STATE_NO_CONSUMER_EXISTS;
1797 if (!process_->HasConnection())
1798 return INPUT_EVENT_ACK_STATE_UNKNOWN;
1800 if (event.type == WebInputEvent::MouseDown ||
1801 event.type == WebInputEvent::GestureTapDown) {
1802 OnUserGesture();
1805 return view_ ? view_->FilterInputEvent(event)
1806 : INPUT_EVENT_ACK_STATE_NOT_CONSUMED;
1809 void RenderWidgetHostImpl::IncrementInFlightEventCount() {
1810 increment_in_flight_event_count();
1811 if (!is_hidden_)
1812 StartHangMonitorTimeout(hung_renderer_delay_);
1815 void RenderWidgetHostImpl::DecrementInFlightEventCount() {
1816 if (decrement_in_flight_event_count() <= 0) {
1817 // Cancel pending hung renderer checks since the renderer is responsive.
1818 StopHangMonitorTimeout();
1819 } else {
1820 // The renderer is responsive, but there are in-flight events to wait for.
1821 if (!is_hidden_)
1822 RestartHangMonitorTimeout();
1826 void RenderWidgetHostImpl::OnHasTouchEventHandlers(bool has_handlers) {
1827 has_touch_handler_ = has_handlers;
1830 void RenderWidgetHostImpl::DidFlush() {
1831 if (synthetic_gesture_controller_)
1832 synthetic_gesture_controller_->OnDidFlushInput();
1835 void RenderWidgetHostImpl::DidOverscroll(const DidOverscrollParams& params) {
1836 if (view_)
1837 view_->DidOverscroll(params);
1840 void RenderWidgetHostImpl::DidStopFlinging() {
1841 if (view_)
1842 view_->DidStopFlinging();
1845 void RenderWidgetHostImpl::OnKeyboardEventAck(
1846 const NativeWebKeyboardEventWithLatencyInfo& event,
1847 InputEventAckState ack_result) {
1848 latency_tracker_.OnInputEventAck(event.event, &event.latency);
1850 #if defined(OS_MACOSX)
1851 if (!is_hidden() && view_ && view_->PostProcessEventForPluginIme(event.event))
1852 return;
1853 #endif
1855 // We only send unprocessed key event upwards if we are not hidden,
1856 // because the user has moved away from us and no longer expect any effect
1857 // of this key event.
1858 const bool processed = (INPUT_EVENT_ACK_STATE_CONSUMED == ack_result);
1859 if (delegate_ && !processed && !is_hidden() && !event.event.skip_in_browser) {
1860 delegate_->HandleKeyboardEvent(event.event);
1862 // WARNING: This RenderWidgetHostImpl can be deallocated at this point
1863 // (i.e. in the case of Ctrl+W, where the call to
1864 // HandleKeyboardEvent destroys this RenderWidgetHostImpl).
1868 void RenderWidgetHostImpl::OnMouseEventAck(
1869 const MouseEventWithLatencyInfo& mouse_event,
1870 InputEventAckState ack_result) {
1871 latency_tracker_.OnInputEventAck(mouse_event.event, &mouse_event.latency);
1874 void RenderWidgetHostImpl::OnWheelEventAck(
1875 const MouseWheelEventWithLatencyInfo& wheel_event,
1876 InputEventAckState ack_result) {
1877 latency_tracker_.OnInputEventAck(wheel_event.event, &wheel_event.latency);
1879 if (!is_hidden() && view_) {
1880 if (ack_result != INPUT_EVENT_ACK_STATE_CONSUMED &&
1881 delegate_->HandleWheelEvent(wheel_event.event)) {
1882 ack_result = INPUT_EVENT_ACK_STATE_CONSUMED;
1884 view_->WheelEventAck(wheel_event.event, ack_result);
1888 void RenderWidgetHostImpl::OnGestureEventAck(
1889 const GestureEventWithLatencyInfo& event,
1890 InputEventAckState ack_result) {
1891 latency_tracker_.OnInputEventAck(event.event, &event.latency);
1893 if (view_)
1894 view_->GestureEventAck(event.event, ack_result);
1897 void RenderWidgetHostImpl::OnTouchEventAck(
1898 const TouchEventWithLatencyInfo& event,
1899 InputEventAckState ack_result) {
1900 latency_tracker_.OnInputEventAck(event.event, &event.latency);
1902 if (touch_emulator_ &&
1903 touch_emulator_->HandleTouchEventAck(event.event, ack_result)) {
1904 return;
1907 if (view_)
1908 view_->ProcessAckedTouchEvent(event, ack_result);
1911 void RenderWidgetHostImpl::OnUnexpectedEventAck(UnexpectedEventAckType type) {
1912 if (type == BAD_ACK_MESSAGE) {
1913 bad_message::ReceivedBadMessage(process_, bad_message::RWH_BAD_ACK_MESSAGE);
1914 } else if (type == UNEXPECTED_EVENT_TYPE) {
1915 suppress_next_char_events_ = false;
1919 void RenderWidgetHostImpl::OnSyntheticGestureCompleted(
1920 SyntheticGesture::Result result) {
1921 Send(new InputMsg_SyntheticGestureCompleted(GetRoutingID()));
1924 bool RenderWidgetHostImpl::IgnoreInputEvents() const {
1925 return ignore_input_events_ || process_->IgnoreInputEvents();
1928 void RenderWidgetHostImpl::StartUserGesture() {
1929 OnUserGesture();
1932 void RenderWidgetHostImpl::SetBackgroundOpaque(bool opaque) {
1933 Send(new ViewMsg_SetBackgroundOpaque(GetRoutingID(), opaque));
1936 void RenderWidgetHostImpl::SetEditCommandsForNextKeyEvent(
1937 const std::vector<EditCommand>& commands) {
1938 Send(new InputMsg_SetEditCommandsForNextKeyEvent(GetRoutingID(), commands));
1941 void RenderWidgetHostImpl::ExecuteEditCommand(const std::string& command,
1942 const std::string& value) {
1943 Send(new InputMsg_ExecuteEditCommand(GetRoutingID(), command, value));
1946 void RenderWidgetHostImpl::ScrollFocusedEditableNodeIntoRect(
1947 const gfx::Rect& rect) {
1948 Send(new InputMsg_ScrollFocusedEditableNodeIntoRect(GetRoutingID(), rect));
1951 void RenderWidgetHostImpl::MoveCaret(const gfx::Point& point) {
1952 Send(new InputMsg_MoveCaret(GetRoutingID(), point));
1955 bool RenderWidgetHostImpl::GotResponseToLockMouseRequest(bool allowed) {
1956 if (!allowed) {
1957 RejectMouseLockOrUnlockIfNecessary();
1958 return false;
1961 if (!pending_mouse_lock_request_) {
1962 // This is possible, e.g., the plugin sends us an unlock request before
1963 // the user allows to lock to mouse.
1964 return false;
1967 pending_mouse_lock_request_ = false;
1968 if (!view_ || !view_->HasFocus()|| !view_->LockMouse()) {
1969 Send(new ViewMsg_LockMouse_ACK(routing_id_, false));
1970 return false;
1973 Send(new ViewMsg_LockMouse_ACK(routing_id_, true));
1974 return true;
1977 // static
1978 void RenderWidgetHostImpl::SendSwapCompositorFrameAck(
1979 int32_t route_id,
1980 uint32_t output_surface_id,
1981 int renderer_host_id,
1982 const cc::CompositorFrameAck& ack) {
1983 RenderProcessHost* host = RenderProcessHost::FromID(renderer_host_id);
1984 if (!host)
1985 return;
1986 host->Send(new ViewMsg_SwapCompositorFrameAck(
1987 route_id, output_surface_id, ack));
1990 // static
1991 void RenderWidgetHostImpl::SendReclaimCompositorResources(
1992 int32_t route_id,
1993 uint32_t output_surface_id,
1994 int renderer_host_id,
1995 const cc::CompositorFrameAck& ack) {
1996 RenderProcessHost* host = RenderProcessHost::FromID(renderer_host_id);
1997 if (!host)
1998 return;
1999 host->Send(
2000 new ViewMsg_ReclaimCompositorResources(route_id, output_surface_id, ack));
2003 void RenderWidgetHostImpl::DelayedAutoResized() {
2004 gfx::Size new_size = new_auto_size_;
2005 // Clear the new_auto_size_ since the empty value is used as a flag to
2006 // indicate that no callback is in progress (i.e. without this line
2007 // DelayedAutoResized will not get called again).
2008 new_auto_size_.SetSize(0, 0);
2009 if (!auto_resize_enabled_)
2010 return;
2012 OnRenderAutoResized(new_size);
2015 void RenderWidgetHostImpl::DetachDelegate() {
2016 delegate_ = NULL;
2019 void RenderWidgetHostImpl::FrameSwapped(const ui::LatencyInfo& latency_info) {
2020 ui::LatencyInfo::LatencyComponent window_snapshot_component;
2021 if (latency_info.FindLatency(ui::WINDOW_SNAPSHOT_FRAME_NUMBER_COMPONENT,
2022 GetLatencyComponentId(),
2023 &window_snapshot_component)) {
2024 int sequence_number = static_cast<int>(
2025 window_snapshot_component.sequence_number);
2026 #if defined(OS_MACOSX)
2027 // On Mac, when using CoreAnmation, there is a delay between when content
2028 // is drawn to the screen, and when the snapshot will actually pick up
2029 // that content. Insert a manual delay of 1/6th of a second (to simulate
2030 // 10 frames at 60 fps) before actually taking the snapshot.
2031 base::MessageLoop::current()->PostDelayedTask(
2032 FROM_HERE,
2033 base::Bind(&RenderWidgetHostImpl::WindowSnapshotReachedScreen,
2034 weak_factory_.GetWeakPtr(),
2035 sequence_number),
2036 base::TimeDelta::FromSecondsD(1. / 6));
2037 #else
2038 WindowSnapshotReachedScreen(sequence_number);
2039 #endif
2042 latency_tracker_.OnFrameSwapped(latency_info);
2045 void RenderWidgetHostImpl::DidReceiveRendererFrame() {
2046 view_->DidReceiveRendererFrame();
2049 void RenderWidgetHostImpl::WindowSnapshotReachedScreen(int snapshot_id) {
2050 DCHECK(base::MessageLoopForUI::IsCurrent());
2052 gfx::Rect view_bounds = GetView()->GetViewBounds();
2053 gfx::Rect snapshot_bounds(view_bounds.size());
2055 std::vector<unsigned char> png;
2056 if (ui::GrabViewSnapshot(
2057 GetView()->GetNativeView(), &png, snapshot_bounds)) {
2058 OnSnapshotDataReceived(snapshot_id, &png.front(), png.size());
2059 return;
2062 ui::GrabViewSnapshotAsync(
2063 GetView()->GetNativeView(),
2064 snapshot_bounds,
2065 base::ThreadTaskRunnerHandle::Get(),
2066 base::Bind(&RenderWidgetHostImpl::OnSnapshotDataReceivedAsync,
2067 weak_factory_.GetWeakPtr(),
2068 snapshot_id));
2071 void RenderWidgetHostImpl::OnSnapshotDataReceived(int snapshot_id,
2072 const unsigned char* data,
2073 size_t size) {
2074 // Any pending snapshots with a lower ID than the one received are considered
2075 // to be implicitly complete, and returned the same snapshot data.
2076 PendingSnapshotMap::iterator it = pending_browser_snapshots_.begin();
2077 while (it != pending_browser_snapshots_.end()) {
2078 if (it->first <= snapshot_id) {
2079 it->second.Run(data, size);
2080 pending_browser_snapshots_.erase(it++);
2081 } else {
2082 ++it;
2087 void RenderWidgetHostImpl::OnSnapshotDataReceivedAsync(
2088 int snapshot_id,
2089 scoped_refptr<base::RefCountedBytes> png_data) {
2090 if (png_data.get())
2091 OnSnapshotDataReceived(snapshot_id, png_data->front(), png_data->size());
2092 else
2093 OnSnapshotDataReceived(snapshot_id, NULL, 0);
2096 // static
2097 void RenderWidgetHostImpl::CompositorFrameDrawn(
2098 const std::vector<ui::LatencyInfo>& latency_info) {
2099 for (size_t i = 0; i < latency_info.size(); i++) {
2100 std::set<RenderWidgetHostImpl*> rwhi_set;
2101 for (const auto& lc : latency_info[i].latency_components()) {
2102 if (lc.first.first == ui::INPUT_EVENT_LATENCY_BEGIN_RWH_COMPONENT ||
2103 lc.first.first == ui::WINDOW_SNAPSHOT_FRAME_NUMBER_COMPONENT ||
2104 lc.first.first == ui::TAB_SHOW_COMPONENT) {
2105 // Matches with GetLatencyComponentId
2106 int routing_id = lc.first.second & 0xffffffff;
2107 int process_id = (lc.first.second >> 32) & 0xffffffff;
2108 RenderWidgetHost* rwh =
2109 RenderWidgetHost::FromID(process_id, routing_id);
2110 if (!rwh) {
2111 continue;
2113 RenderWidgetHostImpl* rwhi = RenderWidgetHostImpl::From(rwh);
2114 if (rwhi_set.insert(rwhi).second)
2115 rwhi->FrameSwapped(latency_info[i]);
2121 BrowserAccessibilityManager*
2122 RenderWidgetHostImpl::GetRootBrowserAccessibilityManager() {
2123 return delegate_ ? delegate_->GetRootBrowserAccessibilityManager() : NULL;
2126 BrowserAccessibilityManager*
2127 RenderWidgetHostImpl::GetOrCreateRootBrowserAccessibilityManager() {
2128 return delegate_ ?
2129 delegate_->GetOrCreateRootBrowserAccessibilityManager() : NULL;
2132 #if defined(OS_WIN)
2133 gfx::NativeViewAccessible
2134 RenderWidgetHostImpl::GetParentNativeViewAccessible() {
2135 return delegate_ ? delegate_->GetParentNativeViewAccessible() : NULL;
2137 #endif
2139 } // namespace content