Make USB permissions work in the new permission message system
[chromium-blink-merge.git] / content / browser / renderer_host / render_widget_host_impl.cc
blob8ea74c799e277febfa1469daefd545ccca0787be
1 // Copyright (c) 2012 The Chromium Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
5 #include "content/browser/renderer_host/render_widget_host_impl.h"
7 #include <math.h>
8 #include <set>
9 #include <utility>
11 #include "base/auto_reset.h"
12 #include "base/bind.h"
13 #include "base/command_line.h"
14 #include "base/containers/hash_tables.h"
15 #include "base/i18n/rtl.h"
16 #include "base/lazy_instance.h"
17 #include "base/location.h"
18 #include "base/metrics/field_trial.h"
19 #include "base/metrics/histogram.h"
20 #include "base/single_thread_task_runner.h"
21 #include "base/strings/string_number_conversions.h"
22 #include "base/strings/utf_string_conversions.h"
23 #include "base/thread_task_runner_handle.h"
24 #include "base/trace_event/trace_event.h"
25 #include "cc/base/switches.h"
26 #include "cc/output/compositor_frame.h"
27 #include "cc/output/compositor_frame_ack.h"
28 #include "content/browser/accessibility/accessibility_mode_helper.h"
29 #include "content/browser/accessibility/browser_accessibility_state_impl.h"
30 #include "content/browser/bad_message.h"
31 #include "content/browser/browser_plugin/browser_plugin_guest.h"
32 #include "content/browser/gpu/compositor_util.h"
33 #include "content/browser/gpu/gpu_process_host.h"
34 #include "content/browser/gpu/gpu_process_host_ui_shim.h"
35 #include "content/browser/gpu/gpu_surface_tracker.h"
36 #include "content/browser/renderer_host/dip_util.h"
37 #include "content/browser/renderer_host/frame_metadata_util.h"
38 #include "content/browser/renderer_host/input/input_router_config_helper.h"
39 #include "content/browser/renderer_host/input/input_router_impl.h"
40 #include "content/browser/renderer_host/input/synthetic_gesture.h"
41 #include "content/browser/renderer_host/input/synthetic_gesture_controller.h"
42 #include "content/browser/renderer_host/input/synthetic_gesture_target.h"
43 #include "content/browser/renderer_host/input/timeout_monitor.h"
44 #include "content/browser/renderer_host/input/touch_emulator.h"
45 #include "content/browser/renderer_host/render_process_host_impl.h"
46 #include "content/browser/renderer_host/render_view_host_impl.h"
47 #include "content/browser/renderer_host/render_widget_helper.h"
48 #include "content/browser/renderer_host/render_widget_host_delegate.h"
49 #include "content/browser/renderer_host/render_widget_host_view_base.h"
50 #include "content/browser/renderer_host/render_widget_resize_helper.h"
51 #include "content/common/content_constants_internal.h"
52 #include "content/common/cursors/webcursor.h"
53 #include "content/common/frame_messages.h"
54 #include "content/common/gpu/gpu_messages.h"
55 #include "content/common/host_shared_bitmap_manager.h"
56 #include "content/common/input_messages.h"
57 #include "content/common/view_messages.h"
58 #include "content/public/browser/native_web_keyboard_event.h"
59 #include "content/public/browser/notification_service.h"
60 #include "content/public/browser/notification_types.h"
61 #include "content/public/browser/render_widget_host_iterator.h"
62 #include "content/public/common/content_constants.h"
63 #include "content/public/common/content_switches.h"
64 #include "content/public/common/result_codes.h"
65 #include "content/public/common/web_preferences.h"
66 #include "gpu/GLES2/gl2extchromium.h"
67 #include "gpu/command_buffer/service/gpu_switches.h"
68 #include "skia/ext/image_operations.h"
69 #include "skia/ext/platform_canvas.h"
70 #include "third_party/WebKit/public/web/WebCompositionUnderline.h"
71 #include "ui/events/event.h"
72 #include "ui/events/keycodes/keyboard_codes.h"
73 #include "ui/gfx/geometry/size_conversions.h"
74 #include "ui/gfx/geometry/vector2d_conversions.h"
75 #include "ui/gfx/skbitmap_operations.h"
76 #include "ui/snapshot/snapshot.h"
78 #if defined(OS_WIN)
79 #include "content/common/plugin_constants_win.h"
80 #endif
82 using base::Time;
83 using base::TimeDelta;
84 using base::TimeTicks;
85 using blink::WebGestureEvent;
86 using blink::WebInputEvent;
87 using blink::WebKeyboardEvent;
88 using blink::WebMouseEvent;
89 using blink::WebMouseWheelEvent;
90 using blink::WebTextDirection;
92 namespace content {
93 namespace {
95 bool g_check_for_pending_resize_ack = true;
97 typedef std::pair<int32, int32> RenderWidgetHostID;
98 typedef base::hash_map<RenderWidgetHostID, RenderWidgetHostImpl*>
99 RoutingIDWidgetMap;
100 base::LazyInstance<RoutingIDWidgetMap> g_routing_id_widget_map =
101 LAZY_INSTANCE_INITIALIZER;
103 // Implements the RenderWidgetHostIterator interface. It keeps a list of
104 // RenderWidgetHosts, and makes sure it returns a live RenderWidgetHost at each
105 // iteration (or NULL if there isn't any left).
106 class RenderWidgetHostIteratorImpl : public RenderWidgetHostIterator {
107 public:
108 RenderWidgetHostIteratorImpl()
109 : current_index_(0) {
112 ~RenderWidgetHostIteratorImpl() override {}
114 void Add(RenderWidgetHost* host) {
115 hosts_.push_back(RenderWidgetHostID(host->GetProcess()->GetID(),
116 host->GetRoutingID()));
119 // RenderWidgetHostIterator:
120 RenderWidgetHost* GetNextHost() override {
121 RenderWidgetHost* host = NULL;
122 while (current_index_ < hosts_.size() && !host) {
123 RenderWidgetHostID id = hosts_[current_index_];
124 host = RenderWidgetHost::FromID(id.first, id.second);
125 ++current_index_;
127 return host;
130 private:
131 std::vector<RenderWidgetHostID> hosts_;
132 size_t current_index_;
134 DISALLOW_COPY_AND_ASSIGN(RenderWidgetHostIteratorImpl);
137 } // namespace
139 ///////////////////////////////////////////////////////////////////////////////
140 // RenderWidgetHostImpl
142 RenderWidgetHostImpl::RenderWidgetHostImpl(RenderWidgetHostDelegate* delegate,
143 RenderProcessHost* process,
144 int routing_id,
145 bool hidden)
146 : view_(NULL),
147 hung_renderer_delay_(
148 base::TimeDelta::FromMilliseconds(kHungRendererDelayMs)),
149 renderer_initialized_(false),
150 delegate_(delegate),
151 process_(process),
152 routing_id_(routing_id),
153 surface_id_(0),
154 is_loading_(false),
155 is_hidden_(hidden),
156 repaint_ack_pending_(false),
157 resize_ack_pending_(false),
158 auto_resize_enabled_(false),
159 waiting_for_screen_rects_ack_(false),
160 needs_repainting_on_restore_(false),
161 is_unresponsive_(false),
162 in_flight_event_count_(0),
163 in_get_backing_store_(false),
164 ignore_input_events_(false),
165 text_direction_updated_(false),
166 text_direction_(blink::WebTextDirectionLeftToRight),
167 text_direction_canceled_(false),
168 suppress_next_char_events_(false),
169 pending_mouse_lock_request_(false),
170 allow_privileged_mouse_lock_(false),
171 has_touch_handler_(false),
172 next_browser_snapshot_id_(1),
173 owned_by_render_frame_host_(false),
174 is_focused_(false),
175 weak_factory_(this) {
176 CHECK(delegate_);
177 if (routing_id_ == MSG_ROUTING_NONE) {
178 routing_id_ = process_->GetNextRoutingID();
179 surface_id_ = GpuSurfaceTracker::Get()->AddSurfaceForRenderer(
180 process_->GetID(),
181 routing_id_);
182 } else {
183 // TODO(piman): This is a O(N) lookup, where we could forward the
184 // information from the RenderWidgetHelper. The problem is that doing so
185 // currently leaks outside of content all the way to chrome classes, and
186 // would be a layering violation. Since we don't expect more than a few
187 // hundreds of RWH, this seems acceptable. Revisit if performance become a
188 // problem, for example by tracking in the RenderWidgetHelper the routing id
189 // (and surface id) that have been created, but whose RWH haven't yet.
190 surface_id_ = GpuSurfaceTracker::Get()->LookupSurfaceForRenderer(
191 process_->GetID(),
192 routing_id_);
193 DCHECK(surface_id_);
196 std::pair<RoutingIDWidgetMap::iterator, bool> result =
197 g_routing_id_widget_map.Get().insert(std::make_pair(
198 RenderWidgetHostID(process->GetID(), routing_id_), this));
199 CHECK(result.second) << "Inserting a duplicate item!";
200 process_->AddRoute(routing_id_, this);
202 // If we're initially visible, tell the process host that we're alive.
203 // Otherwise we'll notify the process host when we are first shown.
204 if (!hidden)
205 process_->WidgetRestored();
207 latency_tracker_.Initialize(routing_id_, GetProcess()->GetID());
209 input_router_.reset(new InputRouterImpl(
210 process_, this, this, routing_id_, GetInputRouterConfigForPlatform()));
212 touch_emulator_.reset();
214 RenderViewHostImpl* rvh = static_cast<RenderViewHostImpl*>(
215 IsRenderView() ? RenderViewHost::From(this) : NULL);
216 if (BrowserPluginGuest::IsGuest(rvh) ||
217 !base::CommandLine::ForCurrentProcess()->HasSwitch(
218 switches::kDisableHangMonitor)) {
219 hang_monitor_timeout_.reset(new TimeoutMonitor(
220 base::Bind(&RenderWidgetHostImpl::RendererIsUnresponsive,
221 weak_factory_.GetWeakPtr())));
225 RenderWidgetHostImpl::~RenderWidgetHostImpl() {
226 if (view_weak_)
227 view_weak_->RenderWidgetHostGone();
228 SetView(NULL);
230 GpuSurfaceTracker::Get()->RemoveSurface(surface_id_);
231 surface_id_ = 0;
233 process_->RemoveRoute(routing_id_);
234 g_routing_id_widget_map.Get().erase(
235 RenderWidgetHostID(process_->GetID(), routing_id_));
237 if (delegate_)
238 delegate_->RenderWidgetDeleted(this);
241 // static
242 RenderWidgetHost* RenderWidgetHost::FromID(
243 int32 process_id,
244 int32 routing_id) {
245 return RenderWidgetHostImpl::FromID(process_id, routing_id);
248 // static
249 RenderWidgetHostImpl* RenderWidgetHostImpl::FromID(
250 int32 process_id,
251 int32 routing_id) {
252 DCHECK_CURRENTLY_ON(BrowserThread::UI);
253 RoutingIDWidgetMap* widgets = g_routing_id_widget_map.Pointer();
254 RoutingIDWidgetMap::iterator it = widgets->find(
255 RenderWidgetHostID(process_id, routing_id));
256 return it == widgets->end() ? NULL : it->second;
259 // static
260 scoped_ptr<RenderWidgetHostIterator> RenderWidgetHost::GetRenderWidgetHosts() {
261 RenderWidgetHostIteratorImpl* hosts = new RenderWidgetHostIteratorImpl();
262 RoutingIDWidgetMap* widgets = g_routing_id_widget_map.Pointer();
263 for (RoutingIDWidgetMap::const_iterator it = widgets->begin();
264 it != widgets->end();
265 ++it) {
266 RenderWidgetHost* widget = it->second;
268 if (!widget->IsRenderView()) {
269 hosts->Add(widget);
270 continue;
273 // Add only active RenderViewHosts.
274 RenderViewHost* rvh = RenderViewHost::From(widget);
275 if (static_cast<RenderViewHostImpl*>(rvh)->is_active())
276 hosts->Add(widget);
279 return scoped_ptr<RenderWidgetHostIterator>(hosts);
282 // static
283 scoped_ptr<RenderWidgetHostIterator>
284 RenderWidgetHostImpl::GetAllRenderWidgetHosts() {
285 RenderWidgetHostIteratorImpl* hosts = new RenderWidgetHostIteratorImpl();
286 RoutingIDWidgetMap* widgets = g_routing_id_widget_map.Pointer();
287 for (RoutingIDWidgetMap::const_iterator it = widgets->begin();
288 it != widgets->end();
289 ++it) {
290 hosts->Add(it->second);
293 return scoped_ptr<RenderWidgetHostIterator>(hosts);
296 // static
297 RenderWidgetHostImpl* RenderWidgetHostImpl::From(RenderWidgetHost* rwh) {
298 return rwh->AsRenderWidgetHostImpl();
301 void RenderWidgetHostImpl::SetView(RenderWidgetHostViewBase* view) {
302 if (view)
303 view_weak_ = view->GetWeakPtr();
304 else
305 view_weak_.reset();
306 view_ = view;
308 // If the renderer has not yet been initialized, then the surface ID
309 // namespace will be sent during initialization.
310 if (view_ && renderer_initialized_) {
311 Send(new ViewMsg_SetSurfaceIdNamespace(routing_id_,
312 view_->GetSurfaceIdNamespace()));
315 GpuSurfaceTracker::Get()->SetSurfaceHandle(
316 surface_id_, GetCompositingSurface());
318 synthetic_gesture_controller_.reset();
321 RenderProcessHost* RenderWidgetHostImpl::GetProcess() const {
322 return process_;
325 int RenderWidgetHostImpl::GetRoutingID() const {
326 return routing_id_;
329 RenderWidgetHostView* RenderWidgetHostImpl::GetView() const {
330 return view_;
333 RenderWidgetHostImpl* RenderWidgetHostImpl::AsRenderWidgetHostImpl() {
334 return this;
337 gfx::NativeViewId RenderWidgetHostImpl::GetNativeViewId() const {
338 if (view_)
339 return view_->GetNativeViewId();
340 return 0;
343 gfx::GLSurfaceHandle RenderWidgetHostImpl::GetCompositingSurface() {
344 if (view_)
345 return view_->GetCompositingSurface();
346 return gfx::GLSurfaceHandle();
349 void RenderWidgetHostImpl::ResetSizeAndRepaintPendingFlags() {
350 resize_ack_pending_ = false;
351 if (repaint_ack_pending_) {
352 TRACE_EVENT_ASYNC_END0(
353 "renderer_host", "RenderWidgetHostImpl::repaint_ack_pending_", this);
355 repaint_ack_pending_ = false;
356 if (old_resize_params_)
357 old_resize_params_->new_size = gfx::Size();
360 void RenderWidgetHostImpl::SendScreenRects() {
361 if (!renderer_initialized_ || waiting_for_screen_rects_ack_)
362 return;
364 if (is_hidden_) {
365 // On GTK, this comes in for backgrounded tabs. Ignore, to match what
366 // happens on Win & Mac, and when the view is shown it'll call this again.
367 return;
370 if (!view_)
371 return;
373 last_view_screen_rect_ = view_->GetViewBounds();
374 last_window_screen_rect_ = view_->GetBoundsInRootWindow();
375 Send(new ViewMsg_UpdateScreenRects(
376 GetRoutingID(), last_view_screen_rect_, last_window_screen_rect_));
377 if (delegate_)
378 delegate_->DidSendScreenRects(this);
379 waiting_for_screen_rects_ack_ = true;
382 void RenderWidgetHostImpl::SuppressNextCharEvents() {
383 suppress_next_char_events_ = true;
386 void RenderWidgetHostImpl::FlushInput() {
387 input_router_->RequestNotificationWhenFlushed();
388 if (synthetic_gesture_controller_)
389 synthetic_gesture_controller_->Flush(base::TimeTicks::Now());
392 void RenderWidgetHostImpl::SetNeedsFlush() {
393 if (view_)
394 view_->OnSetNeedsFlushInput();
397 void RenderWidgetHostImpl::Init() {
398 DCHECK(process_->HasConnection());
400 renderer_initialized_ = true;
402 GpuSurfaceTracker::Get()->SetSurfaceHandle(
403 surface_id_, GetCompositingSurface());
405 // Send the ack along with the information on placement.
406 Send(new ViewMsg_CreatingNew_ACK(routing_id_));
407 GetProcess()->ResumeRequestsForView(routing_id_);
409 // If the RWHV has not yet been set, the surface ID namespace will get
410 // passed down by the call to SetView().
411 if (view_) {
412 Send(new ViewMsg_SetSurfaceIdNamespace(routing_id_,
413 view_->GetSurfaceIdNamespace()));
416 WasResized();
419 void RenderWidgetHostImpl::InitForFrame() {
420 DCHECK(process_->HasConnection());
421 renderer_initialized_ = true;
424 void RenderWidgetHostImpl::Shutdown() {
425 RejectMouseLockOrUnlockIfNecessary();
427 if (process_->HasConnection()) {
428 // Tell the renderer object to close.
429 bool rv = Send(new ViewMsg_Close(routing_id_));
430 DCHECK(rv);
433 Destroy();
436 bool RenderWidgetHostImpl::IsLoading() const {
437 return is_loading_;
440 bool RenderWidgetHostImpl::IsRenderView() const {
441 return false;
444 bool RenderWidgetHostImpl::OnMessageReceived(const IPC::Message &msg) {
445 bool handled = true;
446 IPC_BEGIN_MESSAGE_MAP(RenderWidgetHostImpl, msg)
447 IPC_MESSAGE_HANDLER(FrameHostMsg_RenderProcessGone, OnRenderProcessGone)
448 IPC_MESSAGE_HANDLER(InputHostMsg_QueueSyntheticGesture,
449 OnQueueSyntheticGesture)
450 IPC_MESSAGE_HANDLER(InputHostMsg_ImeCancelComposition,
451 OnImeCancelComposition)
452 IPC_MESSAGE_HANDLER(ViewHostMsg_RenderViewReady, OnRenderViewReady)
453 IPC_MESSAGE_HANDLER(ViewHostMsg_Close, OnClose)
454 IPC_MESSAGE_HANDLER(ViewHostMsg_UpdateScreenRects_ACK,
455 OnUpdateScreenRectsAck)
456 IPC_MESSAGE_HANDLER(ViewHostMsg_RequestMove, OnRequestMove)
457 IPC_MESSAGE_HANDLER(ViewHostMsg_SetTooltipText, OnSetTooltipText)
458 IPC_MESSAGE_HANDLER_GENERIC(ViewHostMsg_SwapCompositorFrame,
459 OnSwapCompositorFrame(msg))
460 IPC_MESSAGE_HANDLER(ViewHostMsg_UpdateRect, OnUpdateRect)
461 IPC_MESSAGE_HANDLER(ViewHostMsg_Focus, OnFocus)
462 IPC_MESSAGE_HANDLER(ViewHostMsg_Blur, OnBlur)
463 IPC_MESSAGE_HANDLER(ViewHostMsg_SetCursor, OnSetCursor)
464 IPC_MESSAGE_HANDLER(ViewHostMsg_TextInputStateChanged,
465 OnTextInputStateChanged)
466 IPC_MESSAGE_HANDLER(ViewHostMsg_LockMouse, OnLockMouse)
467 IPC_MESSAGE_HANDLER(ViewHostMsg_UnlockMouse, OnUnlockMouse)
468 IPC_MESSAGE_HANDLER(ViewHostMsg_ShowDisambiguationPopup,
469 OnShowDisambiguationPopup)
470 IPC_MESSAGE_HANDLER(ViewHostMsg_SelectionChanged, OnSelectionChanged)
471 IPC_MESSAGE_HANDLER(ViewHostMsg_SelectionBoundsChanged,
472 OnSelectionBoundsChanged)
473 #if defined(OS_WIN)
474 IPC_MESSAGE_HANDLER(ViewHostMsg_WindowlessPluginDummyWindowCreated,
475 OnWindowlessPluginDummyWindowCreated)
476 IPC_MESSAGE_HANDLER(ViewHostMsg_WindowlessPluginDummyWindowDestroyed,
477 OnWindowlessPluginDummyWindowDestroyed)
478 #endif
479 IPC_MESSAGE_HANDLER(InputHostMsg_ImeCompositionRangeChanged,
480 OnImeCompositionRangeChanged)
481 IPC_MESSAGE_UNHANDLED(handled = false)
482 IPC_END_MESSAGE_MAP()
484 if (!handled && input_router_ && input_router_->OnMessageReceived(msg))
485 return true;
487 if (!handled && view_ && view_->OnMessageReceived(msg))
488 return true;
490 return handled;
493 bool RenderWidgetHostImpl::Send(IPC::Message* msg) {
494 if (IPC_MESSAGE_ID_CLASS(msg->type()) == InputMsgStart)
495 return input_router_->SendInput(make_scoped_ptr(msg));
497 return process_->Send(msg);
500 void RenderWidgetHostImpl::SetIsLoading(bool is_loading) {
501 is_loading_ = is_loading;
502 if (!view_)
503 return;
504 view_->SetIsLoading(is_loading);
507 void RenderWidgetHostImpl::WasHidden() {
508 if (is_hidden_)
509 return;
511 TRACE_EVENT0("renderer_host", "RenderWidgetHostImpl::WasHidden");
512 is_hidden_ = true;
514 // Don't bother reporting hung state when we aren't active.
515 StopHangMonitorTimeout();
517 // If we have a renderer, then inform it that we are being hidden so it can
518 // reduce its resource utilization.
519 Send(new ViewMsg_WasHidden(routing_id_));
521 // Tell the RenderProcessHost we were hidden.
522 process_->WidgetHidden();
524 bool is_visible = false;
525 NotificationService::current()->Notify(
526 NOTIFICATION_RENDER_WIDGET_VISIBILITY_CHANGED,
527 Source<RenderWidgetHost>(this),
528 Details<bool>(&is_visible));
531 void RenderWidgetHostImpl::WasShown(const ui::LatencyInfo& latency_info) {
532 if (!is_hidden_)
533 return;
535 TRACE_EVENT0("renderer_host", "RenderWidgetHostImpl::WasShown");
536 is_hidden_ = false;
538 SendScreenRects();
540 // When hidden, timeout monitoring for input events is disabled. Restore it
541 // now to ensure consistent hang detection.
542 if (in_flight_event_count_)
543 RestartHangMonitorTimeout();
545 // Always repaint on restore.
546 bool needs_repainting = true;
547 needs_repainting_on_restore_ = false;
548 Send(new ViewMsg_WasShown(routing_id_, needs_repainting, latency_info));
550 process_->WidgetRestored();
552 bool is_visible = true;
553 NotificationService::current()->Notify(
554 NOTIFICATION_RENDER_WIDGET_VISIBILITY_CHANGED,
555 Source<RenderWidgetHost>(this),
556 Details<bool>(&is_visible));
558 // It's possible for our size to be out of sync with the renderer. The
559 // following is one case that leads to this:
560 // 1. WasResized -> Send ViewMsg_Resize to render
561 // 2. WasResized -> do nothing as resize_ack_pending_ is true
562 // 3. WasHidden
563 // 4. OnUpdateRect from (1) processed. Does NOT invoke WasResized as view
564 // is hidden. Now renderer/browser out of sync with what they think size
565 // is.
566 // By invoking WasResized the renderer is updated as necessary. WasResized
567 // does nothing if the sizes are already in sync.
569 // TODO: ideally ViewMsg_WasShown would take a size. This way, the renderer
570 // could handle both the restore and resize at once. This isn't that big a
571 // deal as RenderWidget::WasShown delays updating, so that the resize from
572 // WasResized is usually processed before the renderer is painted.
573 WasResized();
576 bool RenderWidgetHostImpl::GetResizeParams(
577 ViewMsg_Resize_Params* resize_params) {
578 *resize_params = ViewMsg_Resize_Params();
580 GetWebScreenInfo(&resize_params->screen_info);
581 resize_params->resizer_rect = GetRootWindowResizerRect();
583 if (view_) {
584 resize_params->new_size = view_->GetRequestedRendererSize();
585 resize_params->physical_backing_size = view_->GetPhysicalBackingSize();
586 resize_params->top_controls_height = view_->GetTopControlsHeight();
587 resize_params->top_controls_shrink_blink_size =
588 view_->DoTopControlsShrinkBlinkSize();
589 resize_params->visible_viewport_size = view_->GetVisibleViewportSize();
590 resize_params->is_fullscreen_granted = IsFullscreenGranted();
591 resize_params->display_mode = GetDisplayMode();
594 const bool size_changed =
595 !old_resize_params_ ||
596 old_resize_params_->new_size != resize_params->new_size ||
597 (old_resize_params_->physical_backing_size.IsEmpty() &&
598 !resize_params->physical_backing_size.IsEmpty());
599 bool dirty = size_changed ||
600 old_resize_params_->screen_info != resize_params->screen_info ||
601 old_resize_params_->physical_backing_size !=
602 resize_params->physical_backing_size ||
603 old_resize_params_->is_fullscreen_granted !=
604 resize_params->is_fullscreen_granted ||
605 old_resize_params_->display_mode != resize_params->display_mode ||
606 old_resize_params_->top_controls_height !=
607 resize_params->top_controls_height ||
608 old_resize_params_->top_controls_shrink_blink_size !=
609 resize_params->top_controls_shrink_blink_size ||
610 old_resize_params_->visible_viewport_size !=
611 resize_params->visible_viewport_size;
613 // We don't expect to receive an ACK when the requested size or the physical
614 // backing size is empty, or when the main viewport size didn't change.
615 resize_params->needs_resize_ack =
616 g_check_for_pending_resize_ack && !resize_params->new_size.IsEmpty() &&
617 !resize_params->physical_backing_size.IsEmpty() && size_changed;
619 return dirty;
622 void RenderWidgetHostImpl::SetInitialRenderSizeParams(
623 const ViewMsg_Resize_Params& resize_params) {
624 resize_ack_pending_ = resize_params.needs_resize_ack;
626 old_resize_params_ =
627 make_scoped_ptr(new ViewMsg_Resize_Params(resize_params));
630 void RenderWidgetHostImpl::WasResized() {
631 // Skip if the |delegate_| has already been detached because
632 // it's web contents is being deleted.
633 if (resize_ack_pending_ || !process_->HasConnection() || !view_ ||
634 !renderer_initialized_ || auto_resize_enabled_ || !delegate_) {
635 return;
638 scoped_ptr<ViewMsg_Resize_Params> params(new ViewMsg_Resize_Params);
639 if (!GetResizeParams(params.get()))
640 return;
642 bool width_changed =
643 !old_resize_params_ ||
644 old_resize_params_->new_size.width() != params->new_size.width();
645 if (Send(new ViewMsg_Resize(routing_id_, *params))) {
646 resize_ack_pending_ = params->needs_resize_ack;
647 old_resize_params_.swap(params);
650 if (delegate_)
651 delegate_->RenderWidgetWasResized(this, width_changed);
654 void RenderWidgetHostImpl::ResizeRectChanged(const gfx::Rect& new_rect) {
655 Send(new ViewMsg_ChangeResizeRect(routing_id_, new_rect));
658 void RenderWidgetHostImpl::GotFocus() {
659 Focus();
660 if (delegate_)
661 delegate_->RenderWidgetGotFocus(this);
664 void RenderWidgetHostImpl::Focus() {
665 is_focused_ = true;
667 Send(new InputMsg_SetFocus(routing_id_, true));
670 void RenderWidgetHostImpl::Blur() {
671 is_focused_ = false;
673 // If there is a pending mouse lock request, we don't want to reject it at
674 // this point. The user can switch focus back to this view and approve the
675 // request later.
676 if (IsMouseLocked())
677 view_->UnlockMouse();
679 if (touch_emulator_)
680 touch_emulator_->CancelTouch();
682 Send(new InputMsg_SetFocus(routing_id_, false));
685 void RenderWidgetHostImpl::LostCapture() {
686 if (touch_emulator_)
687 touch_emulator_->CancelTouch();
689 Send(new InputMsg_MouseCaptureLost(routing_id_));
692 void RenderWidgetHostImpl::SetActive(bool active) {
693 Send(new ViewMsg_SetActive(routing_id_, active));
696 void RenderWidgetHostImpl::LostMouseLock() {
697 Send(new ViewMsg_MouseLockLost(routing_id_));
700 void RenderWidgetHostImpl::ViewDestroyed() {
701 RejectMouseLockOrUnlockIfNecessary();
703 // TODO(evanm): tracking this may no longer be necessary;
704 // eliminate this function if so.
705 SetView(NULL);
708 void RenderWidgetHostImpl::CopyFromBackingStore(
709 const gfx::Rect& src_subrect,
710 const gfx::Size& accelerated_dst_size,
711 ReadbackRequestCallback& callback,
712 const SkColorType preferred_color_type) {
713 if (view_) {
714 TRACE_EVENT0("browser",
715 "RenderWidgetHostImpl::CopyFromBackingStore::FromCompositingSurface");
716 gfx::Rect accelerated_copy_rect = src_subrect.IsEmpty() ?
717 gfx::Rect(view_->GetViewBounds().size()) : src_subrect;
718 view_->CopyFromCompositingSurface(accelerated_copy_rect,
719 accelerated_dst_size, callback,
720 preferred_color_type);
721 return;
724 callback.Run(SkBitmap(), content::READBACK_FAILED);
727 bool RenderWidgetHostImpl::CanCopyFromBackingStore() {
728 if (view_)
729 return view_->IsSurfaceAvailableForCopy();
730 return false;
733 #if defined(OS_ANDROID)
734 void RenderWidgetHostImpl::LockBackingStore() {
735 if (view_)
736 view_->LockCompositingSurface();
739 void RenderWidgetHostImpl::UnlockBackingStore() {
740 if (view_)
741 view_->UnlockCompositingSurface();
743 #endif
745 #if defined(OS_MACOSX)
746 void RenderWidgetHostImpl::PauseForPendingResizeOrRepaints() {
747 TRACE_EVENT0("browser",
748 "RenderWidgetHostImpl::PauseForPendingResizeOrRepaints");
750 if (!CanPauseForPendingResizeOrRepaints())
751 return;
753 WaitForSurface();
756 bool RenderWidgetHostImpl::CanPauseForPendingResizeOrRepaints() {
757 // Do not pause if the view is hidden.
758 if (is_hidden())
759 return false;
761 // Do not pause if there is not a paint or resize already coming.
762 if (!repaint_ack_pending_ && !resize_ack_pending_)
763 return false;
765 return true;
768 void RenderWidgetHostImpl::WaitForSurface() {
769 // How long to (synchronously) wait for the renderer to respond with a
770 // new frame when our current frame doesn't exist or is the wrong size.
771 // This timeout impacts the "choppiness" of our window resize.
772 const int kPaintMsgTimeoutMS = 50;
774 if (!view_)
775 return;
777 // The view_size will be current_size_ for auto-sized views and otherwise the
778 // size of the view_. (For auto-sized views, current_size_ is updated during
779 // UpdateRect messages.)
780 gfx::Size view_size = current_size_;
781 if (!auto_resize_enabled_) {
782 // Get the desired size from the current view bounds.
783 gfx::Rect view_rect = view_->GetViewBounds();
784 if (view_rect.IsEmpty())
785 return;
786 view_size = view_rect.size();
789 TRACE_EVENT2("renderer_host",
790 "RenderWidgetHostImpl::WaitForSurface",
791 "width",
792 base::IntToString(view_size.width()),
793 "height",
794 base::IntToString(view_size.height()));
796 // We should not be asked to paint while we are hidden. If we are hidden,
797 // then it means that our consumer failed to call WasShown.
798 DCHECK(!is_hidden_) << "WaitForSurface called while hidden!";
800 // We should never be called recursively; this can theoretically lead to
801 // infinite recursion and almost certainly leads to lower performance.
802 DCHECK(!in_get_backing_store_) << "WaitForSurface called recursively!";
803 base::AutoReset<bool> auto_reset_in_get_backing_store(
804 &in_get_backing_store_, true);
806 // We might have a surface that we can use already.
807 if (view_->HasAcceleratedSurface(view_size))
808 return;
810 // Request that the renderer produce a frame of the right size, if it
811 // hasn't been requested already.
812 if (!repaint_ack_pending_ && !resize_ack_pending_) {
813 repaint_start_time_ = TimeTicks::Now();
814 repaint_ack_pending_ = true;
815 TRACE_EVENT_ASYNC_BEGIN0(
816 "renderer_host", "RenderWidgetHostImpl::repaint_ack_pending_", this);
817 Send(new ViewMsg_Repaint(routing_id_, view_size));
820 // Pump a nested message loop until we time out or get a frame of the right
821 // size.
822 TimeTicks start_time = TimeTicks::Now();
823 TimeDelta time_left = TimeDelta::FromMilliseconds(kPaintMsgTimeoutMS);
824 TimeTicks timeout_time = start_time + time_left;
825 while (1) {
826 TRACE_EVENT0("renderer_host", "WaitForSurface::WaitForSingleTaskToRun");
827 if (RenderWidgetResizeHelper::Get()->WaitForSingleTaskToRun(time_left)) {
828 // For auto-resized views, current_size_ determines the view_size and it
829 // may have changed during the handling of an UpdateRect message.
830 if (auto_resize_enabled_)
831 view_size = current_size_;
832 if (view_->HasAcceleratedSurface(view_size))
833 break;
835 time_left = timeout_time - TimeTicks::Now();
836 if (time_left <= TimeDelta::FromSeconds(0)) {
837 TRACE_EVENT0("renderer_host", "WaitForSurface::Timeout");
838 break;
842 UMA_HISTOGRAM_CUSTOM_TIMES("OSX.RendererHost.SurfaceWaitTime",
843 TimeTicks::Now() - start_time,
844 TimeDelta::FromMilliseconds(1),
845 TimeDelta::FromMilliseconds(200), 50);
847 #endif
849 bool RenderWidgetHostImpl::ScheduleComposite() {
850 if (is_hidden_ || current_size_.IsEmpty() || repaint_ack_pending_ ||
851 resize_ack_pending_) {
852 return false;
855 // Send out a request to the renderer to paint the view if required.
856 repaint_start_time_ = TimeTicks::Now();
857 repaint_ack_pending_ = true;
858 TRACE_EVENT_ASYNC_BEGIN0(
859 "renderer_host", "RenderWidgetHostImpl::repaint_ack_pending_", this);
860 Send(new ViewMsg_Repaint(routing_id_, current_size_));
861 return true;
864 void RenderWidgetHostImpl::StartHangMonitorTimeout(base::TimeDelta delay) {
865 if (hang_monitor_timeout_)
866 hang_monitor_timeout_->Start(delay);
869 void RenderWidgetHostImpl::RestartHangMonitorTimeout() {
870 if (hang_monitor_timeout_)
871 hang_monitor_timeout_->Restart(hung_renderer_delay_);
874 void RenderWidgetHostImpl::StopHangMonitorTimeout() {
875 if (hang_monitor_timeout_)
876 hang_monitor_timeout_->Stop();
877 RendererIsResponsive();
880 void RenderWidgetHostImpl::ForwardMouseEvent(const WebMouseEvent& mouse_event) {
881 ForwardMouseEventWithLatencyInfo(mouse_event, ui::LatencyInfo());
884 void RenderWidgetHostImpl::ForwardMouseEventWithLatencyInfo(
885 const blink::WebMouseEvent& mouse_event,
886 const ui::LatencyInfo& ui_latency) {
887 TRACE_EVENT2("input", "RenderWidgetHostImpl::ForwardMouseEvent",
888 "x", mouse_event.x, "y", mouse_event.y);
890 for (size_t i = 0; i < mouse_event_callbacks_.size(); ++i) {
891 if (mouse_event_callbacks_[i].Run(mouse_event))
892 return;
895 if (IgnoreInputEvents())
896 return;
898 if (touch_emulator_ && touch_emulator_->HandleMouseEvent(mouse_event))
899 return;
901 MouseEventWithLatencyInfo mouse_with_latency(mouse_event, ui_latency);
902 latency_tracker_.OnInputEvent(mouse_event, &mouse_with_latency.latency);
903 input_router_->SendMouseEvent(mouse_with_latency);
905 // Pass mouse state to gpu service if the subscribe uniform
906 // extension is enabled.
907 if (process_->SubscribeUniformEnabled()) {
908 gpu::ValueState state;
909 state.int_value[0] = mouse_event.x;
910 state.int_value[1] = mouse_event.y;
911 // TODO(orglofch) Separate the mapping of pending value states to the
912 // Gpu Service to be per RWH not per process
913 process_->SendUpdateValueState(GL_MOUSE_POSITION_CHROMIUM, state);
917 void RenderWidgetHostImpl::ForwardWheelEvent(
918 const WebMouseWheelEvent& wheel_event) {
919 ForwardWheelEventWithLatencyInfo(wheel_event, ui::LatencyInfo());
922 void RenderWidgetHostImpl::ForwardWheelEventWithLatencyInfo(
923 const blink::WebMouseWheelEvent& wheel_event,
924 const ui::LatencyInfo& ui_latency) {
925 TRACE_EVENT2("input", "RenderWidgetHostImpl::ForwardWheelEvent",
926 "dx", wheel_event.deltaX, "dy", wheel_event.deltaY);
928 if (IgnoreInputEvents())
929 return;
931 if (touch_emulator_ && touch_emulator_->HandleMouseWheelEvent(wheel_event))
932 return;
934 MouseWheelEventWithLatencyInfo wheel_with_latency(wheel_event, ui_latency);
935 latency_tracker_.OnInputEvent(wheel_event, &wheel_with_latency.latency);
936 input_router_->SendWheelEvent(wheel_with_latency);
939 void RenderWidgetHostImpl::ForwardGestureEvent(
940 const blink::WebGestureEvent& gesture_event) {
941 ForwardGestureEventWithLatencyInfo(gesture_event, ui::LatencyInfo());
944 void RenderWidgetHostImpl::ForwardGestureEventWithLatencyInfo(
945 const blink::WebGestureEvent& gesture_event,
946 const ui::LatencyInfo& ui_latency) {
947 TRACE_EVENT0("input", "RenderWidgetHostImpl::ForwardGestureEvent");
948 // Early out if necessary, prior to performing latency logic.
949 if (IgnoreInputEvents())
950 return;
952 if (delegate_->PreHandleGestureEvent(gesture_event))
953 return;
955 GestureEventWithLatencyInfo gesture_with_latency(gesture_event, ui_latency);
956 latency_tracker_.OnInputEvent(gesture_event, &gesture_with_latency.latency);
957 input_router_->SendGestureEvent(gesture_with_latency);
960 void RenderWidgetHostImpl::ForwardEmulatedTouchEvent(
961 const blink::WebTouchEvent& touch_event) {
962 TRACE_EVENT0("input", "RenderWidgetHostImpl::ForwardEmulatedTouchEvent");
964 TouchEventWithLatencyInfo touch_with_latency(touch_event);
965 latency_tracker_.OnInputEvent(touch_event, &touch_with_latency.latency);
966 input_router_->SendTouchEvent(touch_with_latency);
969 void RenderWidgetHostImpl::ForwardTouchEventWithLatencyInfo(
970 const blink::WebTouchEvent& touch_event,
971 const ui::LatencyInfo& ui_latency) {
972 TRACE_EVENT0("input", "RenderWidgetHostImpl::ForwardTouchEvent");
974 // Always forward TouchEvents for touch stream consistency. They will be
975 // ignored if appropriate in FilterInputEvent().
977 TouchEventWithLatencyInfo touch_with_latency(touch_event, ui_latency);
978 if (touch_emulator_ &&
979 touch_emulator_->HandleTouchEvent(touch_with_latency.event)) {
980 if (view_) {
981 view_->ProcessAckedTouchEvent(
982 touch_with_latency, INPUT_EVENT_ACK_STATE_CONSUMED);
984 return;
987 latency_tracker_.OnInputEvent(touch_event, &touch_with_latency.latency);
988 input_router_->SendTouchEvent(touch_with_latency);
991 void RenderWidgetHostImpl::ForwardKeyboardEvent(
992 const NativeWebKeyboardEvent& key_event) {
993 TRACE_EVENT0("input", "RenderWidgetHostImpl::ForwardKeyboardEvent");
994 if (IgnoreInputEvents())
995 return;
997 if (!process_->HasConnection())
998 return;
1000 // First, let keypress listeners take a shot at handling the event. If a
1001 // listener handles the event, it should not be propagated to the renderer.
1002 if (KeyPressListenersHandleEvent(key_event)) {
1003 // Some keypresses that are accepted by the listener might have follow up
1004 // char events, which should be ignored.
1005 if (key_event.type == WebKeyboardEvent::RawKeyDown)
1006 suppress_next_char_events_ = true;
1007 return;
1010 if (key_event.type == WebKeyboardEvent::Char &&
1011 (key_event.windowsKeyCode == ui::VKEY_RETURN ||
1012 key_event.windowsKeyCode == ui::VKEY_SPACE)) {
1013 OnUserGesture();
1016 // Double check the type to make sure caller hasn't sent us nonsense that
1017 // will mess up our key queue.
1018 if (!WebInputEvent::isKeyboardEventType(key_event.type))
1019 return;
1021 if (suppress_next_char_events_) {
1022 // If preceding RawKeyDown event was handled by the browser, then we need
1023 // suppress all Char events generated by it. Please note that, one
1024 // RawKeyDown event may generate multiple Char events, so we can't reset
1025 // |suppress_next_char_events_| until we get a KeyUp or a RawKeyDown.
1026 if (key_event.type == WebKeyboardEvent::Char)
1027 return;
1028 // We get a KeyUp or a RawKeyDown event.
1029 suppress_next_char_events_ = false;
1032 bool is_shortcut = false;
1034 // Only pre-handle the key event if it's not handled by the input method.
1035 if (delegate_ && !key_event.skip_in_browser) {
1036 // We need to set |suppress_next_char_events_| to true if
1037 // PreHandleKeyboardEvent() returns true, but |this| may already be
1038 // destroyed at that time. So set |suppress_next_char_events_| true here,
1039 // then revert it afterwards when necessary.
1040 if (key_event.type == WebKeyboardEvent::RawKeyDown)
1041 suppress_next_char_events_ = true;
1043 // Tab switching/closing accelerators aren't sent to the renderer to avoid
1044 // a hung/malicious renderer from interfering.
1045 if (delegate_->PreHandleKeyboardEvent(key_event, &is_shortcut))
1046 return;
1048 if (key_event.type == WebKeyboardEvent::RawKeyDown)
1049 suppress_next_char_events_ = false;
1052 if (touch_emulator_ && touch_emulator_->HandleKeyboardEvent(key_event))
1053 return;
1055 NativeWebKeyboardEventWithLatencyInfo key_event_with_latency(key_event);
1056 latency_tracker_.OnInputEvent(key_event, &key_event_with_latency.latency);
1057 input_router_->SendKeyboardEvent(key_event_with_latency, is_shortcut);
1060 void RenderWidgetHostImpl::QueueSyntheticGesture(
1061 scoped_ptr<SyntheticGesture> synthetic_gesture,
1062 const base::Callback<void(SyntheticGesture::Result)>& on_complete) {
1063 if (!synthetic_gesture_controller_ && view_) {
1064 synthetic_gesture_controller_.reset(
1065 new SyntheticGestureController(
1066 view_->CreateSyntheticGestureTarget().Pass()));
1068 if (synthetic_gesture_controller_) {
1069 synthetic_gesture_controller_->QueueSyntheticGesture(
1070 synthetic_gesture.Pass(), on_complete);
1074 void RenderWidgetHostImpl::SetCursor(const WebCursor& cursor) {
1075 if (!view_)
1076 return;
1077 view_->UpdateCursor(cursor);
1080 void RenderWidgetHostImpl::ShowContextMenuAtPoint(const gfx::Point& point) {
1081 Send(new ViewMsg_ShowContextMenu(
1082 GetRoutingID(), ui::MENU_SOURCE_MOUSE, point));
1085 void RenderWidgetHostImpl::SendCursorVisibilityState(bool is_visible) {
1086 Send(new InputMsg_CursorVisibilityChange(GetRoutingID(), is_visible));
1089 int64 RenderWidgetHostImpl::GetLatencyComponentId() const {
1090 return latency_tracker_.latency_component_id();
1093 // static
1094 void RenderWidgetHostImpl::DisableResizeAckCheckForTesting() {
1095 g_check_for_pending_resize_ack = false;
1098 void RenderWidgetHostImpl::AddKeyPressEventCallback(
1099 const KeyPressEventCallback& callback) {
1100 key_press_event_callbacks_.push_back(callback);
1103 void RenderWidgetHostImpl::RemoveKeyPressEventCallback(
1104 const KeyPressEventCallback& callback) {
1105 for (size_t i = 0; i < key_press_event_callbacks_.size(); ++i) {
1106 if (key_press_event_callbacks_[i].Equals(callback)) {
1107 key_press_event_callbacks_.erase(
1108 key_press_event_callbacks_.begin() + i);
1109 return;
1114 void RenderWidgetHostImpl::AddMouseEventCallback(
1115 const MouseEventCallback& callback) {
1116 mouse_event_callbacks_.push_back(callback);
1119 void RenderWidgetHostImpl::RemoveMouseEventCallback(
1120 const MouseEventCallback& callback) {
1121 for (size_t i = 0; i < mouse_event_callbacks_.size(); ++i) {
1122 if (mouse_event_callbacks_[i].Equals(callback)) {
1123 mouse_event_callbacks_.erase(mouse_event_callbacks_.begin() + i);
1124 return;
1129 void RenderWidgetHostImpl::GetWebScreenInfo(blink::WebScreenInfo* result) {
1130 TRACE_EVENT0("renderer_host", "RenderWidgetHostImpl::GetWebScreenInfo");
1131 if (view_)
1132 view_->GetScreenInfo(result);
1133 else
1134 RenderWidgetHostViewBase::GetDefaultScreenInfo(result);
1135 // TODO(sievers): find a way to make this done another way so the method
1136 // can be const.
1137 latency_tracker_.set_device_scale_factor(result->deviceScaleFactor);
1140 const NativeWebKeyboardEvent*
1141 RenderWidgetHostImpl::GetLastKeyboardEvent() const {
1142 return input_router_->GetLastKeyboardEvent();
1145 void RenderWidgetHostImpl::NotifyScreenInfoChanged() {
1146 if (delegate_)
1147 delegate_->ScreenInfoChanged();
1149 // The resize message (which may not happen immediately) will carry with it
1150 // the screen info as well as the new size (if the screen has changed scale
1151 // factor).
1152 WasResized();
1155 void RenderWidgetHostImpl::GetSnapshotFromBrowser(
1156 const base::Callback<void(const unsigned char*,size_t)> callback) {
1157 int id = next_browser_snapshot_id_++;
1158 pending_browser_snapshots_.insert(std::make_pair(id, callback));
1159 Send(new ViewMsg_ForceRedraw(GetRoutingID(), id));
1162 void RenderWidgetHostImpl::OnSelectionChanged(const base::string16& text,
1163 size_t offset,
1164 const gfx::Range& range) {
1165 if (view_)
1166 view_->SelectionChanged(text, offset, range);
1169 void RenderWidgetHostImpl::OnSelectionBoundsChanged(
1170 const ViewHostMsg_SelectionBounds_Params& params) {
1171 if (view_) {
1172 view_->SelectionBoundsChanged(params);
1176 void RenderWidgetHostImpl::UpdateVSyncParameters(base::TimeTicks timebase,
1177 base::TimeDelta interval) {
1178 Send(new ViewMsg_UpdateVSyncParameters(GetRoutingID(), timebase, interval));
1181 void RenderWidgetHostImpl::RendererExited(base::TerminationStatus status,
1182 int exit_code) {
1183 if (!renderer_initialized_)
1184 return;
1186 // Clearing this flag causes us to re-create the renderer when recovering
1187 // from a crashed renderer.
1188 renderer_initialized_ = false;
1190 waiting_for_screen_rects_ack_ = false;
1192 // Must reset these to ensure that keyboard events work with a new renderer.
1193 suppress_next_char_events_ = false;
1195 // Reset some fields in preparation for recovering from a crash.
1196 ResetSizeAndRepaintPendingFlags();
1197 current_size_.SetSize(0, 0);
1198 // After the renderer crashes, the view is destroyed and so the
1199 // RenderWidgetHost cannot track its visibility anymore. We assume such
1200 // RenderWidgetHost to be visible for the sake of internal accounting - be
1201 // careful about changing this - see http://crbug.com/401859.
1203 // We need to at least make sure that the RenderProcessHost is notified about
1204 // the |is_hidden_| change, so that the renderer will have correct visibility
1205 // set when respawned.
1206 if (is_hidden_) {
1207 process_->WidgetRestored();
1208 is_hidden_ = false;
1211 // Reset this to ensure the hung renderer mechanism is working properly.
1212 in_flight_event_count_ = 0;
1213 StopHangMonitorTimeout();
1215 if (view_) {
1216 GpuSurfaceTracker::Get()->SetSurfaceHandle(surface_id_,
1217 gfx::GLSurfaceHandle());
1218 view_->RenderProcessGone(status, exit_code);
1219 view_ = NULL; // The View should be deleted by RenderProcessGone.
1220 view_weak_.reset();
1223 // Reconstruct the input router to ensure that it has fresh state for a new
1224 // renderer. Otherwise it may be stuck waiting for the old renderer to ack an
1225 // event. (In particular, the above call to view_->RenderProcessGone will
1226 // destroy the aura window, which may dispatch a synthetic mouse move.)
1227 input_router_.reset(new InputRouterImpl(
1228 process_, this, this, routing_id_, GetInputRouterConfigForPlatform()));
1230 synthetic_gesture_controller_.reset();
1233 void RenderWidgetHostImpl::UpdateTextDirection(WebTextDirection direction) {
1234 text_direction_updated_ = true;
1235 text_direction_ = direction;
1238 void RenderWidgetHostImpl::CancelUpdateTextDirection() {
1239 if (text_direction_updated_)
1240 text_direction_canceled_ = true;
1243 void RenderWidgetHostImpl::NotifyTextDirection() {
1244 if (text_direction_updated_) {
1245 if (!text_direction_canceled_)
1246 Send(new ViewMsg_SetTextDirection(GetRoutingID(), text_direction_));
1247 text_direction_updated_ = false;
1248 text_direction_canceled_ = false;
1252 void RenderWidgetHostImpl::ImeSetComposition(
1253 const base::string16& text,
1254 const std::vector<blink::WebCompositionUnderline>& underlines,
1255 int selection_start,
1256 int selection_end) {
1257 Send(new InputMsg_ImeSetComposition(
1258 GetRoutingID(), text, underlines, selection_start, selection_end));
1261 void RenderWidgetHostImpl::ImeConfirmComposition(
1262 const base::string16& text,
1263 const gfx::Range& replacement_range,
1264 bool keep_selection) {
1265 Send(new InputMsg_ImeConfirmComposition(
1266 GetRoutingID(), text, replacement_range, keep_selection));
1269 void RenderWidgetHostImpl::ImeCancelComposition() {
1270 Send(new InputMsg_ImeSetComposition(GetRoutingID(), base::string16(),
1271 std::vector<blink::WebCompositionUnderline>(), 0, 0));
1274 gfx::Rect RenderWidgetHostImpl::GetRootWindowResizerRect() const {
1275 return gfx::Rect();
1278 void RenderWidgetHostImpl::RequestToLockMouse(bool user_gesture,
1279 bool last_unlocked_by_target) {
1280 // Directly reject to lock the mouse. Subclass can override this method to
1281 // decide whether to allow mouse lock or not.
1282 GotResponseToLockMouseRequest(false);
1285 void RenderWidgetHostImpl::RejectMouseLockOrUnlockIfNecessary() {
1286 DCHECK(!pending_mouse_lock_request_ || !IsMouseLocked());
1287 if (pending_mouse_lock_request_) {
1288 pending_mouse_lock_request_ = false;
1289 Send(new ViewMsg_LockMouse_ACK(routing_id_, false));
1290 } else if (IsMouseLocked()) {
1291 view_->UnlockMouse();
1295 bool RenderWidgetHostImpl::IsMouseLocked() const {
1296 return view_ ? view_->IsMouseLocked() : false;
1299 bool RenderWidgetHostImpl::IsFullscreenGranted() const {
1300 return false;
1303 blink::WebDisplayMode RenderWidgetHostImpl::GetDisplayMode() const {
1304 return blink::WebDisplayModeBrowser;
1307 void RenderWidgetHostImpl::SetAutoResize(bool enable,
1308 const gfx::Size& min_size,
1309 const gfx::Size& max_size) {
1310 auto_resize_enabled_ = enable;
1311 min_size_for_auto_resize_ = min_size;
1312 max_size_for_auto_resize_ = max_size;
1315 void RenderWidgetHostImpl::Destroy() {
1316 NotificationService::current()->Notify(
1317 NOTIFICATION_RENDER_WIDGET_HOST_DESTROYED,
1318 Source<RenderWidgetHost>(this),
1319 NotificationService::NoDetails());
1321 // Tell the view to die.
1322 // Note that in the process of the view shutting down, it can call a ton
1323 // of other messages on us. So if you do any other deinitialization here,
1324 // do it after this call to view_->Destroy().
1325 if (view_) {
1326 view_->Destroy();
1327 view_ = nullptr;
1330 delete this;
1333 void RenderWidgetHostImpl::RendererIsUnresponsive() {
1334 NotificationService::current()->Notify(
1335 NOTIFICATION_RENDER_WIDGET_HOST_HANG,
1336 Source<RenderWidgetHost>(this),
1337 NotificationService::NoDetails());
1338 is_unresponsive_ = true;
1339 NotifyRendererUnresponsive();
1342 void RenderWidgetHostImpl::RendererIsResponsive() {
1343 if (is_unresponsive_) {
1344 is_unresponsive_ = false;
1345 NotifyRendererResponsive();
1349 void RenderWidgetHostImpl::OnRenderViewReady() {
1350 SendScreenRects();
1351 WasResized();
1354 void RenderWidgetHostImpl::OnRenderProcessGone(int status, int exit_code) {
1355 // RenderFrameHost owns a RenderWidgetHost when it needs one, in which case
1356 // it handles destruction.
1357 if (!owned_by_render_frame_host_) {
1358 // TODO(evanm): This synchronously ends up calling "delete this".
1359 // Is that really what we want in response to this message? I'm matching
1360 // previous behavior of the code here.
1361 Destroy();
1362 } else {
1363 RendererExited(static_cast<base::TerminationStatus>(status), exit_code);
1367 void RenderWidgetHostImpl::OnClose() {
1368 Shutdown();
1371 void RenderWidgetHostImpl::OnSetTooltipText(
1372 const base::string16& tooltip_text,
1373 WebTextDirection text_direction_hint) {
1374 // First, add directionality marks around tooltip text if necessary.
1375 // A naive solution would be to simply always wrap the text. However, on
1376 // windows, Unicode directional embedding characters can't be displayed on
1377 // systems that lack RTL fonts and are instead displayed as empty squares.
1379 // To get around this we only wrap the string when we deem it necessary i.e.
1380 // when the locale direction is different than the tooltip direction hint.
1382 // Currently, we use element's directionality as the tooltip direction hint.
1383 // An alternate solution would be to set the overall directionality based on
1384 // trying to detect the directionality from the tooltip text rather than the
1385 // element direction. One could argue that would be a preferable solution
1386 // but we use the current approach to match Fx & IE's behavior.
1387 base::string16 wrapped_tooltip_text = tooltip_text;
1388 if (!tooltip_text.empty()) {
1389 if (text_direction_hint == blink::WebTextDirectionLeftToRight) {
1390 // Force the tooltip to have LTR directionality.
1391 wrapped_tooltip_text =
1392 base::i18n::GetDisplayStringInLTRDirectionality(wrapped_tooltip_text);
1393 } else if (text_direction_hint == blink::WebTextDirectionRightToLeft &&
1394 !base::i18n::IsRTL()) {
1395 // Force the tooltip to have RTL directionality.
1396 base::i18n::WrapStringWithRTLFormatting(&wrapped_tooltip_text);
1399 if (GetView())
1400 view_->SetTooltipText(wrapped_tooltip_text);
1403 void RenderWidgetHostImpl::OnUpdateScreenRectsAck() {
1404 waiting_for_screen_rects_ack_ = false;
1405 if (!view_)
1406 return;
1408 if (view_->GetViewBounds() == last_view_screen_rect_ &&
1409 view_->GetBoundsInRootWindow() == last_window_screen_rect_) {
1410 return;
1413 SendScreenRects();
1416 void RenderWidgetHostImpl::OnRequestMove(const gfx::Rect& pos) {
1417 if (view_) {
1418 view_->SetBounds(pos);
1419 Send(new ViewMsg_Move_ACK(routing_id_));
1423 bool RenderWidgetHostImpl::OnSwapCompositorFrame(
1424 const IPC::Message& message) {
1425 // This trace event is used in
1426 // chrome/browser/extensions/api/cast_streaming/performance_test.cc
1427 TRACE_EVENT0("test_fps,benchmark", "OnSwapCompositorFrame");
1428 ViewHostMsg_SwapCompositorFrame::Param param;
1429 if (!ViewHostMsg_SwapCompositorFrame::Read(&message, &param))
1430 return false;
1431 scoped_ptr<cc::CompositorFrame> frame(new cc::CompositorFrame);
1432 uint32 output_surface_id = base::get<0>(param);
1433 base::get<1>(param).AssignTo(frame.get());
1434 std::vector<IPC::Message> messages_to_deliver_with_frame;
1435 messages_to_deliver_with_frame.swap(base::get<2>(param));
1437 if (!ui::LatencyInfo::Verify(frame->metadata.latency_info,
1438 "RenderWidgetHostImpl::OnSwapCompositorFrame"))
1439 return false;
1441 latency_tracker_.OnSwapCompositorFrame(&frame->metadata.latency_info);
1443 bool is_mobile_optimized = IsMobileOptimizedFrame(frame->metadata);
1444 input_router_->NotifySiteIsMobileOptimized(is_mobile_optimized);
1445 if (touch_emulator_)
1446 touch_emulator_->SetDoubleTapSupportForPageEnabled(!is_mobile_optimized);
1448 if (view_) {
1449 view_->OnSwapCompositorFrame(output_surface_id, frame.Pass());
1450 view_->DidReceiveRendererFrame();
1451 } else {
1452 cc::CompositorFrameAck ack;
1453 if (frame->gl_frame_data) {
1454 ack.gl_frame_data = frame->gl_frame_data.Pass();
1455 ack.gl_frame_data->sync_point = 0;
1456 } else if (frame->delegated_frame_data) {
1457 cc::TransferableResource::ReturnResources(
1458 frame->delegated_frame_data->resource_list,
1459 &ack.resources);
1461 SendSwapCompositorFrameAck(routing_id_, output_surface_id,
1462 process_->GetID(), ack);
1465 RenderProcessHost* rph = GetProcess();
1466 for (std::vector<IPC::Message>::const_iterator i =
1467 messages_to_deliver_with_frame.begin();
1468 i != messages_to_deliver_with_frame.end();
1469 ++i) {
1470 rph->OnMessageReceived(*i);
1471 if (i->dispatch_error())
1472 rph->OnBadMessageReceived(*i);
1474 messages_to_deliver_with_frame.clear();
1476 return true;
1479 void RenderWidgetHostImpl::OnUpdateRect(
1480 const ViewHostMsg_UpdateRect_Params& params) {
1481 TRACE_EVENT0("renderer_host", "RenderWidgetHostImpl::OnUpdateRect");
1482 TimeTicks paint_start = TimeTicks::Now();
1484 // Update our knowledge of the RenderWidget's size.
1485 current_size_ = params.view_size;
1487 bool is_resize_ack =
1488 ViewHostMsg_UpdateRect_Flags::is_resize_ack(params.flags);
1490 // resize_ack_pending_ needs to be cleared before we call DidPaintRect, since
1491 // that will end up reaching GetBackingStore.
1492 if (is_resize_ack) {
1493 DCHECK(!g_check_for_pending_resize_ack || resize_ack_pending_);
1494 resize_ack_pending_ = false;
1497 bool is_repaint_ack =
1498 ViewHostMsg_UpdateRect_Flags::is_repaint_ack(params.flags);
1499 if (is_repaint_ack) {
1500 DCHECK(repaint_ack_pending_);
1501 TRACE_EVENT_ASYNC_END0(
1502 "renderer_host", "RenderWidgetHostImpl::repaint_ack_pending_", this);
1503 repaint_ack_pending_ = false;
1504 TimeDelta delta = TimeTicks::Now() - repaint_start_time_;
1505 UMA_HISTOGRAM_TIMES("MPArch.RWH_RepaintDelta", delta);
1508 DCHECK(!params.view_size.IsEmpty());
1510 DidUpdateBackingStore(params, paint_start);
1512 if (auto_resize_enabled_) {
1513 bool post_callback = new_auto_size_.IsEmpty();
1514 new_auto_size_ = params.view_size;
1515 if (post_callback) {
1516 base::ThreadTaskRunnerHandle::Get()->PostTask(
1517 FROM_HERE, base::Bind(&RenderWidgetHostImpl::DelayedAutoResized,
1518 weak_factory_.GetWeakPtr()));
1522 // Log the time delta for processing a paint message. On platforms that don't
1523 // support asynchronous painting, this is equivalent to
1524 // MPArch.RWH_TotalPaintTime.
1525 TimeDelta delta = TimeTicks::Now() - paint_start;
1526 UMA_HISTOGRAM_TIMES("MPArch.RWH_OnMsgUpdateRect", delta);
1529 void RenderWidgetHostImpl::DidUpdateBackingStore(
1530 const ViewHostMsg_UpdateRect_Params& params,
1531 const TimeTicks& paint_start) {
1532 TRACE_EVENT0("renderer_host", "RenderWidgetHostImpl::DidUpdateBackingStore");
1533 TimeTicks update_start = TimeTicks::Now();
1535 // Move the plugins if the view hasn't already been destroyed. Plugin moves
1536 // will not be re-issued, so must move them now, regardless of whether we
1537 // paint or not. MovePluginWindows attempts to move the plugin windows and
1538 // in the process could dispatch other window messages which could cause the
1539 // view to be destroyed.
1540 if (view_)
1541 view_->MovePluginWindows(params.plugin_window_moves);
1543 NotificationService::current()->Notify(
1544 NOTIFICATION_RENDER_WIDGET_HOST_DID_UPDATE_BACKING_STORE,
1545 Source<RenderWidgetHost>(this),
1546 NotificationService::NoDetails());
1548 // We don't need to update the view if the view is hidden. We must do this
1549 // early return after the ACK is sent, however, or the renderer will not send
1550 // us more data.
1551 if (is_hidden_)
1552 return;
1554 // If we got a resize ack, then perhaps we have another resize to send?
1555 bool is_resize_ack =
1556 ViewHostMsg_UpdateRect_Flags::is_resize_ack(params.flags);
1557 if (is_resize_ack)
1558 WasResized();
1560 // Log the time delta for processing a paint message.
1561 TimeTicks now = TimeTicks::Now();
1562 TimeDelta delta = now - update_start;
1563 UMA_HISTOGRAM_TIMES("MPArch.RWH_DidUpdateBackingStore", delta);
1566 void RenderWidgetHostImpl::OnQueueSyntheticGesture(
1567 const SyntheticGesturePacket& gesture_packet) {
1568 // Only allow untrustworthy gestures if explicitly enabled.
1569 if (!base::CommandLine::ForCurrentProcess()->HasSwitch(
1570 cc::switches::kEnableGpuBenchmarking)) {
1571 bad_message::ReceivedBadMessage(GetProcess(),
1572 bad_message::RWH_SYNTHETIC_GESTURE);
1573 return;
1576 QueueSyntheticGesture(
1577 SyntheticGesture::Create(*gesture_packet.gesture_params()),
1578 base::Bind(&RenderWidgetHostImpl::OnSyntheticGestureCompleted,
1579 weak_factory_.GetWeakPtr()));
1582 void RenderWidgetHostImpl::OnFocus() {
1583 // Only RenderViewHost can deal with that message.
1584 bad_message::ReceivedBadMessage(GetProcess(), bad_message::RWH_FOCUS);
1587 void RenderWidgetHostImpl::OnBlur() {
1588 // Only RenderViewHost can deal with that message.
1589 bad_message::ReceivedBadMessage(GetProcess(), bad_message::RWH_BLUR);
1592 void RenderWidgetHostImpl::OnSetCursor(const WebCursor& cursor) {
1593 SetCursor(cursor);
1596 void RenderWidgetHostImpl::SetTouchEventEmulationEnabled(
1597 bool enabled, ui::GestureProviderConfigType config_type) {
1598 if (enabled) {
1599 if (!touch_emulator_) {
1600 touch_emulator_.reset(new TouchEmulator(
1601 this, view_ ? content::GetScaleFactorForView(view_) : 1.0f));
1603 touch_emulator_->Enable(config_type);
1604 } else {
1605 if (touch_emulator_)
1606 touch_emulator_->Disable();
1610 void RenderWidgetHostImpl::OnTextInputStateChanged(
1611 const ViewHostMsg_TextInputState_Params& params) {
1612 if (view_)
1613 view_->TextInputStateChanged(params);
1616 void RenderWidgetHostImpl::OnImeCompositionRangeChanged(
1617 const gfx::Range& range,
1618 const std::vector<gfx::Rect>& character_bounds) {
1619 if (view_)
1620 view_->ImeCompositionRangeChanged(range, character_bounds);
1623 void RenderWidgetHostImpl::OnImeCancelComposition() {
1624 if (view_)
1625 view_->ImeCancelComposition();
1628 void RenderWidgetHostImpl::OnLockMouse(bool user_gesture,
1629 bool last_unlocked_by_target,
1630 bool privileged) {
1632 if (pending_mouse_lock_request_) {
1633 Send(new ViewMsg_LockMouse_ACK(routing_id_, false));
1634 return;
1635 } else if (IsMouseLocked()) {
1636 Send(new ViewMsg_LockMouse_ACK(routing_id_, true));
1637 return;
1640 pending_mouse_lock_request_ = true;
1641 if (privileged && allow_privileged_mouse_lock_) {
1642 // Directly approve to lock the mouse.
1643 GotResponseToLockMouseRequest(true);
1644 } else {
1645 RequestToLockMouse(user_gesture, last_unlocked_by_target);
1649 void RenderWidgetHostImpl::OnUnlockMouse() {
1650 RejectMouseLockOrUnlockIfNecessary();
1653 void RenderWidgetHostImpl::OnShowDisambiguationPopup(
1654 const gfx::Rect& rect_pixels,
1655 const gfx::Size& size,
1656 const cc::SharedBitmapId& id) {
1657 DCHECK(!rect_pixels.IsEmpty());
1658 DCHECK(!size.IsEmpty());
1660 scoped_ptr<cc::SharedBitmap> bitmap =
1661 HostSharedBitmapManager::current()->GetSharedBitmapFromId(size, id);
1662 if (!bitmap) {
1663 bad_message::ReceivedBadMessage(GetProcess(),
1664 bad_message::RWH_SHARED_BITMAP);
1665 return;
1668 DCHECK(bitmap->pixels());
1670 SkImageInfo info = SkImageInfo::MakeN32Premul(size.width(), size.height());
1671 SkBitmap zoomed_bitmap;
1672 zoomed_bitmap.installPixels(info, bitmap->pixels(), info.minRowBytes());
1674 // Note that |rect| is in coordinates of pixels relative to the window origin.
1675 // Aura-based systems will want to convert this to DIPs.
1676 if (view_)
1677 view_->ShowDisambiguationPopup(rect_pixels, zoomed_bitmap);
1679 // It is assumed that the disambiguation popup will make a copy of the
1680 // provided zoomed image, so we delete this one.
1681 zoomed_bitmap.setPixels(0);
1682 Send(new ViewMsg_ReleaseDisambiguationPopupBitmap(GetRoutingID(), id));
1685 #if defined(OS_WIN)
1686 void RenderWidgetHostImpl::OnWindowlessPluginDummyWindowCreated(
1687 gfx::NativeViewId dummy_activation_window) {
1688 HWND hwnd = reinterpret_cast<HWND>(dummy_activation_window);
1690 // This may happen as a result of a race condition when the plugin is going
1691 // away.
1692 wchar_t window_title[MAX_PATH + 1] = {0};
1693 if (!IsWindow(hwnd) ||
1694 !GetWindowText(hwnd, window_title, arraysize(window_title)) ||
1695 lstrcmpiW(window_title, kDummyActivationWindowName) != 0) {
1696 return;
1699 #if defined(USE_AURA)
1700 SetParent(hwnd,
1701 reinterpret_cast<HWND>(view_->GetParentForWindowlessPlugin()));
1702 #else
1703 SetParent(hwnd, reinterpret_cast<HWND>(GetNativeViewId()));
1704 #endif
1705 dummy_windows_for_activation_.push_back(hwnd);
1708 void RenderWidgetHostImpl::OnWindowlessPluginDummyWindowDestroyed(
1709 gfx::NativeViewId dummy_activation_window) {
1710 HWND hwnd = reinterpret_cast<HWND>(dummy_activation_window);
1711 std::list<HWND>::iterator i = dummy_windows_for_activation_.begin();
1712 for (; i != dummy_windows_for_activation_.end(); ++i) {
1713 if ((*i) == hwnd) {
1714 dummy_windows_for_activation_.erase(i);
1715 return;
1718 NOTREACHED() << "Unknown dummy window";
1720 #endif
1722 void RenderWidgetHostImpl::SetIgnoreInputEvents(bool ignore_input_events) {
1723 ignore_input_events_ = ignore_input_events;
1726 bool RenderWidgetHostImpl::KeyPressListenersHandleEvent(
1727 const NativeWebKeyboardEvent& event) {
1728 if (event.skip_in_browser || event.type != WebKeyboardEvent::RawKeyDown)
1729 return false;
1731 for (size_t i = 0; i < key_press_event_callbacks_.size(); i++) {
1732 size_t original_size = key_press_event_callbacks_.size();
1733 if (key_press_event_callbacks_[i].Run(event))
1734 return true;
1736 // Check whether the callback that just ran removed itself, in which case
1737 // the iterator needs to be decremented to properly account for the removal.
1738 size_t current_size = key_press_event_callbacks_.size();
1739 if (current_size != original_size) {
1740 DCHECK_EQ(original_size - 1, current_size);
1741 --i;
1745 return false;
1748 InputEventAckState RenderWidgetHostImpl::FilterInputEvent(
1749 const blink::WebInputEvent& event, const ui::LatencyInfo& latency_info) {
1750 // Don't ignore touch cancel events, since they may be sent while input
1751 // events are being ignored in order to keep the renderer from getting
1752 // confused about how many touches are active.
1753 if (IgnoreInputEvents() && event.type != WebInputEvent::TouchCancel)
1754 return INPUT_EVENT_ACK_STATE_NO_CONSUMER_EXISTS;
1756 if (!process_->HasConnection())
1757 return INPUT_EVENT_ACK_STATE_UNKNOWN;
1759 if (event.type == WebInputEvent::MouseDown ||
1760 event.type == WebInputEvent::GestureTapDown) {
1761 OnUserGesture();
1764 return view_ ? view_->FilterInputEvent(event)
1765 : INPUT_EVENT_ACK_STATE_NOT_CONSUMED;
1768 void RenderWidgetHostImpl::IncrementInFlightEventCount() {
1769 increment_in_flight_event_count();
1770 if (!is_hidden_)
1771 StartHangMonitorTimeout(hung_renderer_delay_);
1774 void RenderWidgetHostImpl::DecrementInFlightEventCount() {
1775 if (decrement_in_flight_event_count() <= 0) {
1776 // Cancel pending hung renderer checks since the renderer is responsive.
1777 StopHangMonitorTimeout();
1778 } else {
1779 // The renderer is responsive, but there are in-flight events to wait for.
1780 if (!is_hidden_)
1781 RestartHangMonitorTimeout();
1785 void RenderWidgetHostImpl::OnHasTouchEventHandlers(bool has_handlers) {
1786 has_touch_handler_ = has_handlers;
1789 void RenderWidgetHostImpl::DidFlush() {
1790 if (synthetic_gesture_controller_)
1791 synthetic_gesture_controller_->OnDidFlushInput();
1794 void RenderWidgetHostImpl::DidOverscroll(const DidOverscrollParams& params) {
1795 if (view_)
1796 view_->DidOverscroll(params);
1799 void RenderWidgetHostImpl::DidStopFlinging() {
1800 if (view_)
1801 view_->DidStopFlinging();
1804 void RenderWidgetHostImpl::OnKeyboardEventAck(
1805 const NativeWebKeyboardEventWithLatencyInfo& event,
1806 InputEventAckState ack_result) {
1807 latency_tracker_.OnInputEventAck(event.event, &event.latency);
1809 #if defined(OS_MACOSX)
1810 if (!is_hidden() && view_ && view_->PostProcessEventForPluginIme(event.event))
1811 return;
1812 #endif
1814 // We only send unprocessed key event upwards if we are not hidden,
1815 // because the user has moved away from us and no longer expect any effect
1816 // of this key event.
1817 const bool processed = (INPUT_EVENT_ACK_STATE_CONSUMED == ack_result);
1818 if (delegate_ && !processed && !is_hidden() && !event.event.skip_in_browser) {
1819 delegate_->HandleKeyboardEvent(event.event);
1821 // WARNING: This RenderWidgetHostImpl can be deallocated at this point
1822 // (i.e. in the case of Ctrl+W, where the call to
1823 // HandleKeyboardEvent destroys this RenderWidgetHostImpl).
1827 void RenderWidgetHostImpl::OnMouseEventAck(
1828 const MouseEventWithLatencyInfo& mouse_event,
1829 InputEventAckState ack_result) {
1830 latency_tracker_.OnInputEventAck(mouse_event.event, &mouse_event.latency);
1833 void RenderWidgetHostImpl::OnWheelEventAck(
1834 const MouseWheelEventWithLatencyInfo& wheel_event,
1835 InputEventAckState ack_result) {
1836 latency_tracker_.OnInputEventAck(wheel_event.event, &wheel_event.latency);
1838 if (!is_hidden() && view_) {
1839 if (ack_result != INPUT_EVENT_ACK_STATE_CONSUMED &&
1840 delegate_->HandleWheelEvent(wheel_event.event)) {
1841 ack_result = INPUT_EVENT_ACK_STATE_CONSUMED;
1843 view_->WheelEventAck(wheel_event.event, ack_result);
1847 void RenderWidgetHostImpl::OnGestureEventAck(
1848 const GestureEventWithLatencyInfo& event,
1849 InputEventAckState ack_result) {
1850 latency_tracker_.OnInputEventAck(event.event, &event.latency);
1852 if (view_)
1853 view_->GestureEventAck(event.event, ack_result);
1856 void RenderWidgetHostImpl::OnTouchEventAck(
1857 const TouchEventWithLatencyInfo& event,
1858 InputEventAckState ack_result) {
1859 latency_tracker_.OnInputEventAck(event.event, &event.latency);
1861 if (touch_emulator_ &&
1862 touch_emulator_->HandleTouchEventAck(event.event, ack_result)) {
1863 return;
1866 if (view_)
1867 view_->ProcessAckedTouchEvent(event, ack_result);
1870 void RenderWidgetHostImpl::OnUnexpectedEventAck(UnexpectedEventAckType type) {
1871 if (type == BAD_ACK_MESSAGE) {
1872 bad_message::ReceivedBadMessage(process_, bad_message::RWH_BAD_ACK_MESSAGE);
1873 } else if (type == UNEXPECTED_EVENT_TYPE) {
1874 suppress_next_char_events_ = false;
1878 void RenderWidgetHostImpl::OnSyntheticGestureCompleted(
1879 SyntheticGesture::Result result) {
1880 Send(new InputMsg_SyntheticGestureCompleted(GetRoutingID()));
1883 bool RenderWidgetHostImpl::IgnoreInputEvents() const {
1884 return ignore_input_events_ || process_->IgnoreInputEvents();
1887 void RenderWidgetHostImpl::StartUserGesture() {
1888 OnUserGesture();
1891 void RenderWidgetHostImpl::SetBackgroundOpaque(bool opaque) {
1892 Send(new ViewMsg_SetBackgroundOpaque(GetRoutingID(), opaque));
1895 void RenderWidgetHostImpl::SetEditCommandsForNextKeyEvent(
1896 const std::vector<EditCommand>& commands) {
1897 Send(new InputMsg_SetEditCommandsForNextKeyEvent(GetRoutingID(), commands));
1900 void RenderWidgetHostImpl::ExecuteEditCommand(const std::string& command,
1901 const std::string& value) {
1902 Send(new InputMsg_ExecuteEditCommand(GetRoutingID(), command, value));
1905 void RenderWidgetHostImpl::ScrollFocusedEditableNodeIntoRect(
1906 const gfx::Rect& rect) {
1907 Send(new InputMsg_ScrollFocusedEditableNodeIntoRect(GetRoutingID(), rect));
1910 void RenderWidgetHostImpl::MoveCaret(const gfx::Point& point) {
1911 Send(new InputMsg_MoveCaret(GetRoutingID(), point));
1914 bool RenderWidgetHostImpl::GotResponseToLockMouseRequest(bool allowed) {
1915 if (!allowed) {
1916 RejectMouseLockOrUnlockIfNecessary();
1917 return false;
1918 } else {
1919 if (!pending_mouse_lock_request_) {
1920 // This is possible, e.g., the plugin sends us an unlock request before
1921 // the user allows to lock to mouse.
1922 return false;
1925 pending_mouse_lock_request_ = false;
1926 if (!view_ || !view_->HasFocus()|| !view_->LockMouse()) {
1927 Send(new ViewMsg_LockMouse_ACK(routing_id_, false));
1928 return false;
1929 } else {
1930 Send(new ViewMsg_LockMouse_ACK(routing_id_, true));
1931 return true;
1936 // static
1937 void RenderWidgetHostImpl::SendSwapCompositorFrameAck(
1938 int32 route_id,
1939 uint32 output_surface_id,
1940 int renderer_host_id,
1941 const cc::CompositorFrameAck& ack) {
1942 RenderProcessHost* host = RenderProcessHost::FromID(renderer_host_id);
1943 if (!host)
1944 return;
1945 host->Send(new ViewMsg_SwapCompositorFrameAck(
1946 route_id, output_surface_id, ack));
1949 // static
1950 void RenderWidgetHostImpl::SendReclaimCompositorResources(
1951 int32 route_id,
1952 uint32 output_surface_id,
1953 int renderer_host_id,
1954 const cc::CompositorFrameAck& ack) {
1955 RenderProcessHost* host = RenderProcessHost::FromID(renderer_host_id);
1956 if (!host)
1957 return;
1958 host->Send(
1959 new ViewMsg_ReclaimCompositorResources(route_id, output_surface_id, ack));
1962 void RenderWidgetHostImpl::DelayedAutoResized() {
1963 gfx::Size new_size = new_auto_size_;
1964 // Clear the new_auto_size_ since the empty value is used as a flag to
1965 // indicate that no callback is in progress (i.e. without this line
1966 // DelayedAutoResized will not get called again).
1967 new_auto_size_.SetSize(0, 0);
1968 if (!auto_resize_enabled_)
1969 return;
1971 OnRenderAutoResized(new_size);
1974 void RenderWidgetHostImpl::DetachDelegate() {
1975 delegate_ = NULL;
1978 void RenderWidgetHostImpl::FrameSwapped(const ui::LatencyInfo& latency_info) {
1979 ui::LatencyInfo::LatencyComponent window_snapshot_component;
1980 if (latency_info.FindLatency(ui::WINDOW_SNAPSHOT_FRAME_NUMBER_COMPONENT,
1981 GetLatencyComponentId(),
1982 &window_snapshot_component)) {
1983 int sequence_number = static_cast<int>(
1984 window_snapshot_component.sequence_number);
1985 #if defined(OS_MACOSX)
1986 // On Mac, when using CoreAnmation, there is a delay between when content
1987 // is drawn to the screen, and when the snapshot will actually pick up
1988 // that content. Insert a manual delay of 1/6th of a second (to simulate
1989 // 10 frames at 60 fps) before actually taking the snapshot.
1990 base::MessageLoop::current()->PostDelayedTask(
1991 FROM_HERE,
1992 base::Bind(&RenderWidgetHostImpl::WindowSnapshotReachedScreen,
1993 weak_factory_.GetWeakPtr(),
1994 sequence_number),
1995 base::TimeDelta::FromSecondsD(1. / 6));
1996 #else
1997 WindowSnapshotReachedScreen(sequence_number);
1998 #endif
2001 latency_tracker_.OnFrameSwapped(latency_info);
2004 void RenderWidgetHostImpl::DidReceiveRendererFrame() {
2005 view_->DidReceiveRendererFrame();
2008 void RenderWidgetHostImpl::WindowSnapshotReachedScreen(int snapshot_id) {
2009 DCHECK(base::MessageLoopForUI::IsCurrent());
2011 gfx::Rect view_bounds = GetView()->GetViewBounds();
2012 gfx::Rect snapshot_bounds(view_bounds.size());
2014 std::vector<unsigned char> png;
2015 if (ui::GrabViewSnapshot(
2016 GetView()->GetNativeView(), &png, snapshot_bounds)) {
2017 OnSnapshotDataReceived(snapshot_id, &png.front(), png.size());
2018 return;
2021 ui::GrabViewSnapshotAsync(
2022 GetView()->GetNativeView(),
2023 snapshot_bounds,
2024 base::ThreadTaskRunnerHandle::Get(),
2025 base::Bind(&RenderWidgetHostImpl::OnSnapshotDataReceivedAsync,
2026 weak_factory_.GetWeakPtr(),
2027 snapshot_id));
2030 void RenderWidgetHostImpl::OnSnapshotDataReceived(int snapshot_id,
2031 const unsigned char* data,
2032 size_t size) {
2033 // Any pending snapshots with a lower ID than the one received are considered
2034 // to be implicitly complete, and returned the same snapshot data.
2035 PendingSnapshotMap::iterator it = pending_browser_snapshots_.begin();
2036 while(it != pending_browser_snapshots_.end()) {
2037 if (it->first <= snapshot_id) {
2038 it->second.Run(data, size);
2039 pending_browser_snapshots_.erase(it++);
2040 } else {
2041 ++it;
2046 void RenderWidgetHostImpl::OnSnapshotDataReceivedAsync(
2047 int snapshot_id,
2048 scoped_refptr<base::RefCountedBytes> png_data) {
2049 if (png_data.get())
2050 OnSnapshotDataReceived(snapshot_id, png_data->front(), png_data->size());
2051 else
2052 OnSnapshotDataReceived(snapshot_id, NULL, 0);
2055 // static
2056 void RenderWidgetHostImpl::CompositorFrameDrawn(
2057 const std::vector<ui::LatencyInfo>& latency_info) {
2058 for (size_t i = 0; i < latency_info.size(); i++) {
2059 std::set<RenderWidgetHostImpl*> rwhi_set;
2060 for (const auto& lc : latency_info[i].latency_components()) {
2061 if (lc.first.first == ui::INPUT_EVENT_LATENCY_BEGIN_RWH_COMPONENT ||
2062 lc.first.first == ui::WINDOW_SNAPSHOT_FRAME_NUMBER_COMPONENT ||
2063 lc.first.first == ui::TAB_SHOW_COMPONENT) {
2064 // Matches with GetLatencyComponentId
2065 int routing_id = lc.first.second & 0xffffffff;
2066 int process_id = (lc.first.second >> 32) & 0xffffffff;
2067 RenderWidgetHost* rwh =
2068 RenderWidgetHost::FromID(process_id, routing_id);
2069 if (!rwh) {
2070 continue;
2072 RenderWidgetHostImpl* rwhi = RenderWidgetHostImpl::From(rwh);
2073 if (rwhi_set.insert(rwhi).second)
2074 rwhi->FrameSwapped(latency_info[i]);
2080 BrowserAccessibilityManager*
2081 RenderWidgetHostImpl::GetRootBrowserAccessibilityManager() {
2082 return delegate_ ? delegate_->GetRootBrowserAccessibilityManager() : NULL;
2085 BrowserAccessibilityManager*
2086 RenderWidgetHostImpl::GetOrCreateRootBrowserAccessibilityManager() {
2087 return delegate_ ?
2088 delegate_->GetOrCreateRootBrowserAccessibilityManager() : NULL;
2091 #if defined(OS_WIN)
2092 gfx::NativeViewAccessible
2093 RenderWidgetHostImpl::GetParentNativeViewAccessible() {
2094 return delegate_ ? delegate_->GetParentNativeViewAccessible() : NULL;
2096 #endif
2098 } // namespace content