[Session restore] Rename group name Enabled to Restore.
[chromium-blink-merge.git] / content / browser / renderer_host / render_widget_host_impl.cc
blobfe0203ff98f81e007b0d7e22aaa10b0bd7048e96
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/message_loop/message_loop.h"
18 #include "base/metrics/field_trial.h"
19 #include "base/metrics/histogram.h"
20 #include "base/strings/string_number_conversions.h"
21 #include "base/strings/utf_string_conversions.h"
22 #include "base/thread_task_runner_handle.h"
23 #include "base/trace_event/trace_event.h"
24 #include "cc/base/switches.h"
25 #include "cc/output/compositor_frame.h"
26 #include "cc/output/compositor_frame_ack.h"
27 #include "content/browser/accessibility/accessibility_mode_helper.h"
28 #include "content/browser/accessibility/browser_accessibility_state_impl.h"
29 #include "content/browser/bad_message.h"
30 #include "content/browser/browser_plugin/browser_plugin_guest.h"
31 #include "content/browser/gpu/compositor_util.h"
32 #include "content/browser/gpu/gpu_process_host.h"
33 #include "content/browser/gpu/gpu_process_host_ui_shim.h"
34 #include "content/browser/gpu/gpu_surface_tracker.h"
35 #include "content/browser/renderer_host/dip_util.h"
36 #include "content/browser/renderer_host/frame_metadata_util.h"
37 #include "content/browser/renderer_host/input/input_router_config_helper.h"
38 #include "content/browser/renderer_host/input/input_router_impl.h"
39 #include "content/browser/renderer_host/input/synthetic_gesture.h"
40 #include "content/browser/renderer_host/input/synthetic_gesture_controller.h"
41 #include "content/browser/renderer_host/input/synthetic_gesture_target.h"
42 #include "content/browser/renderer_host/input/timeout_monitor.h"
43 #include "content/browser/renderer_host/input/touch_emulator.h"
44 #include "content/browser/renderer_host/render_process_host_impl.h"
45 #include "content/browser/renderer_host/render_view_host_impl.h"
46 #include "content/browser/renderer_host/render_widget_helper.h"
47 #include "content/browser/renderer_host/render_widget_host_delegate.h"
48 #include "content/browser/renderer_host/render_widget_host_view_base.h"
49 #include "content/browser/renderer_host/render_widget_resize_helper.h"
50 #include "content/common/content_constants_internal.h"
51 #include "content/common/cursors/webcursor.h"
52 #include "content/common/frame_messages.h"
53 #include "content/common/gpu/gpu_messages.h"
54 #include "content/common/host_shared_bitmap_manager.h"
55 #include "content/common/input_messages.h"
56 #include "content/common/view_messages.h"
57 #include "content/public/browser/native_web_keyboard_event.h"
58 #include "content/public/browser/notification_service.h"
59 #include "content/public/browser/notification_types.h"
60 #include "content/public/browser/render_widget_host_iterator.h"
61 #include "content/public/common/content_constants.h"
62 #include "content/public/common/content_switches.h"
63 #include "content/public/common/result_codes.h"
64 #include "content/public/common/web_preferences.h"
65 #include "gpu/GLES2/gl2extchromium.h"
66 #include "gpu/command_buffer/service/gpu_switches.h"
67 #include "skia/ext/image_operations.h"
68 #include "skia/ext/platform_canvas.h"
69 #include "third_party/WebKit/public/web/WebCompositionUnderline.h"
70 #include "ui/events/event.h"
71 #include "ui/events/keycodes/keyboard_codes.h"
72 #include "ui/gfx/geometry/size_conversions.h"
73 #include "ui/gfx/geometry/vector2d_conversions.h"
74 #include "ui/gfx/skbitmap_operations.h"
75 #include "ui/snapshot/snapshot.h"
77 #if defined(OS_WIN)
78 #include "content/common/plugin_constants_win.h"
79 #endif
81 using base::Time;
82 using base::TimeDelta;
83 using base::TimeTicks;
84 using blink::WebGestureEvent;
85 using blink::WebInputEvent;
86 using blink::WebKeyboardEvent;
87 using blink::WebMouseEvent;
88 using blink::WebMouseWheelEvent;
89 using blink::WebTextDirection;
91 namespace content {
92 namespace {
94 bool g_check_for_pending_resize_ack = true;
96 typedef std::pair<int32, int32> RenderWidgetHostID;
97 typedef base::hash_map<RenderWidgetHostID, RenderWidgetHostImpl*>
98 RoutingIDWidgetMap;
99 base::LazyInstance<RoutingIDWidgetMap> g_routing_id_widget_map =
100 LAZY_INSTANCE_INITIALIZER;
102 int GetInputRouterViewFlagsFromCompositorFrameMetadata(
103 const cc::CompositorFrameMetadata metadata) {
104 int view_flags = InputRouter::VIEW_FLAGS_NONE;
106 if (metadata.min_page_scale_factor == metadata.max_page_scale_factor)
107 view_flags |= InputRouter::FIXED_PAGE_SCALE;
109 const float window_width_dip = std::ceil(
110 metadata.page_scale_factor * metadata.scrollable_viewport_size.width());
111 const float content_width_css = metadata.root_layer_size.width();
112 if (content_width_css <= window_width_dip)
113 view_flags |= InputRouter::MOBILE_VIEWPORT;
115 return view_flags;
118 // Implements the RenderWidgetHostIterator interface. It keeps a list of
119 // RenderWidgetHosts, and makes sure it returns a live RenderWidgetHost at each
120 // iteration (or NULL if there isn't any left).
121 class RenderWidgetHostIteratorImpl : public RenderWidgetHostIterator {
122 public:
123 RenderWidgetHostIteratorImpl()
124 : current_index_(0) {
127 ~RenderWidgetHostIteratorImpl() override {}
129 void Add(RenderWidgetHost* host) {
130 hosts_.push_back(RenderWidgetHostID(host->GetProcess()->GetID(),
131 host->GetRoutingID()));
134 // RenderWidgetHostIterator:
135 RenderWidgetHost* GetNextHost() override {
136 RenderWidgetHost* host = NULL;
137 while (current_index_ < hosts_.size() && !host) {
138 RenderWidgetHostID id = hosts_[current_index_];
139 host = RenderWidgetHost::FromID(id.first, id.second);
140 ++current_index_;
142 return host;
145 private:
146 std::vector<RenderWidgetHostID> hosts_;
147 size_t current_index_;
149 DISALLOW_COPY_AND_ASSIGN(RenderWidgetHostIteratorImpl);
152 } // namespace
154 ///////////////////////////////////////////////////////////////////////////////
155 // RenderWidgetHostImpl
157 RenderWidgetHostImpl::RenderWidgetHostImpl(RenderWidgetHostDelegate* delegate,
158 RenderProcessHost* process,
159 int routing_id,
160 bool hidden)
161 : view_(NULL),
162 renderer_initialized_(false),
163 hung_renderer_delay_(
164 base::TimeDelta::FromMilliseconds(kHungRendererDelayMs)),
165 delegate_(delegate),
166 process_(process),
167 routing_id_(routing_id),
168 surface_id_(0),
169 is_loading_(false),
170 is_hidden_(hidden),
171 repaint_ack_pending_(false),
172 resize_ack_pending_(false),
173 screen_info_out_of_date_(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 GpuSurfaceTracker::Get()->SetSurfaceHandle(
326 surface_id_, GetCompositingSurface());
328 synthetic_gesture_controller_.reset();
331 RenderProcessHost* RenderWidgetHostImpl::GetProcess() const {
332 return process_;
335 int RenderWidgetHostImpl::GetRoutingID() const {
336 return routing_id_;
339 RenderWidgetHostView* RenderWidgetHostImpl::GetView() const {
340 return view_;
343 RenderWidgetHostImpl* RenderWidgetHostImpl::AsRenderWidgetHostImpl() {
344 return this;
347 gfx::NativeViewId RenderWidgetHostImpl::GetNativeViewId() const {
348 if (view_)
349 return view_->GetNativeViewId();
350 return 0;
353 gfx::GLSurfaceHandle RenderWidgetHostImpl::GetCompositingSurface() {
354 if (view_)
355 return view_->GetCompositingSurface();
356 return gfx::GLSurfaceHandle();
359 void RenderWidgetHostImpl::ResetSizeAndRepaintPendingFlags() {
360 resize_ack_pending_ = false;
361 if (repaint_ack_pending_) {
362 TRACE_EVENT_ASYNC_END0(
363 "renderer_host", "RenderWidgetHostImpl::repaint_ack_pending_", this);
365 repaint_ack_pending_ = false;
366 if (old_resize_params_)
367 old_resize_params_->new_size = gfx::Size();
370 void RenderWidgetHostImpl::SendScreenRects() {
371 if (!renderer_initialized_ || waiting_for_screen_rects_ack_)
372 return;
374 if (is_hidden_) {
375 // On GTK, this comes in for backgrounded tabs. Ignore, to match what
376 // happens on Win & Mac, and when the view is shown it'll call this again.
377 return;
380 if (!view_)
381 return;
383 last_view_screen_rect_ = view_->GetViewBounds();
384 last_window_screen_rect_ = view_->GetBoundsInRootWindow();
385 Send(new ViewMsg_UpdateScreenRects(
386 GetRoutingID(), last_view_screen_rect_, last_window_screen_rect_));
387 if (delegate_)
388 delegate_->DidSendScreenRects(this);
389 waiting_for_screen_rects_ack_ = true;
392 void RenderWidgetHostImpl::SuppressNextCharEvents() {
393 suppress_next_char_events_ = true;
396 void RenderWidgetHostImpl::FlushInput() {
397 input_router_->RequestNotificationWhenFlushed();
398 if (synthetic_gesture_controller_)
399 synthetic_gesture_controller_->Flush(base::TimeTicks::Now());
402 void RenderWidgetHostImpl::SetNeedsFlush() {
403 if (view_)
404 view_->OnSetNeedsFlushInput();
407 void RenderWidgetHostImpl::Init() {
408 DCHECK(process_->HasConnection());
410 renderer_initialized_ = true;
412 GpuSurfaceTracker::Get()->SetSurfaceHandle(
413 surface_id_, GetCompositingSurface());
415 // Send the ack along with the information on placement.
416 Send(new ViewMsg_CreatingNew_ACK(routing_id_));
417 GetProcess()->ResumeRequestsForView(routing_id_);
419 WasResized();
422 void RenderWidgetHostImpl::InitForFrame() {
423 DCHECK(process_->HasConnection());
424 renderer_initialized_ = true;
427 void RenderWidgetHostImpl::Shutdown() {
428 RejectMouseLockOrUnlockIfNecessary();
430 if (process_->HasConnection()) {
431 // Tell the renderer object to close.
432 bool rv = Send(new ViewMsg_Close(routing_id_));
433 DCHECK(rv);
436 Destroy();
439 bool RenderWidgetHostImpl::IsLoading() const {
440 return is_loading_;
443 bool RenderWidgetHostImpl::IsRenderView() const {
444 return false;
447 bool RenderWidgetHostImpl::OnMessageReceived(const IPC::Message &msg) {
448 bool handled = true;
449 IPC_BEGIN_MESSAGE_MAP(RenderWidgetHostImpl, msg)
450 IPC_MESSAGE_HANDLER(FrameHostMsg_RenderProcessGone, OnRenderProcessGone)
451 IPC_MESSAGE_HANDLER(InputHostMsg_QueueSyntheticGesture,
452 OnQueueSyntheticGesture)
453 IPC_MESSAGE_HANDLER(InputHostMsg_ImeCancelComposition,
454 OnImeCancelComposition)
455 IPC_MESSAGE_HANDLER(ViewHostMsg_RenderViewReady, OnRenderViewReady)
456 IPC_MESSAGE_HANDLER(ViewHostMsg_Close, OnClose)
457 IPC_MESSAGE_HANDLER(ViewHostMsg_UpdateScreenRects_ACK,
458 OnUpdateScreenRectsAck)
459 IPC_MESSAGE_HANDLER(ViewHostMsg_RequestMove, OnRequestMove)
460 IPC_MESSAGE_HANDLER(ViewHostMsg_SetTooltipText, OnSetTooltipText)
461 IPC_MESSAGE_HANDLER_GENERIC(ViewHostMsg_SwapCompositorFrame,
462 OnSwapCompositorFrame(msg))
463 IPC_MESSAGE_HANDLER(ViewHostMsg_UpdateRect, OnUpdateRect)
464 IPC_MESSAGE_HANDLER(ViewHostMsg_Focus, OnFocus)
465 IPC_MESSAGE_HANDLER(ViewHostMsg_Blur, OnBlur)
466 IPC_MESSAGE_HANDLER(ViewHostMsg_SetCursor, OnSetCursor)
467 IPC_MESSAGE_HANDLER(ViewHostMsg_TextInputTypeChanged,
468 OnTextInputTypeChanged)
469 IPC_MESSAGE_HANDLER(ViewHostMsg_LockMouse, OnLockMouse)
470 IPC_MESSAGE_HANDLER(ViewHostMsg_UnlockMouse, OnUnlockMouse)
471 IPC_MESSAGE_HANDLER(ViewHostMsg_ShowDisambiguationPopup,
472 OnShowDisambiguationPopup)
473 IPC_MESSAGE_HANDLER(ViewHostMsg_SelectionChanged, OnSelectionChanged)
474 IPC_MESSAGE_HANDLER(ViewHostMsg_SelectionBoundsChanged,
475 OnSelectionBoundsChanged)
476 #if defined(OS_WIN)
477 IPC_MESSAGE_HANDLER(ViewHostMsg_WindowlessPluginDummyWindowCreated,
478 OnWindowlessPluginDummyWindowCreated)
479 IPC_MESSAGE_HANDLER(ViewHostMsg_WindowlessPluginDummyWindowDestroyed,
480 OnWindowlessPluginDummyWindowDestroyed)
481 #endif
482 IPC_MESSAGE_HANDLER(InputHostMsg_ImeCompositionRangeChanged,
483 OnImeCompositionRangeChanged)
484 IPC_MESSAGE_UNHANDLED(handled = false)
485 IPC_END_MESSAGE_MAP()
487 if (!handled && input_router_ && input_router_->OnMessageReceived(msg))
488 return true;
490 if (!handled && view_ && view_->OnMessageReceived(msg))
491 return true;
493 return handled;
496 bool RenderWidgetHostImpl::Send(IPC::Message* msg) {
497 if (IPC_MESSAGE_ID_CLASS(msg->type()) == InputMsgStart)
498 return input_router_->SendInput(make_scoped_ptr(msg));
500 return process_->Send(msg);
503 void RenderWidgetHostImpl::SetIsLoading(bool is_loading) {
504 is_loading_ = is_loading;
505 if (!view_)
506 return;
507 view_->SetIsLoading(is_loading);
510 void RenderWidgetHostImpl::WasHidden() {
511 if (is_hidden_)
512 return;
514 TRACE_EVENT0("renderer_host", "RenderWidgetHostImpl::WasHidden");
515 is_hidden_ = true;
517 // Don't bother reporting hung state when we aren't active.
518 StopHangMonitorTimeout();
520 // If we have a renderer, then inform it that we are being hidden so it can
521 // reduce its resource utilization.
522 Send(new ViewMsg_WasHidden(routing_id_));
524 // Tell the RenderProcessHost we were hidden.
525 process_->WidgetHidden();
527 bool is_visible = false;
528 NotificationService::current()->Notify(
529 NOTIFICATION_RENDER_WIDGET_VISIBILITY_CHANGED,
530 Source<RenderWidgetHost>(this),
531 Details<bool>(&is_visible));
534 void RenderWidgetHostImpl::WasShown(const ui::LatencyInfo& latency_info) {
535 if (!is_hidden_)
536 return;
538 TRACE_EVENT0("renderer_host", "RenderWidgetHostImpl::WasShown");
539 is_hidden_ = false;
541 SendScreenRects();
543 // When hidden, timeout monitoring for input events is disabled. Restore it
544 // now to ensure consistent hang detection.
545 if (in_flight_event_count_)
546 RestartHangMonitorTimeout();
548 // Always repaint on restore.
549 bool needs_repainting = true;
550 needs_repainting_on_restore_ = false;
551 Send(new ViewMsg_WasShown(routing_id_, needs_repainting, latency_info));
553 process_->WidgetRestored();
555 bool is_visible = true;
556 NotificationService::current()->Notify(
557 NOTIFICATION_RENDER_WIDGET_VISIBILITY_CHANGED,
558 Source<RenderWidgetHost>(this),
559 Details<bool>(&is_visible));
561 // It's possible for our size to be out of sync with the renderer. The
562 // following is one case that leads to this:
563 // 1. WasResized -> Send ViewMsg_Resize to render
564 // 2. WasResized -> do nothing as resize_ack_pending_ is true
565 // 3. WasHidden
566 // 4. OnUpdateRect from (1) processed. Does NOT invoke WasResized as view
567 // is hidden. Now renderer/browser out of sync with what they think size
568 // is.
569 // By invoking WasResized the renderer is updated as necessary. WasResized
570 // does nothing if the sizes are already in sync.
572 // TODO: ideally ViewMsg_WasShown would take a size. This way, the renderer
573 // could handle both the restore and resize at once. This isn't that big a
574 // deal as RenderWidget::WasShown delays updating, so that the resize from
575 // WasResized is usually processed before the renderer is painted.
576 WasResized();
579 bool RenderWidgetHostImpl::GetResizeParams(
580 ViewMsg_Resize_Params* resize_params) {
581 *resize_params = ViewMsg_Resize_Params();
583 if (!screen_info_) {
584 screen_info_.reset(new blink::WebScreenInfo);
585 GetWebScreenInfo(screen_info_.get());
587 resize_params->screen_info = *screen_info_;
588 resize_params->resizer_rect = GetRootWindowResizerRect();
590 if (view_) {
591 resize_params->new_size = view_->GetRequestedRendererSize();
592 resize_params->physical_backing_size = view_->GetPhysicalBackingSize();
593 resize_params->top_controls_height = view_->GetTopControlsHeight();
594 resize_params->top_controls_shrink_blink_size =
595 view_->DoTopControlsShrinkBlinkSize();
596 resize_params->visible_viewport_size = view_->GetVisibleViewportSize();
597 resize_params->is_fullscreen = IsFullscreen();
600 const bool size_changed =
601 !old_resize_params_ ||
602 old_resize_params_->new_size != resize_params->new_size ||
603 (old_resize_params_->physical_backing_size.IsEmpty() &&
604 !resize_params->physical_backing_size.IsEmpty());
605 bool dirty =
606 size_changed || screen_info_out_of_date_ ||
607 old_resize_params_->physical_backing_size !=
608 resize_params->physical_backing_size ||
609 old_resize_params_->is_fullscreen != resize_params->is_fullscreen ||
610 old_resize_params_->top_controls_height !=
611 resize_params->top_controls_height ||
612 old_resize_params_->top_controls_shrink_blink_size !=
613 resize_params->top_controls_shrink_blink_size ||
614 old_resize_params_->visible_viewport_size !=
615 resize_params->visible_viewport_size;
617 // We don't expect to receive an ACK when the requested size or the physical
618 // backing size is empty, or when the main viewport size didn't change.
619 resize_params->needs_resize_ack =
620 g_check_for_pending_resize_ack && !resize_params->new_size.IsEmpty() &&
621 !resize_params->physical_backing_size.IsEmpty() && size_changed;
623 return dirty;
626 void RenderWidgetHostImpl::SetInitialRenderSizeParams(
627 const ViewMsg_Resize_Params& resize_params) {
628 resize_ack_pending_ = resize_params.needs_resize_ack;
630 old_resize_params_ =
631 make_scoped_ptr(new ViewMsg_Resize_Params(resize_params));
634 void RenderWidgetHostImpl::WasResized() {
635 // Skip if the |delegate_| has already been detached because
636 // it's web contents is being deleted.
637 if (resize_ack_pending_ || !process_->HasConnection() || !view_ ||
638 !renderer_initialized_ || auto_resize_enabled_ || !delegate_) {
639 return;
642 scoped_ptr<ViewMsg_Resize_Params> params(new ViewMsg_Resize_Params);
643 if (!GetResizeParams(params.get()))
644 return;
646 bool width_changed =
647 !old_resize_params_ ||
648 old_resize_params_->new_size.width() != params->new_size.width();
649 if (Send(new ViewMsg_Resize(routing_id_, *params))) {
650 resize_ack_pending_ = params->needs_resize_ack;
651 old_resize_params_.swap(params);
654 if (delegate_)
655 delegate_->RenderWidgetWasResized(this, width_changed);
658 void RenderWidgetHostImpl::ResizeRectChanged(const gfx::Rect& new_rect) {
659 Send(new ViewMsg_ChangeResizeRect(routing_id_, new_rect));
662 void RenderWidgetHostImpl::GotFocus() {
663 Focus();
664 if (delegate_)
665 delegate_->RenderWidgetGotFocus(this);
668 void RenderWidgetHostImpl::Focus() {
669 is_focused_ = true;
671 Send(new InputMsg_SetFocus(routing_id_, true));
674 void RenderWidgetHostImpl::Blur() {
675 is_focused_ = false;
677 // If there is a pending mouse lock request, we don't want to reject it at
678 // this point. The user can switch focus back to this view and approve the
679 // request later.
680 if (IsMouseLocked())
681 view_->UnlockMouse();
683 if (touch_emulator_)
684 touch_emulator_->CancelTouch();
686 Send(new InputMsg_SetFocus(routing_id_, false));
689 void RenderWidgetHostImpl::LostCapture() {
690 if (touch_emulator_)
691 touch_emulator_->CancelTouch();
693 Send(new InputMsg_MouseCaptureLost(routing_id_));
696 void RenderWidgetHostImpl::SetActive(bool active) {
697 Send(new ViewMsg_SetActive(routing_id_, active));
700 void RenderWidgetHostImpl::LostMouseLock() {
701 Send(new ViewMsg_MouseLockLost(routing_id_));
704 void RenderWidgetHostImpl::ViewDestroyed() {
705 RejectMouseLockOrUnlockIfNecessary();
707 // TODO(evanm): tracking this may no longer be necessary;
708 // eliminate this function if so.
709 SetView(NULL);
712 void RenderWidgetHostImpl::CopyFromBackingStore(
713 const gfx::Rect& src_subrect,
714 const gfx::Size& accelerated_dst_size,
715 ReadbackRequestCallback& callback,
716 const SkColorType color_type) {
717 if (view_) {
718 TRACE_EVENT0("browser",
719 "RenderWidgetHostImpl::CopyFromBackingStore::FromCompositingSurface");
720 gfx::Rect accelerated_copy_rect = src_subrect.IsEmpty() ?
721 gfx::Rect(view_->GetViewBounds().size()) : src_subrect;
722 view_->CopyFromCompositingSurface(
723 accelerated_copy_rect, accelerated_dst_size, callback, color_type);
724 return;
727 callback.Run(SkBitmap(), content::READBACK_FAILED);
730 bool RenderWidgetHostImpl::CanCopyFromBackingStore() {
731 if (view_)
732 return view_->IsSurfaceAvailableForCopy();
733 return false;
736 #if defined(OS_ANDROID)
737 void RenderWidgetHostImpl::LockBackingStore() {
738 if (view_)
739 view_->LockCompositingSurface();
742 void RenderWidgetHostImpl::UnlockBackingStore() {
743 if (view_)
744 view_->UnlockCompositingSurface();
746 #endif
748 #if defined(OS_MACOSX)
749 void RenderWidgetHostImpl::PauseForPendingResizeOrRepaints() {
750 TRACE_EVENT0("browser",
751 "RenderWidgetHostImpl::PauseForPendingResizeOrRepaints");
753 if (!CanPauseForPendingResizeOrRepaints())
754 return;
756 WaitForSurface();
759 bool RenderWidgetHostImpl::CanPauseForPendingResizeOrRepaints() {
760 // Do not pause if the view is hidden.
761 if (is_hidden())
762 return false;
764 // Do not pause if there is not a paint or resize already coming.
765 if (!repaint_ack_pending_ && !resize_ack_pending_)
766 return false;
768 return true;
771 void RenderWidgetHostImpl::WaitForSurface() {
772 // How long to (synchronously) wait for the renderer to respond with a
773 // new frame when our current frame doesn't exist or is the wrong size.
774 // This timeout impacts the "choppiness" of our window resize.
775 const int kPaintMsgTimeoutMS = 50;
777 if (!view_)
778 return;
780 // The view_size will be current_size_ for auto-sized views and otherwise the
781 // size of the view_. (For auto-sized views, current_size_ is updated during
782 // UpdateRect messages.)
783 gfx::Size view_size = current_size_;
784 if (!auto_resize_enabled_) {
785 // Get the desired size from the current view bounds.
786 gfx::Rect view_rect = view_->GetViewBounds();
787 if (view_rect.IsEmpty())
788 return;
789 view_size = view_rect.size();
792 TRACE_EVENT2("renderer_host",
793 "RenderWidgetHostImpl::WaitForSurface",
794 "width",
795 base::IntToString(view_size.width()),
796 "height",
797 base::IntToString(view_size.height()));
799 // We should not be asked to paint while we are hidden. If we are hidden,
800 // then it means that our consumer failed to call WasShown.
801 DCHECK(!is_hidden_) << "WaitForSurface called while hidden!";
803 // We should never be called recursively; this can theoretically lead to
804 // infinite recursion and almost certainly leads to lower performance.
805 DCHECK(!in_get_backing_store_) << "WaitForSurface called recursively!";
806 base::AutoReset<bool> auto_reset_in_get_backing_store(
807 &in_get_backing_store_, true);
809 // We might have a surface that we can use already.
810 if (view_->HasAcceleratedSurface(view_size))
811 return;
813 // Request that the renderer produce a frame of the right size, if it
814 // hasn't been requested already.
815 if (!repaint_ack_pending_ && !resize_ack_pending_) {
816 repaint_start_time_ = TimeTicks::Now();
817 repaint_ack_pending_ = true;
818 TRACE_EVENT_ASYNC_BEGIN0(
819 "renderer_host", "RenderWidgetHostImpl::repaint_ack_pending_", this);
820 Send(new ViewMsg_Repaint(routing_id_, view_size));
823 // Pump a nested message loop until we time out or get a frame of the right
824 // size.
825 TimeTicks start_time = TimeTicks::Now();
826 TimeDelta time_left = TimeDelta::FromMilliseconds(kPaintMsgTimeoutMS);
827 TimeTicks timeout_time = start_time + time_left;
828 while (1) {
829 TRACE_EVENT0("renderer_host", "WaitForSurface::WaitForSingleTaskToRun");
830 if (RenderWidgetResizeHelper::Get()->WaitForSingleTaskToRun(time_left)) {
831 // For auto-resized views, current_size_ determines the view_size and it
832 // may have changed during the handling of an UpdateRect message.
833 if (auto_resize_enabled_)
834 view_size = current_size_;
835 if (view_->HasAcceleratedSurface(view_size))
836 break;
838 time_left = timeout_time - TimeTicks::Now();
839 if (time_left <= TimeDelta::FromSeconds(0)) {
840 TRACE_EVENT0("renderer_host", "WaitForSurface::Timeout");
841 break;
845 UMA_HISTOGRAM_CUSTOM_TIMES("OSX.RendererHost.SurfaceWaitTime",
846 TimeTicks::Now() - start_time,
847 TimeDelta::FromMilliseconds(1),
848 TimeDelta::FromMilliseconds(200), 50);
850 #endif
852 bool RenderWidgetHostImpl::ScheduleComposite() {
853 if (is_hidden_ || current_size_.IsEmpty() || repaint_ack_pending_ ||
854 resize_ack_pending_) {
855 return false;
858 // Send out a request to the renderer to paint the view if required.
859 repaint_start_time_ = TimeTicks::Now();
860 repaint_ack_pending_ = true;
861 TRACE_EVENT_ASYNC_BEGIN0(
862 "renderer_host", "RenderWidgetHostImpl::repaint_ack_pending_", this);
863 Send(new ViewMsg_Repaint(routing_id_, current_size_));
864 return true;
867 void RenderWidgetHostImpl::StartHangMonitorTimeout(base::TimeDelta delay) {
868 if (hang_monitor_timeout_)
869 hang_monitor_timeout_->Start(delay);
872 void RenderWidgetHostImpl::RestartHangMonitorTimeout() {
873 if (hang_monitor_timeout_)
874 hang_monitor_timeout_->Restart(hung_renderer_delay_);
877 void RenderWidgetHostImpl::StopHangMonitorTimeout() {
878 if (hang_monitor_timeout_)
879 hang_monitor_timeout_->Stop();
880 RendererIsResponsive();
883 void RenderWidgetHostImpl::ForwardMouseEvent(const WebMouseEvent& mouse_event) {
884 ForwardMouseEventWithLatencyInfo(mouse_event, ui::LatencyInfo());
887 void RenderWidgetHostImpl::ForwardMouseEventWithLatencyInfo(
888 const blink::WebMouseEvent& mouse_event,
889 const ui::LatencyInfo& ui_latency) {
890 TRACE_EVENT2("input", "RenderWidgetHostImpl::ForwardMouseEvent",
891 "x", mouse_event.x, "y", mouse_event.y);
893 for (size_t i = 0; i < mouse_event_callbacks_.size(); ++i) {
894 if (mouse_event_callbacks_[i].Run(mouse_event))
895 return;
898 if (IgnoreInputEvents())
899 return;
901 if (touch_emulator_ && touch_emulator_->HandleMouseEvent(mouse_event))
902 return;
904 MouseEventWithLatencyInfo mouse_with_latency(mouse_event, ui_latency);
905 latency_tracker_.OnInputEvent(mouse_event, &mouse_with_latency.latency);
906 input_router_->SendMouseEvent(mouse_with_latency);
908 // Pass mouse state to gpu service if the subscribe uniform
909 // extension is enabled.
910 if (process_->SubscribeUniformEnabled()) {
911 gpu::ValueState state;
912 state.int_value[0] = mouse_event.x;
913 state.int_value[1] = mouse_event.y;
914 // TODO(orglofch) Separate the mapping of pending value states to the
915 // Gpu Service to be per RWH not per process
916 process_->SendUpdateValueState(GL_MOUSE_POSITION_CHROMIUM, state);
920 void RenderWidgetHostImpl::ForwardWheelEvent(
921 const WebMouseWheelEvent& wheel_event) {
922 ForwardWheelEventWithLatencyInfo(wheel_event, ui::LatencyInfo());
925 void RenderWidgetHostImpl::ForwardWheelEventWithLatencyInfo(
926 const blink::WebMouseWheelEvent& wheel_event,
927 const ui::LatencyInfo& ui_latency) {
928 TRACE_EVENT0("input", "RenderWidgetHostImpl::ForwardWheelEvent");
930 if (IgnoreInputEvents())
931 return;
933 if (touch_emulator_ && touch_emulator_->HandleMouseWheelEvent(wheel_event))
934 return;
936 MouseWheelEventWithLatencyInfo wheel_with_latency(wheel_event, ui_latency);
937 latency_tracker_.OnInputEvent(wheel_event, &wheel_with_latency.latency);
938 input_router_->SendWheelEvent(wheel_with_latency);
941 void RenderWidgetHostImpl::ForwardGestureEvent(
942 const blink::WebGestureEvent& gesture_event) {
943 ForwardGestureEventWithLatencyInfo(gesture_event, ui::LatencyInfo());
946 void RenderWidgetHostImpl::ForwardGestureEventWithLatencyInfo(
947 const blink::WebGestureEvent& gesture_event,
948 const ui::LatencyInfo& ui_latency) {
949 TRACE_EVENT0("input", "RenderWidgetHostImpl::ForwardGestureEvent");
950 // Early out if necessary, prior to performing latency logic.
951 if (IgnoreInputEvents())
952 return;
954 if (delegate_->PreHandleGestureEvent(gesture_event))
955 return;
957 GestureEventWithLatencyInfo gesture_with_latency(gesture_event, ui_latency);
958 latency_tracker_.OnInputEvent(gesture_event, &gesture_with_latency.latency);
959 input_router_->SendGestureEvent(gesture_with_latency);
962 void RenderWidgetHostImpl::ForwardEmulatedTouchEvent(
963 const blink::WebTouchEvent& touch_event) {
964 TRACE_EVENT0("input", "RenderWidgetHostImpl::ForwardEmulatedTouchEvent");
966 TouchEventWithLatencyInfo touch_with_latency(touch_event);
967 latency_tracker_.OnInputEvent(touch_event, &touch_with_latency.latency);
968 input_router_->SendTouchEvent(touch_with_latency);
971 void RenderWidgetHostImpl::ForwardTouchEventWithLatencyInfo(
972 const blink::WebTouchEvent& touch_event,
973 const ui::LatencyInfo& ui_latency) {
974 TRACE_EVENT0("input", "RenderWidgetHostImpl::ForwardTouchEvent");
976 // Always forward TouchEvents for touch stream consistency. They will be
977 // ignored if appropriate in FilterInputEvent().
979 TouchEventWithLatencyInfo touch_with_latency(touch_event, ui_latency);
980 if (touch_emulator_ &&
981 touch_emulator_->HandleTouchEvent(touch_with_latency.event)) {
982 if (view_) {
983 view_->ProcessAckedTouchEvent(
984 touch_with_latency, INPUT_EVENT_ACK_STATE_CONSUMED);
986 return;
989 latency_tracker_.OnInputEvent(touch_event, &touch_with_latency.latency);
990 input_router_->SendTouchEvent(touch_with_latency);
993 void RenderWidgetHostImpl::ForwardKeyboardEvent(
994 const NativeWebKeyboardEvent& key_event) {
995 TRACE_EVENT0("input", "RenderWidgetHostImpl::ForwardKeyboardEvent");
996 if (IgnoreInputEvents())
997 return;
999 if (!process_->HasConnection())
1000 return;
1002 // First, let keypress listeners take a shot at handling the event. If a
1003 // listener handles the event, it should not be propagated to the renderer.
1004 if (KeyPressListenersHandleEvent(key_event)) {
1005 // Some keypresses that are accepted by the listener might have follow up
1006 // char events, which should be ignored.
1007 if (key_event.type == WebKeyboardEvent::RawKeyDown)
1008 suppress_next_char_events_ = true;
1009 return;
1012 if (key_event.type == WebKeyboardEvent::Char &&
1013 (key_event.windowsKeyCode == ui::VKEY_RETURN ||
1014 key_event.windowsKeyCode == ui::VKEY_SPACE)) {
1015 OnUserGesture();
1018 // Double check the type to make sure caller hasn't sent us nonsense that
1019 // will mess up our key queue.
1020 if (!WebInputEvent::isKeyboardEventType(key_event.type))
1021 return;
1023 if (suppress_next_char_events_) {
1024 // If preceding RawKeyDown event was handled by the browser, then we need
1025 // suppress all Char events generated by it. Please note that, one
1026 // RawKeyDown event may generate multiple Char events, so we can't reset
1027 // |suppress_next_char_events_| until we get a KeyUp or a RawKeyDown.
1028 if (key_event.type == WebKeyboardEvent::Char)
1029 return;
1030 // We get a KeyUp or a RawKeyDown event.
1031 suppress_next_char_events_ = false;
1034 bool is_shortcut = false;
1036 // Only pre-handle the key event if it's not handled by the input method.
1037 if (delegate_ && !key_event.skip_in_browser) {
1038 // We need to set |suppress_next_char_events_| to true if
1039 // PreHandleKeyboardEvent() returns true, but |this| may already be
1040 // destroyed at that time. So set |suppress_next_char_events_| true here,
1041 // then revert it afterwards when necessary.
1042 if (key_event.type == WebKeyboardEvent::RawKeyDown)
1043 suppress_next_char_events_ = true;
1045 // Tab switching/closing accelerators aren't sent to the renderer to avoid
1046 // a hung/malicious renderer from interfering.
1047 if (delegate_->PreHandleKeyboardEvent(key_event, &is_shortcut))
1048 return;
1050 if (key_event.type == WebKeyboardEvent::RawKeyDown)
1051 suppress_next_char_events_ = false;
1054 if (touch_emulator_ && touch_emulator_->HandleKeyboardEvent(key_event))
1055 return;
1057 ui::LatencyInfo latency;
1058 latency_tracker_.OnInputEvent(key_event, &latency);
1059 input_router_->SendKeyboardEvent(key_event, latency, is_shortcut);
1062 void RenderWidgetHostImpl::QueueSyntheticGesture(
1063 scoped_ptr<SyntheticGesture> synthetic_gesture,
1064 const base::Callback<void(SyntheticGesture::Result)>& on_complete) {
1065 if (!synthetic_gesture_controller_ && view_) {
1066 synthetic_gesture_controller_.reset(
1067 new SyntheticGestureController(
1068 view_->CreateSyntheticGestureTarget().Pass()));
1070 if (synthetic_gesture_controller_) {
1071 synthetic_gesture_controller_->QueueSyntheticGesture(
1072 synthetic_gesture.Pass(), on_complete);
1076 void RenderWidgetHostImpl::SetCursor(const WebCursor& cursor) {
1077 if (!view_)
1078 return;
1079 view_->UpdateCursor(cursor);
1082 void RenderWidgetHostImpl::ShowContextMenuAtPoint(const gfx::Point& point) {
1083 Send(new ViewMsg_ShowContextMenu(
1084 GetRoutingID(), ui::MENU_SOURCE_MOUSE, point));
1087 void RenderWidgetHostImpl::SendCursorVisibilityState(bool is_visible) {
1088 Send(new InputMsg_CursorVisibilityChange(GetRoutingID(), is_visible));
1091 int64 RenderWidgetHostImpl::GetLatencyComponentId() const {
1092 return latency_tracker_.latency_component_id();
1095 // static
1096 void RenderWidgetHostImpl::DisableResizeAckCheckForTesting() {
1097 g_check_for_pending_resize_ack = false;
1100 void RenderWidgetHostImpl::AddKeyPressEventCallback(
1101 const KeyPressEventCallback& callback) {
1102 key_press_event_callbacks_.push_back(callback);
1105 void RenderWidgetHostImpl::RemoveKeyPressEventCallback(
1106 const KeyPressEventCallback& callback) {
1107 for (size_t i = 0; i < key_press_event_callbacks_.size(); ++i) {
1108 if (key_press_event_callbacks_[i].Equals(callback)) {
1109 key_press_event_callbacks_.erase(
1110 key_press_event_callbacks_.begin() + i);
1111 return;
1116 void RenderWidgetHostImpl::AddMouseEventCallback(
1117 const MouseEventCallback& callback) {
1118 mouse_event_callbacks_.push_back(callback);
1121 void RenderWidgetHostImpl::RemoveMouseEventCallback(
1122 const MouseEventCallback& callback) {
1123 for (size_t i = 0; i < mouse_event_callbacks_.size(); ++i) {
1124 if (mouse_event_callbacks_[i].Equals(callback)) {
1125 mouse_event_callbacks_.erase(mouse_event_callbacks_.begin() + i);
1126 return;
1131 void RenderWidgetHostImpl::GetWebScreenInfo(blink::WebScreenInfo* result) {
1132 TRACE_EVENT0("renderer_host", "RenderWidgetHostImpl::GetWebScreenInfo");
1133 if (view_)
1134 view_->GetScreenInfo(result);
1135 else
1136 RenderWidgetHostViewBase::GetDefaultScreenInfo(result);
1137 latency_tracker_.set_device_scale_factor(result->deviceScaleFactor);
1138 screen_info_out_of_date_ = false;
1141 const NativeWebKeyboardEvent*
1142 RenderWidgetHostImpl::GetLastKeyboardEvent() const {
1143 return input_router_->GetLastKeyboardEvent();
1146 void RenderWidgetHostImpl::NotifyScreenInfoChanged() {
1147 if (delegate_)
1148 delegate_->ScreenInfoChanged();
1150 // The resize message (which may not happen immediately) will carry with it
1151 // the screen info as well as the new size (if the screen has changed scale
1152 // factor).
1153 InvalidateScreenInfo();
1154 WasResized();
1157 void RenderWidgetHostImpl::InvalidateScreenInfo() {
1158 screen_info_out_of_date_ = true;
1159 screen_info_.reset();
1162 void RenderWidgetHostImpl::GetSnapshotFromBrowser(
1163 const base::Callback<void(const unsigned char*,size_t)> callback) {
1164 int id = next_browser_snapshot_id_++;
1165 pending_browser_snapshots_.insert(std::make_pair(id, callback));
1166 Send(new ViewMsg_ForceRedraw(GetRoutingID(), id));
1169 void RenderWidgetHostImpl::OnSelectionChanged(const base::string16& text,
1170 size_t offset,
1171 const gfx::Range& range) {
1172 if (view_)
1173 view_->SelectionChanged(text, offset, range);
1176 void RenderWidgetHostImpl::OnSelectionBoundsChanged(
1177 const ViewHostMsg_SelectionBounds_Params& params) {
1178 if (view_) {
1179 view_->SelectionBoundsChanged(params);
1183 void RenderWidgetHostImpl::UpdateVSyncParameters(base::TimeTicks timebase,
1184 base::TimeDelta interval) {
1185 Send(new ViewMsg_UpdateVSyncParameters(GetRoutingID(), timebase, interval));
1188 void RenderWidgetHostImpl::RendererExited(base::TerminationStatus status,
1189 int exit_code) {
1190 // Clearing this flag causes us to re-create the renderer when recovering
1191 // from a crashed renderer.
1192 renderer_initialized_ = false;
1194 waiting_for_screen_rects_ack_ = false;
1196 // Must reset these to ensure that keyboard events work with a new renderer.
1197 suppress_next_char_events_ = false;
1199 // Reset some fields in preparation for recovering from a crash.
1200 ResetSizeAndRepaintPendingFlags();
1201 current_size_.SetSize(0, 0);
1202 // After the renderer crashes, the view is destroyed and so the
1203 // RenderWidgetHost cannot track its visibility anymore. We assume such
1204 // RenderWidgetHost to be visible for the sake of internal accounting - be
1205 // careful about changing this - see http://crbug.com/401859.
1207 // We need to at least make sure that the RenderProcessHost is notified about
1208 // the |is_hidden_| change, so that the renderer will have correct visibility
1209 // set when respawned.
1210 if (is_hidden_) {
1211 process_->WidgetRestored();
1212 is_hidden_ = false;
1215 // Reset this to ensure the hung renderer mechanism is working properly.
1216 in_flight_event_count_ = 0;
1217 StopHangMonitorTimeout();
1219 if (view_) {
1220 GpuSurfaceTracker::Get()->SetSurfaceHandle(surface_id_,
1221 gfx::GLSurfaceHandle());
1222 view_->RenderProcessGone(status, exit_code);
1223 view_ = NULL; // The View should be deleted by RenderProcessGone.
1224 view_weak_.reset();
1227 // Reconstruct the input router to ensure that it has fresh state for a new
1228 // renderer. Otherwise it may be stuck waiting for the old renderer to ack an
1229 // event. (In particular, the above call to view_->RenderProcessGone will
1230 // destroy the aura window, which may dispatch a synthetic mouse move.)
1231 input_router_.reset(new InputRouterImpl(
1232 process_, this, this, routing_id_, GetInputRouterConfigForPlatform()));
1234 synthetic_gesture_controller_.reset();
1237 void RenderWidgetHostImpl::UpdateTextDirection(WebTextDirection direction) {
1238 text_direction_updated_ = true;
1239 text_direction_ = direction;
1242 void RenderWidgetHostImpl::CancelUpdateTextDirection() {
1243 if (text_direction_updated_)
1244 text_direction_canceled_ = true;
1247 void RenderWidgetHostImpl::NotifyTextDirection() {
1248 if (text_direction_updated_) {
1249 if (!text_direction_canceled_)
1250 Send(new ViewMsg_SetTextDirection(GetRoutingID(), text_direction_));
1251 text_direction_updated_ = false;
1252 text_direction_canceled_ = false;
1256 void RenderWidgetHostImpl::SetInputMethodActive(bool activate) {
1257 input_method_active_ = activate;
1258 Send(new ViewMsg_SetInputMethodActive(GetRoutingID(), activate));
1261 void RenderWidgetHostImpl::CandidateWindowShown() {
1262 Send(new ViewMsg_CandidateWindowShown(GetRoutingID()));
1265 void RenderWidgetHostImpl::CandidateWindowUpdated() {
1266 Send(new ViewMsg_CandidateWindowUpdated(GetRoutingID()));
1269 void RenderWidgetHostImpl::CandidateWindowHidden() {
1270 Send(new ViewMsg_CandidateWindowHidden(GetRoutingID()));
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::IsFullscreen() const {
1321 return false;
1324 void RenderWidgetHostImpl::SetAutoResize(bool enable,
1325 const gfx::Size& min_size,
1326 const gfx::Size& max_size) {
1327 auto_resize_enabled_ = enable;
1328 min_size_for_auto_resize_ = min_size;
1329 max_size_for_auto_resize_ = max_size;
1332 void RenderWidgetHostImpl::Cleanup() {
1333 if (view_) {
1334 view_->Destroy();
1335 view_ = nullptr;
1339 void RenderWidgetHostImpl::Destroy() {
1340 NotificationService::current()->Notify(
1341 NOTIFICATION_RENDER_WIDGET_HOST_DESTROYED,
1342 Source<RenderWidgetHost>(this),
1343 NotificationService::NoDetails());
1345 // Tell the view to die.
1346 // Note that in the process of the view shutting down, it can call a ton
1347 // of other messages on us. So if you do any other deinitialization here,
1348 // do it after this call to view_->Destroy().
1349 if (view_) {
1350 view_->Destroy();
1351 view_ = nullptr;
1354 delete this;
1357 void RenderWidgetHostImpl::RendererIsUnresponsive() {
1358 NotificationService::current()->Notify(
1359 NOTIFICATION_RENDER_WIDGET_HOST_HANG,
1360 Source<RenderWidgetHost>(this),
1361 NotificationService::NoDetails());
1362 is_unresponsive_ = true;
1363 NotifyRendererUnresponsive();
1366 void RenderWidgetHostImpl::RendererIsResponsive() {
1367 if (is_unresponsive_) {
1368 is_unresponsive_ = false;
1369 NotifyRendererResponsive();
1373 void RenderWidgetHostImpl::OnRenderViewReady() {
1374 SendScreenRects();
1375 WasResized();
1378 void RenderWidgetHostImpl::OnRenderProcessGone(int status, int exit_code) {
1379 // RenderFrameHost owns a RenderWidgetHost when it needs one, in which case
1380 // it handles destruction.
1381 if (!owned_by_render_frame_host_) {
1382 // TODO(evanm): This synchronously ends up calling "delete this".
1383 // Is that really what we want in response to this message? I'm matching
1384 // previous behavior of the code here.
1385 Destroy();
1386 } else {
1387 RendererExited(static_cast<base::TerminationStatus>(status), exit_code);
1391 void RenderWidgetHostImpl::OnClose() {
1392 Shutdown();
1395 void RenderWidgetHostImpl::OnSetTooltipText(
1396 const base::string16& tooltip_text,
1397 WebTextDirection text_direction_hint) {
1398 // First, add directionality marks around tooltip text if necessary.
1399 // A naive solution would be to simply always wrap the text. However, on
1400 // windows, Unicode directional embedding characters can't be displayed on
1401 // systems that lack RTL fonts and are instead displayed as empty squares.
1403 // To get around this we only wrap the string when we deem it necessary i.e.
1404 // when the locale direction is different than the tooltip direction hint.
1406 // Currently, we use element's directionality as the tooltip direction hint.
1407 // An alternate solution would be to set the overall directionality based on
1408 // trying to detect the directionality from the tooltip text rather than the
1409 // element direction. One could argue that would be a preferable solution
1410 // but we use the current approach to match Fx & IE's behavior.
1411 base::string16 wrapped_tooltip_text = tooltip_text;
1412 if (!tooltip_text.empty()) {
1413 if (text_direction_hint == blink::WebTextDirectionLeftToRight) {
1414 // Force the tooltip to have LTR directionality.
1415 wrapped_tooltip_text =
1416 base::i18n::GetDisplayStringInLTRDirectionality(wrapped_tooltip_text);
1417 } else if (text_direction_hint == blink::WebTextDirectionRightToLeft &&
1418 !base::i18n::IsRTL()) {
1419 // Force the tooltip to have RTL directionality.
1420 base::i18n::WrapStringWithRTLFormatting(&wrapped_tooltip_text);
1423 if (GetView())
1424 view_->SetTooltipText(wrapped_tooltip_text);
1427 void RenderWidgetHostImpl::OnUpdateScreenRectsAck() {
1428 waiting_for_screen_rects_ack_ = false;
1429 if (!view_)
1430 return;
1432 if (view_->GetViewBounds() == last_view_screen_rect_ &&
1433 view_->GetBoundsInRootWindow() == last_window_screen_rect_) {
1434 return;
1437 SendScreenRects();
1440 void RenderWidgetHostImpl::OnRequestMove(const gfx::Rect& pos) {
1441 if (view_) {
1442 view_->SetBounds(pos);
1443 Send(new ViewMsg_Move_ACK(routing_id_));
1447 bool RenderWidgetHostImpl::OnSwapCompositorFrame(
1448 const IPC::Message& message) {
1449 // This trace event is used in
1450 // chrome/browser/extensions/api/cast_streaming/performance_test.cc
1451 TRACE_EVENT0("test_fps,benchmark", "OnSwapCompositorFrame");
1452 ViewHostMsg_SwapCompositorFrame::Param param;
1453 if (!ViewHostMsg_SwapCompositorFrame::Read(&message, &param))
1454 return false;
1455 scoped_ptr<cc::CompositorFrame> frame(new cc::CompositorFrame);
1456 uint32 output_surface_id = get<0>(param);
1457 get<1>(param).AssignTo(frame.get());
1458 std::vector<IPC::Message> messages_to_deliver_with_frame;
1459 messages_to_deliver_with_frame.swap(get<2>(param));
1461 latency_tracker_.OnSwapCompositorFrame(&frame->metadata.latency_info);
1463 input_router_->OnViewUpdated(
1464 GetInputRouterViewFlagsFromCompositorFrameMetadata(frame->metadata));
1466 if (touch_emulator_) {
1467 touch_emulator_->SetDoubleTapSupportForPageEnabled(
1468 !IsMobileOptimizedFrame(frame->metadata));
1471 if (view_) {
1472 view_->OnSwapCompositorFrame(output_surface_id, frame.Pass());
1473 view_->DidReceiveRendererFrame();
1474 } else {
1475 cc::CompositorFrameAck ack;
1476 if (frame->gl_frame_data) {
1477 ack.gl_frame_data = frame->gl_frame_data.Pass();
1478 ack.gl_frame_data->sync_point = 0;
1479 } else if (frame->delegated_frame_data) {
1480 cc::TransferableResource::ReturnResources(
1481 frame->delegated_frame_data->resource_list,
1482 &ack.resources);
1483 } else if (frame->software_frame_data) {
1484 ack.last_software_frame_id = frame->software_frame_data->id;
1486 SendSwapCompositorFrameAck(routing_id_, output_surface_id,
1487 process_->GetID(), ack);
1490 RenderProcessHost* rph = GetProcess();
1491 for (std::vector<IPC::Message>::const_iterator i =
1492 messages_to_deliver_with_frame.begin();
1493 i != messages_to_deliver_with_frame.end();
1494 ++i) {
1495 rph->OnMessageReceived(*i);
1496 if (i->dispatch_error())
1497 rph->OnBadMessageReceived(*i);
1499 messages_to_deliver_with_frame.clear();
1501 return true;
1504 void RenderWidgetHostImpl::OnUpdateRect(
1505 const ViewHostMsg_UpdateRect_Params& params) {
1506 TRACE_EVENT0("renderer_host", "RenderWidgetHostImpl::OnUpdateRect");
1507 TimeTicks paint_start = TimeTicks::Now();
1509 // Update our knowledge of the RenderWidget's size.
1510 current_size_ = params.view_size;
1512 bool is_resize_ack =
1513 ViewHostMsg_UpdateRect_Flags::is_resize_ack(params.flags);
1515 // resize_ack_pending_ needs to be cleared before we call DidPaintRect, since
1516 // that will end up reaching GetBackingStore.
1517 if (is_resize_ack) {
1518 DCHECK(!g_check_for_pending_resize_ack || resize_ack_pending_);
1519 resize_ack_pending_ = false;
1522 bool is_repaint_ack =
1523 ViewHostMsg_UpdateRect_Flags::is_repaint_ack(params.flags);
1524 if (is_repaint_ack) {
1525 DCHECK(repaint_ack_pending_);
1526 TRACE_EVENT_ASYNC_END0(
1527 "renderer_host", "RenderWidgetHostImpl::repaint_ack_pending_", this);
1528 repaint_ack_pending_ = false;
1529 TimeDelta delta = TimeTicks::Now() - repaint_start_time_;
1530 UMA_HISTOGRAM_TIMES("MPArch.RWH_RepaintDelta", delta);
1533 DCHECK(!params.view_size.IsEmpty());
1535 DidUpdateBackingStore(params, paint_start);
1537 if (auto_resize_enabled_) {
1538 bool post_callback = new_auto_size_.IsEmpty();
1539 new_auto_size_ = params.view_size;
1540 if (post_callback) {
1541 base::MessageLoop::current()->PostTask(
1542 FROM_HERE,
1543 base::Bind(&RenderWidgetHostImpl::DelayedAutoResized,
1544 weak_factory_.GetWeakPtr()));
1548 // Log the time delta for processing a paint message. On platforms that don't
1549 // support asynchronous painting, this is equivalent to
1550 // MPArch.RWH_TotalPaintTime.
1551 TimeDelta delta = TimeTicks::Now() - paint_start;
1552 UMA_HISTOGRAM_TIMES("MPArch.RWH_OnMsgUpdateRect", delta);
1555 void RenderWidgetHostImpl::DidUpdateBackingStore(
1556 const ViewHostMsg_UpdateRect_Params& params,
1557 const TimeTicks& paint_start) {
1558 TRACE_EVENT0("renderer_host", "RenderWidgetHostImpl::DidUpdateBackingStore");
1559 TimeTicks update_start = TimeTicks::Now();
1561 // Move the plugins if the view hasn't already been destroyed. Plugin moves
1562 // will not be re-issued, so must move them now, regardless of whether we
1563 // paint or not. MovePluginWindows attempts to move the plugin windows and
1564 // in the process could dispatch other window messages which could cause the
1565 // view to be destroyed.
1566 if (view_)
1567 view_->MovePluginWindows(params.plugin_window_moves);
1569 NotificationService::current()->Notify(
1570 NOTIFICATION_RENDER_WIDGET_HOST_DID_UPDATE_BACKING_STORE,
1571 Source<RenderWidgetHost>(this),
1572 NotificationService::NoDetails());
1574 // We don't need to update the view if the view is hidden. We must do this
1575 // early return after the ACK is sent, however, or the renderer will not send
1576 // us more data.
1577 if (is_hidden_)
1578 return;
1580 // If we got a resize ack, then perhaps we have another resize to send?
1581 bool is_resize_ack =
1582 ViewHostMsg_UpdateRect_Flags::is_resize_ack(params.flags);
1583 if (is_resize_ack)
1584 WasResized();
1586 // Log the time delta for processing a paint message.
1587 TimeTicks now = TimeTicks::Now();
1588 TimeDelta delta = now - update_start;
1589 UMA_HISTOGRAM_TIMES("MPArch.RWH_DidUpdateBackingStore", delta);
1592 void RenderWidgetHostImpl::OnQueueSyntheticGesture(
1593 const SyntheticGesturePacket& gesture_packet) {
1594 // Only allow untrustworthy gestures if explicitly enabled.
1595 if (!base::CommandLine::ForCurrentProcess()->HasSwitch(
1596 cc::switches::kEnableGpuBenchmarking)) {
1597 bad_message::ReceivedBadMessage(GetProcess(),
1598 bad_message::RWH_SYNTHETIC_GESTURE);
1599 return;
1602 QueueSyntheticGesture(
1603 SyntheticGesture::Create(*gesture_packet.gesture_params()),
1604 base::Bind(&RenderWidgetHostImpl::OnSyntheticGestureCompleted,
1605 weak_factory_.GetWeakPtr()));
1608 void RenderWidgetHostImpl::OnFocus() {
1609 // Only RenderViewHost can deal with that message.
1610 bad_message::ReceivedBadMessage(GetProcess(), bad_message::RWH_FOCUS);
1613 void RenderWidgetHostImpl::OnBlur() {
1614 // Only RenderViewHost can deal with that message.
1615 bad_message::ReceivedBadMessage(GetProcess(), bad_message::RWH_BLUR);
1618 void RenderWidgetHostImpl::OnSetCursor(const WebCursor& cursor) {
1619 SetCursor(cursor);
1622 void RenderWidgetHostImpl::SetTouchEventEmulationEnabled(
1623 bool enabled, ui::GestureProviderConfigType config_type) {
1624 if (enabled) {
1625 if (!touch_emulator_)
1626 touch_emulator_.reset(new TouchEmulator(this));
1627 touch_emulator_->Enable(config_type);
1628 } else {
1629 if (touch_emulator_)
1630 touch_emulator_->Disable();
1634 void RenderWidgetHostImpl::OnTextInputTypeChanged(
1635 ui::TextInputType type,
1636 ui::TextInputMode input_mode,
1637 bool can_compose_inline,
1638 int flags) {
1639 if (view_)
1640 view_->TextInputTypeChanged(type, input_mode, can_compose_inline, flags);
1643 void RenderWidgetHostImpl::OnImeCompositionRangeChanged(
1644 const gfx::Range& range,
1645 const std::vector<gfx::Rect>& character_bounds) {
1646 if (view_)
1647 view_->ImeCompositionRangeChanged(range, character_bounds);
1650 void RenderWidgetHostImpl::OnImeCancelComposition() {
1651 if (view_)
1652 view_->ImeCancelComposition();
1655 void RenderWidgetHostImpl::OnLockMouse(bool user_gesture,
1656 bool last_unlocked_by_target,
1657 bool privileged) {
1659 if (pending_mouse_lock_request_) {
1660 Send(new ViewMsg_LockMouse_ACK(routing_id_, false));
1661 return;
1662 } else if (IsMouseLocked()) {
1663 Send(new ViewMsg_LockMouse_ACK(routing_id_, true));
1664 return;
1667 pending_mouse_lock_request_ = true;
1668 if (privileged && allow_privileged_mouse_lock_) {
1669 // Directly approve to lock the mouse.
1670 GotResponseToLockMouseRequest(true);
1671 } else {
1672 RequestToLockMouse(user_gesture, last_unlocked_by_target);
1676 void RenderWidgetHostImpl::OnUnlockMouse() {
1677 RejectMouseLockOrUnlockIfNecessary();
1680 void RenderWidgetHostImpl::OnShowDisambiguationPopup(
1681 const gfx::Rect& rect_pixels,
1682 const gfx::Size& size,
1683 const cc::SharedBitmapId& id) {
1684 DCHECK(!rect_pixels.IsEmpty());
1685 DCHECK(!size.IsEmpty());
1687 scoped_ptr<cc::SharedBitmap> bitmap =
1688 HostSharedBitmapManager::current()->GetSharedBitmapFromId(size, id);
1689 if (!bitmap) {
1690 bad_message::ReceivedBadMessage(GetProcess(),
1691 bad_message::RWH_SHARED_BITMAP);
1692 return;
1695 DCHECK(bitmap->pixels());
1697 SkImageInfo info = SkImageInfo::MakeN32Premul(size.width(), size.height());
1698 SkBitmap zoomed_bitmap;
1699 zoomed_bitmap.installPixels(info, bitmap->pixels(), info.minRowBytes());
1701 // Note that |rect| is in coordinates of pixels relative to the window origin.
1702 // Aura-based systems will want to convert this to DIPs.
1703 if (view_)
1704 view_->ShowDisambiguationPopup(rect_pixels, zoomed_bitmap);
1706 // It is assumed that the disambiguation popup will make a copy of the
1707 // provided zoomed image, so we delete this one.
1708 zoomed_bitmap.setPixels(0);
1709 Send(new ViewMsg_ReleaseDisambiguationPopupBitmap(GetRoutingID(), id));
1712 #if defined(OS_WIN)
1713 void RenderWidgetHostImpl::OnWindowlessPluginDummyWindowCreated(
1714 gfx::NativeViewId dummy_activation_window) {
1715 HWND hwnd = reinterpret_cast<HWND>(dummy_activation_window);
1717 // This may happen as a result of a race condition when the plugin is going
1718 // away.
1719 wchar_t window_title[MAX_PATH + 1] = {0};
1720 if (!IsWindow(hwnd) ||
1721 !GetWindowText(hwnd, window_title, arraysize(window_title)) ||
1722 lstrcmpiW(window_title, kDummyActivationWindowName) != 0) {
1723 return;
1726 #if defined(USE_AURA)
1727 SetParent(hwnd,
1728 reinterpret_cast<HWND>(view_->GetParentForWindowlessPlugin()));
1729 #else
1730 SetParent(hwnd, reinterpret_cast<HWND>(GetNativeViewId()));
1731 #endif
1732 dummy_windows_for_activation_.push_back(hwnd);
1735 void RenderWidgetHostImpl::OnWindowlessPluginDummyWindowDestroyed(
1736 gfx::NativeViewId dummy_activation_window) {
1737 HWND hwnd = reinterpret_cast<HWND>(dummy_activation_window);
1738 std::list<HWND>::iterator i = dummy_windows_for_activation_.begin();
1739 for (; i != dummy_windows_for_activation_.end(); ++i) {
1740 if ((*i) == hwnd) {
1741 dummy_windows_for_activation_.erase(i);
1742 return;
1745 NOTREACHED() << "Unknown dummy window";
1747 #endif
1749 void RenderWidgetHostImpl::SetIgnoreInputEvents(bool ignore_input_events) {
1750 ignore_input_events_ = ignore_input_events;
1753 bool RenderWidgetHostImpl::KeyPressListenersHandleEvent(
1754 const NativeWebKeyboardEvent& event) {
1755 if (event.skip_in_browser || event.type != WebKeyboardEvent::RawKeyDown)
1756 return false;
1758 for (size_t i = 0; i < key_press_event_callbacks_.size(); i++) {
1759 size_t original_size = key_press_event_callbacks_.size();
1760 if (key_press_event_callbacks_[i].Run(event))
1761 return true;
1763 // Check whether the callback that just ran removed itself, in which case
1764 // the iterator needs to be decremented to properly account for the removal.
1765 size_t current_size = key_press_event_callbacks_.size();
1766 if (current_size != original_size) {
1767 DCHECK_EQ(original_size - 1, current_size);
1768 --i;
1772 return false;
1775 InputEventAckState RenderWidgetHostImpl::FilterInputEvent(
1776 const blink::WebInputEvent& event, const ui::LatencyInfo& latency_info) {
1777 // Don't ignore touch cancel events, since they may be sent while input
1778 // events are being ignored in order to keep the renderer from getting
1779 // confused about how many touches are active.
1780 if (IgnoreInputEvents() && event.type != WebInputEvent::TouchCancel)
1781 return INPUT_EVENT_ACK_STATE_NO_CONSUMER_EXISTS;
1783 if (!process_->HasConnection())
1784 return INPUT_EVENT_ACK_STATE_UNKNOWN;
1786 if (event.type == WebInputEvent::MouseDown)
1787 OnUserGesture();
1789 return view_ ? view_->FilterInputEvent(event)
1790 : INPUT_EVENT_ACK_STATE_NOT_CONSUMED;
1793 void RenderWidgetHostImpl::IncrementInFlightEventCount() {
1794 increment_in_flight_event_count();
1795 if (!is_hidden_)
1796 StartHangMonitorTimeout(hung_renderer_delay_);
1799 void RenderWidgetHostImpl::DecrementInFlightEventCount() {
1800 if (decrement_in_flight_event_count() <= 0) {
1801 // Cancel pending hung renderer checks since the renderer is responsive.
1802 StopHangMonitorTimeout();
1803 } else {
1804 // The renderer is responsive, but there are in-flight events to wait for.
1805 if (!is_hidden_)
1806 RestartHangMonitorTimeout();
1810 void RenderWidgetHostImpl::OnHasTouchEventHandlers(bool has_handlers) {
1811 has_touch_handler_ = has_handlers;
1814 void RenderWidgetHostImpl::DidFlush() {
1815 if (synthetic_gesture_controller_)
1816 synthetic_gesture_controller_->OnDidFlushInput();
1819 void RenderWidgetHostImpl::DidOverscroll(const DidOverscrollParams& params) {
1820 if (view_)
1821 view_->DidOverscroll(params);
1824 void RenderWidgetHostImpl::DidStopFlinging() {
1825 if (view_)
1826 view_->DidStopFlinging();
1829 void RenderWidgetHostImpl::OnKeyboardEventAck(
1830 const NativeWebKeyboardEvent& event,
1831 InputEventAckState ack_result) {
1832 #if defined(OS_MACOSX)
1833 if (!is_hidden() && view_ && view_->PostProcessEventForPluginIme(event))
1834 return;
1835 #endif
1837 // We only send unprocessed key event upwards if we are not hidden,
1838 // because the user has moved away from us and no longer expect any effect
1839 // of this key event.
1840 const bool processed = (INPUT_EVENT_ACK_STATE_CONSUMED == ack_result);
1841 if (delegate_ && !processed && !is_hidden() && !event.skip_in_browser) {
1842 delegate_->HandleKeyboardEvent(event);
1844 // WARNING: This RenderWidgetHostImpl can be deallocated at this point
1845 // (i.e. in the case of Ctrl+W, where the call to
1846 // HandleKeyboardEvent destroys this RenderWidgetHostImpl).
1850 void RenderWidgetHostImpl::OnWheelEventAck(
1851 const MouseWheelEventWithLatencyInfo& wheel_event,
1852 InputEventAckState ack_result) {
1853 latency_tracker_.OnInputEventAck(wheel_event.event, &wheel_event.latency);
1855 if (!is_hidden() && view_) {
1856 if (ack_result != INPUT_EVENT_ACK_STATE_CONSUMED &&
1857 delegate_->HandleWheelEvent(wheel_event.event)) {
1858 ack_result = INPUT_EVENT_ACK_STATE_CONSUMED;
1860 view_->WheelEventAck(wheel_event.event, ack_result);
1864 void RenderWidgetHostImpl::OnGestureEventAck(
1865 const GestureEventWithLatencyInfo& event,
1866 InputEventAckState ack_result) {
1867 latency_tracker_.OnInputEventAck(event.event, &event.latency);
1869 if (view_)
1870 view_->GestureEventAck(event.event, ack_result);
1873 void RenderWidgetHostImpl::OnTouchEventAck(
1874 const TouchEventWithLatencyInfo& event,
1875 InputEventAckState ack_result) {
1876 latency_tracker_.OnInputEventAck(event.event, &event.latency);
1878 if (touch_emulator_ &&
1879 touch_emulator_->HandleTouchEventAck(event.event, ack_result)) {
1880 return;
1883 if (view_)
1884 view_->ProcessAckedTouchEvent(event, ack_result);
1887 void RenderWidgetHostImpl::OnUnexpectedEventAck(UnexpectedEventAckType type) {
1888 if (type == BAD_ACK_MESSAGE) {
1889 bad_message::ReceivedBadMessage(process_, bad_message::RWH_BAD_ACK_MESSAGE);
1890 } else if (type == UNEXPECTED_EVENT_TYPE) {
1891 suppress_next_char_events_ = false;
1895 void RenderWidgetHostImpl::OnSyntheticGestureCompleted(
1896 SyntheticGesture::Result result) {
1897 Send(new InputMsg_SyntheticGestureCompleted(GetRoutingID()));
1900 bool RenderWidgetHostImpl::IgnoreInputEvents() const {
1901 return ignore_input_events_ || process_->IgnoreInputEvents();
1904 void RenderWidgetHostImpl::StartUserGesture() {
1905 OnUserGesture();
1908 void RenderWidgetHostImpl::SetBackgroundOpaque(bool opaque) {
1909 Send(new ViewMsg_SetBackgroundOpaque(GetRoutingID(), opaque));
1912 void RenderWidgetHostImpl::SetEditCommandsForNextKeyEvent(
1913 const std::vector<EditCommand>& commands) {
1914 Send(new InputMsg_SetEditCommandsForNextKeyEvent(GetRoutingID(), commands));
1917 void RenderWidgetHostImpl::ExecuteEditCommand(const std::string& command,
1918 const std::string& value) {
1919 Send(new InputMsg_ExecuteEditCommand(GetRoutingID(), command, value));
1922 void RenderWidgetHostImpl::ScrollFocusedEditableNodeIntoRect(
1923 const gfx::Rect& rect) {
1924 Send(new InputMsg_ScrollFocusedEditableNodeIntoRect(GetRoutingID(), rect));
1927 void RenderWidgetHostImpl::MoveCaret(const gfx::Point& point) {
1928 Send(new InputMsg_MoveCaret(GetRoutingID(), point));
1931 bool RenderWidgetHostImpl::GotResponseToLockMouseRequest(bool allowed) {
1932 if (!allowed) {
1933 RejectMouseLockOrUnlockIfNecessary();
1934 return false;
1935 } else {
1936 if (!pending_mouse_lock_request_) {
1937 // This is possible, e.g., the plugin sends us an unlock request before
1938 // the user allows to lock to mouse.
1939 return false;
1942 pending_mouse_lock_request_ = false;
1943 if (!view_ || !view_->HasFocus()|| !view_->LockMouse()) {
1944 Send(new ViewMsg_LockMouse_ACK(routing_id_, false));
1945 return false;
1946 } else {
1947 Send(new ViewMsg_LockMouse_ACK(routing_id_, true));
1948 return true;
1953 // static
1954 void RenderWidgetHostImpl::SendSwapCompositorFrameAck(
1955 int32 route_id,
1956 uint32 output_surface_id,
1957 int renderer_host_id,
1958 const cc::CompositorFrameAck& ack) {
1959 RenderProcessHost* host = RenderProcessHost::FromID(renderer_host_id);
1960 if (!host)
1961 return;
1962 host->Send(new ViewMsg_SwapCompositorFrameAck(
1963 route_id, output_surface_id, ack));
1966 // static
1967 void RenderWidgetHostImpl::SendReclaimCompositorResources(
1968 int32 route_id,
1969 uint32 output_surface_id,
1970 int renderer_host_id,
1971 const cc::CompositorFrameAck& ack) {
1972 RenderProcessHost* host = RenderProcessHost::FromID(renderer_host_id);
1973 if (!host)
1974 return;
1975 host->Send(
1976 new ViewMsg_ReclaimCompositorResources(route_id, output_surface_id, ack));
1979 void RenderWidgetHostImpl::DelayedAutoResized() {
1980 gfx::Size new_size = new_auto_size_;
1981 // Clear the new_auto_size_ since the empty value is used as a flag to
1982 // indicate that no callback is in progress (i.e. without this line
1983 // DelayedAutoResized will not get called again).
1984 new_auto_size_.SetSize(0, 0);
1985 if (!auto_resize_enabled_)
1986 return;
1988 OnRenderAutoResized(new_size);
1991 void RenderWidgetHostImpl::DetachDelegate() {
1992 delegate_ = NULL;
1995 void RenderWidgetHostImpl::FrameSwapped(const ui::LatencyInfo& latency_info) {
1996 ui::LatencyInfo::LatencyComponent window_snapshot_component;
1997 if (latency_info.FindLatency(ui::WINDOW_SNAPSHOT_FRAME_NUMBER_COMPONENT,
1998 GetLatencyComponentId(),
1999 &window_snapshot_component)) {
2000 int sequence_number = static_cast<int>(
2001 window_snapshot_component.sequence_number);
2002 #if defined(OS_MACOSX)
2003 // On Mac, when using CoreAnmation, there is a delay between when content
2004 // is drawn to the screen, and when the snapshot will actually pick up
2005 // that content. Insert a manual delay of 1/6th of a second (to simulate
2006 // 10 frames at 60 fps) before actually taking the snapshot.
2007 base::MessageLoop::current()->PostDelayedTask(
2008 FROM_HERE,
2009 base::Bind(&RenderWidgetHostImpl::WindowSnapshotReachedScreen,
2010 weak_factory_.GetWeakPtr(),
2011 sequence_number),
2012 base::TimeDelta::FromSecondsD(1. / 6));
2013 #else
2014 WindowSnapshotReachedScreen(sequence_number);
2015 #endif
2018 latency_tracker_.OnFrameSwapped(latency_info);
2021 void RenderWidgetHostImpl::DidReceiveRendererFrame() {
2022 view_->DidReceiveRendererFrame();
2025 void RenderWidgetHostImpl::WindowSnapshotReachedScreen(int snapshot_id) {
2026 DCHECK(base::MessageLoopForUI::IsCurrent());
2028 gfx::Rect view_bounds = GetView()->GetViewBounds();
2029 gfx::Rect snapshot_bounds(view_bounds.size());
2031 std::vector<unsigned char> png;
2032 if (ui::GrabViewSnapshot(
2033 GetView()->GetNativeView(), &png, snapshot_bounds)) {
2034 OnSnapshotDataReceived(snapshot_id, &png.front(), png.size());
2035 return;
2038 ui::GrabViewSnapshotAsync(
2039 GetView()->GetNativeView(),
2040 snapshot_bounds,
2041 base::ThreadTaskRunnerHandle::Get(),
2042 base::Bind(&RenderWidgetHostImpl::OnSnapshotDataReceivedAsync,
2043 weak_factory_.GetWeakPtr(),
2044 snapshot_id));
2047 void RenderWidgetHostImpl::OnSnapshotDataReceived(int snapshot_id,
2048 const unsigned char* data,
2049 size_t size) {
2050 // Any pending snapshots with a lower ID than the one received are considered
2051 // to be implicitly complete, and returned the same snapshot data.
2052 PendingSnapshotMap::iterator it = pending_browser_snapshots_.begin();
2053 while(it != pending_browser_snapshots_.end()) {
2054 if (it->first <= snapshot_id) {
2055 it->second.Run(data, size);
2056 pending_browser_snapshots_.erase(it++);
2057 } else {
2058 ++it;
2063 void RenderWidgetHostImpl::OnSnapshotDataReceivedAsync(
2064 int snapshot_id,
2065 scoped_refptr<base::RefCountedBytes> png_data) {
2066 if (png_data.get())
2067 OnSnapshotDataReceived(snapshot_id, png_data->front(), png_data->size());
2068 else
2069 OnSnapshotDataReceived(snapshot_id, NULL, 0);
2072 // static
2073 void RenderWidgetHostImpl::CompositorFrameDrawn(
2074 const std::vector<ui::LatencyInfo>& latency_info) {
2075 for (size_t i = 0; i < latency_info.size(); i++) {
2076 std::set<RenderWidgetHostImpl*> rwhi_set;
2077 for (ui::LatencyInfo::LatencyMap::const_iterator b =
2078 latency_info[i].latency_components.begin();
2079 b != latency_info[i].latency_components.end();
2080 ++b) {
2081 if (b->first.first == ui::INPUT_EVENT_LATENCY_BEGIN_RWH_COMPONENT ||
2082 b->first.first == ui::WINDOW_SNAPSHOT_FRAME_NUMBER_COMPONENT ||
2083 b->first.first == ui::TAB_SHOW_COMPONENT) {
2084 // Matches with GetLatencyComponentId
2085 int routing_id = b->first.second & 0xffffffff;
2086 int process_id = (b->first.second >> 32) & 0xffffffff;
2087 RenderWidgetHost* rwh =
2088 RenderWidgetHost::FromID(process_id, routing_id);
2089 if (!rwh) {
2090 continue;
2092 RenderWidgetHostImpl* rwhi = RenderWidgetHostImpl::From(rwh);
2093 if (rwhi_set.insert(rwhi).second)
2094 rwhi->FrameSwapped(latency_info[i]);
2100 BrowserAccessibilityManager*
2101 RenderWidgetHostImpl::GetRootBrowserAccessibilityManager() {
2102 return delegate_ ? delegate_->GetRootBrowserAccessibilityManager() : NULL;
2105 BrowserAccessibilityManager*
2106 RenderWidgetHostImpl::GetOrCreateRootBrowserAccessibilityManager() {
2107 return delegate_ ?
2108 delegate_->GetOrCreateRootBrowserAccessibilityManager() : NULL;
2111 base::TimeDelta RenderWidgetHostImpl::GetEstimatedBrowserCompositeTime() const {
2112 return latency_tracker_.GetEstimatedBrowserCompositeTime();
2115 #if defined(OS_WIN)
2116 gfx::NativeViewAccessible
2117 RenderWidgetHostImpl::GetParentNativeViewAccessible() {
2118 return delegate_ ? delegate_->GetParentNativeViewAccessible() : NULL;
2120 #endif
2122 SkColorType RenderWidgetHostImpl::PreferredReadbackFormat() {
2123 if (view_)
2124 return view_->PreferredReadbackFormat();
2125 return kN32_SkColorType;
2128 } // namespace content