DevTools: cut host and port from webSocketDebuggerUrl in addition to ws:// prefix
[chromium-blink-merge.git] / content / browser / renderer_host / render_widget_host_impl.cc
blob314f785dfa23d0929dc9b95e409da2a3951ff162
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 input_method_active_(false),
166 text_direction_updated_(false),
167 text_direction_(blink::WebTextDirectionLeftToRight),
168 text_direction_canceled_(false),
169 suppress_next_char_events_(false),
170 pending_mouse_lock_request_(false),
171 allow_privileged_mouse_lock_(false),
172 has_touch_handler_(false),
173 next_browser_snapshot_id_(1),
174 owned_by_render_frame_host_(false),
175 is_focused_(false),
176 weak_factory_(this) {
177 CHECK(delegate_);
178 if (routing_id_ == MSG_ROUTING_NONE) {
179 routing_id_ = process_->GetNextRoutingID();
180 surface_id_ = GpuSurfaceTracker::Get()->AddSurfaceForRenderer(
181 process_->GetID(),
182 routing_id_);
183 } else {
184 // TODO(piman): This is a O(N) lookup, where we could forward the
185 // information from the RenderWidgetHelper. The problem is that doing so
186 // currently leaks outside of content all the way to chrome classes, and
187 // would be a layering violation. Since we don't expect more than a few
188 // hundreds of RWH, this seems acceptable. Revisit if performance become a
189 // problem, for example by tracking in the RenderWidgetHelper the routing id
190 // (and surface id) that have been created, but whose RWH haven't yet.
191 surface_id_ = GpuSurfaceTracker::Get()->LookupSurfaceForRenderer(
192 process_->GetID(),
193 routing_id_);
194 DCHECK(surface_id_);
197 std::pair<RoutingIDWidgetMap::iterator, bool> result =
198 g_routing_id_widget_map.Get().insert(std::make_pair(
199 RenderWidgetHostID(process->GetID(), routing_id_), this));
200 CHECK(result.second) << "Inserting a duplicate item!";
201 process_->AddRoute(routing_id_, this);
203 // If we're initially visible, tell the process host that we're alive.
204 // Otherwise we'll notify the process host when we are first shown.
205 if (!hidden)
206 process_->WidgetRestored();
208 latency_tracker_.Initialize(routing_id_, GetProcess()->GetID());
210 input_router_.reset(new InputRouterImpl(
211 process_, this, this, routing_id_, GetInputRouterConfigForPlatform()));
213 touch_emulator_.reset();
215 RenderViewHostImpl* rvh = static_cast<RenderViewHostImpl*>(
216 IsRenderView() ? RenderViewHost::From(this) : NULL);
217 if (BrowserPluginGuest::IsGuest(rvh) ||
218 !base::CommandLine::ForCurrentProcess()->HasSwitch(
219 switches::kDisableHangMonitor)) {
220 hang_monitor_timeout_.reset(new TimeoutMonitor(
221 base::Bind(&RenderWidgetHostImpl::RendererIsUnresponsive,
222 weak_factory_.GetWeakPtr())));
226 RenderWidgetHostImpl::~RenderWidgetHostImpl() {
227 if (view_weak_)
228 view_weak_->RenderWidgetHostGone();
229 SetView(NULL);
231 GpuSurfaceTracker::Get()->RemoveSurface(surface_id_);
232 surface_id_ = 0;
234 process_->RemoveRoute(routing_id_);
235 g_routing_id_widget_map.Get().erase(
236 RenderWidgetHostID(process_->GetID(), routing_id_));
238 if (delegate_)
239 delegate_->RenderWidgetDeleted(this);
242 // static
243 RenderWidgetHost* RenderWidgetHost::FromID(
244 int32 process_id,
245 int32 routing_id) {
246 return RenderWidgetHostImpl::FromID(process_id, routing_id);
249 // static
250 RenderWidgetHostImpl* RenderWidgetHostImpl::FromID(
251 int32 process_id,
252 int32 routing_id) {
253 DCHECK_CURRENTLY_ON(BrowserThread::UI);
254 RoutingIDWidgetMap* widgets = g_routing_id_widget_map.Pointer();
255 RoutingIDWidgetMap::iterator it = widgets->find(
256 RenderWidgetHostID(process_id, routing_id));
257 return it == widgets->end() ? NULL : it->second;
260 // static
261 scoped_ptr<RenderWidgetHostIterator> RenderWidgetHost::GetRenderWidgetHosts() {
262 RenderWidgetHostIteratorImpl* hosts = new RenderWidgetHostIteratorImpl();
263 RoutingIDWidgetMap* widgets = g_routing_id_widget_map.Pointer();
264 for (RoutingIDWidgetMap::const_iterator it = widgets->begin();
265 it != widgets->end();
266 ++it) {
267 RenderWidgetHost* widget = it->second;
269 if (!widget->IsRenderView()) {
270 hosts->Add(widget);
271 continue;
274 // Add only active RenderViewHosts.
275 RenderViewHost* rvh = RenderViewHost::From(widget);
276 if (static_cast<RenderViewHostImpl*>(rvh)->is_active())
277 hosts->Add(widget);
280 return scoped_ptr<RenderWidgetHostIterator>(hosts);
283 // static
284 scoped_ptr<RenderWidgetHostIterator>
285 RenderWidgetHostImpl::GetAllRenderWidgetHosts() {
286 RenderWidgetHostIteratorImpl* hosts = new RenderWidgetHostIteratorImpl();
287 RoutingIDWidgetMap* widgets = g_routing_id_widget_map.Pointer();
288 for (RoutingIDWidgetMap::const_iterator it = widgets->begin();
289 it != widgets->end();
290 ++it) {
291 hosts->Add(it->second);
294 return scoped_ptr<RenderWidgetHostIterator>(hosts);
297 // static
298 RenderWidgetHostImpl* RenderWidgetHostImpl::From(RenderWidgetHost* rwh) {
299 return rwh->AsRenderWidgetHostImpl();
302 void RenderWidgetHostImpl::SetView(RenderWidgetHostViewBase* view) {
303 if (view)
304 view_weak_ = view->GetWeakPtr();
305 else
306 view_weak_.reset();
307 view_ = view;
309 // If the renderer has not yet been initialized, then the surface ID
310 // namespace will be sent during initialization.
311 if (view_ && renderer_initialized_) {
312 Send(new ViewMsg_SetSurfaceIdNamespace(routing_id_,
313 view_->GetSurfaceIdNamespace()));
316 GpuSurfaceTracker::Get()->SetSurfaceHandle(
317 surface_id_, GetCompositingSurface());
319 synthetic_gesture_controller_.reset();
322 RenderProcessHost* RenderWidgetHostImpl::GetProcess() const {
323 return process_;
326 int RenderWidgetHostImpl::GetRoutingID() const {
327 return routing_id_;
330 RenderWidgetHostView* RenderWidgetHostImpl::GetView() const {
331 return view_;
334 RenderWidgetHostImpl* RenderWidgetHostImpl::AsRenderWidgetHostImpl() {
335 return this;
338 gfx::NativeViewId RenderWidgetHostImpl::GetNativeViewId() const {
339 if (view_)
340 return view_->GetNativeViewId();
341 return 0;
344 gfx::GLSurfaceHandle RenderWidgetHostImpl::GetCompositingSurface() {
345 if (view_)
346 return view_->GetCompositingSurface();
347 return gfx::GLSurfaceHandle();
350 void RenderWidgetHostImpl::ResetSizeAndRepaintPendingFlags() {
351 resize_ack_pending_ = false;
352 if (repaint_ack_pending_) {
353 TRACE_EVENT_ASYNC_END0(
354 "renderer_host", "RenderWidgetHostImpl::repaint_ack_pending_", this);
356 repaint_ack_pending_ = false;
357 if (old_resize_params_)
358 old_resize_params_->new_size = gfx::Size();
361 void RenderWidgetHostImpl::SendScreenRects() {
362 if (!renderer_initialized_ || waiting_for_screen_rects_ack_)
363 return;
365 if (is_hidden_) {
366 // On GTK, this comes in for backgrounded tabs. Ignore, to match what
367 // happens on Win & Mac, and when the view is shown it'll call this again.
368 return;
371 if (!view_)
372 return;
374 last_view_screen_rect_ = view_->GetViewBounds();
375 last_window_screen_rect_ = view_->GetBoundsInRootWindow();
376 Send(new ViewMsg_UpdateScreenRects(
377 GetRoutingID(), last_view_screen_rect_, last_window_screen_rect_));
378 if (delegate_)
379 delegate_->DidSendScreenRects(this);
380 waiting_for_screen_rects_ack_ = true;
383 void RenderWidgetHostImpl::SuppressNextCharEvents() {
384 suppress_next_char_events_ = true;
387 void RenderWidgetHostImpl::FlushInput() {
388 input_router_->RequestNotificationWhenFlushed();
389 if (synthetic_gesture_controller_)
390 synthetic_gesture_controller_->Flush(base::TimeTicks::Now());
393 void RenderWidgetHostImpl::SetNeedsFlush() {
394 if (view_)
395 view_->OnSetNeedsFlushInput();
398 void RenderWidgetHostImpl::Init() {
399 DCHECK(process_->HasConnection());
401 renderer_initialized_ = true;
403 GpuSurfaceTracker::Get()->SetSurfaceHandle(
404 surface_id_, GetCompositingSurface());
406 // Send the ack along with the information on placement.
407 Send(new ViewMsg_CreatingNew_ACK(routing_id_));
408 GetProcess()->ResumeRequestsForView(routing_id_);
410 // If the RWHV has not yet been set, the surface ID namespace will get
411 // passed down by the call to SetView().
412 if (view_) {
413 Send(new ViewMsg_SetSurfaceIdNamespace(routing_id_,
414 view_->GetSurfaceIdNamespace()));
417 WasResized();
420 void RenderWidgetHostImpl::InitForFrame() {
421 DCHECK(process_->HasConnection());
422 renderer_initialized_ = true;
425 void RenderWidgetHostImpl::Shutdown() {
426 RejectMouseLockOrUnlockIfNecessary();
428 if (process_->HasConnection()) {
429 // Tell the renderer object to close.
430 bool rv = Send(new ViewMsg_Close(routing_id_));
431 DCHECK(rv);
434 Destroy();
437 bool RenderWidgetHostImpl::IsLoading() const {
438 return is_loading_;
441 bool RenderWidgetHostImpl::IsRenderView() const {
442 return false;
445 bool RenderWidgetHostImpl::OnMessageReceived(const IPC::Message &msg) {
446 bool handled = true;
447 IPC_BEGIN_MESSAGE_MAP(RenderWidgetHostImpl, msg)
448 IPC_MESSAGE_HANDLER(FrameHostMsg_RenderProcessGone, OnRenderProcessGone)
449 IPC_MESSAGE_HANDLER(InputHostMsg_QueueSyntheticGesture,
450 OnQueueSyntheticGesture)
451 IPC_MESSAGE_HANDLER(InputHostMsg_ImeCancelComposition,
452 OnImeCancelComposition)
453 IPC_MESSAGE_HANDLER(ViewHostMsg_RenderViewReady, OnRenderViewReady)
454 IPC_MESSAGE_HANDLER(ViewHostMsg_Close, OnClose)
455 IPC_MESSAGE_HANDLER(ViewHostMsg_UpdateScreenRects_ACK,
456 OnUpdateScreenRectsAck)
457 IPC_MESSAGE_HANDLER(ViewHostMsg_RequestMove, OnRequestMove)
458 IPC_MESSAGE_HANDLER(ViewHostMsg_SetTooltipText, OnSetTooltipText)
459 IPC_MESSAGE_HANDLER_GENERIC(ViewHostMsg_SwapCompositorFrame,
460 OnSwapCompositorFrame(msg))
461 IPC_MESSAGE_HANDLER(ViewHostMsg_UpdateRect, OnUpdateRect)
462 IPC_MESSAGE_HANDLER(ViewHostMsg_Focus, OnFocus)
463 IPC_MESSAGE_HANDLER(ViewHostMsg_Blur, OnBlur)
464 IPC_MESSAGE_HANDLER(ViewHostMsg_SetCursor, OnSetCursor)
465 IPC_MESSAGE_HANDLER(ViewHostMsg_TextInputTypeChanged,
466 OnTextInputTypeChanged)
467 IPC_MESSAGE_HANDLER(ViewHostMsg_LockMouse, OnLockMouse)
468 IPC_MESSAGE_HANDLER(ViewHostMsg_UnlockMouse, OnUnlockMouse)
469 IPC_MESSAGE_HANDLER(ViewHostMsg_ShowDisambiguationPopup,
470 OnShowDisambiguationPopup)
471 IPC_MESSAGE_HANDLER(ViewHostMsg_SelectionChanged, OnSelectionChanged)
472 IPC_MESSAGE_HANDLER(ViewHostMsg_SelectionBoundsChanged,
473 OnSelectionBoundsChanged)
474 #if defined(OS_WIN)
475 IPC_MESSAGE_HANDLER(ViewHostMsg_WindowlessPluginDummyWindowCreated,
476 OnWindowlessPluginDummyWindowCreated)
477 IPC_MESSAGE_HANDLER(ViewHostMsg_WindowlessPluginDummyWindowDestroyed,
478 OnWindowlessPluginDummyWindowDestroyed)
479 #endif
480 IPC_MESSAGE_HANDLER(InputHostMsg_ImeCompositionRangeChanged,
481 OnImeCompositionRangeChanged)
482 IPC_MESSAGE_UNHANDLED(handled = false)
483 IPC_END_MESSAGE_MAP()
485 if (!handled && input_router_ && input_router_->OnMessageReceived(msg))
486 return true;
488 if (!handled && view_ && view_->OnMessageReceived(msg))
489 return true;
491 return handled;
494 bool RenderWidgetHostImpl::Send(IPC::Message* msg) {
495 if (IPC_MESSAGE_ID_CLASS(msg->type()) == InputMsgStart)
496 return input_router_->SendInput(make_scoped_ptr(msg));
498 return process_->Send(msg);
501 void RenderWidgetHostImpl::SetIsLoading(bool is_loading) {
502 is_loading_ = is_loading;
503 if (!view_)
504 return;
505 view_->SetIsLoading(is_loading);
508 void RenderWidgetHostImpl::WasHidden() {
509 if (is_hidden_)
510 return;
512 TRACE_EVENT0("renderer_host", "RenderWidgetHostImpl::WasHidden");
513 is_hidden_ = true;
515 // Don't bother reporting hung state when we aren't active.
516 StopHangMonitorTimeout();
518 // If we have a renderer, then inform it that we are being hidden so it can
519 // reduce its resource utilization.
520 Send(new ViewMsg_WasHidden(routing_id_));
522 // Tell the RenderProcessHost we were hidden.
523 process_->WidgetHidden();
525 bool is_visible = false;
526 NotificationService::current()->Notify(
527 NOTIFICATION_RENDER_WIDGET_VISIBILITY_CHANGED,
528 Source<RenderWidgetHost>(this),
529 Details<bool>(&is_visible));
532 void RenderWidgetHostImpl::WasShown(const ui::LatencyInfo& latency_info) {
533 if (!is_hidden_)
534 return;
536 TRACE_EVENT0("renderer_host", "RenderWidgetHostImpl::WasShown");
537 is_hidden_ = false;
539 SendScreenRects();
541 // When hidden, timeout monitoring for input events is disabled. Restore it
542 // now to ensure consistent hang detection.
543 if (in_flight_event_count_)
544 RestartHangMonitorTimeout();
546 // Always repaint on restore.
547 bool needs_repainting = true;
548 needs_repainting_on_restore_ = false;
549 Send(new ViewMsg_WasShown(routing_id_, needs_repainting, latency_info));
551 process_->WidgetRestored();
553 bool is_visible = true;
554 NotificationService::current()->Notify(
555 NOTIFICATION_RENDER_WIDGET_VISIBILITY_CHANGED,
556 Source<RenderWidgetHost>(this),
557 Details<bool>(&is_visible));
559 // It's possible for our size to be out of sync with the renderer. The
560 // following is one case that leads to this:
561 // 1. WasResized -> Send ViewMsg_Resize to render
562 // 2. WasResized -> do nothing as resize_ack_pending_ is true
563 // 3. WasHidden
564 // 4. OnUpdateRect from (1) processed. Does NOT invoke WasResized as view
565 // is hidden. Now renderer/browser out of sync with what they think size
566 // is.
567 // By invoking WasResized the renderer is updated as necessary. WasResized
568 // does nothing if the sizes are already in sync.
570 // TODO: ideally ViewMsg_WasShown would take a size. This way, the renderer
571 // could handle both the restore and resize at once. This isn't that big a
572 // deal as RenderWidget::WasShown delays updating, so that the resize from
573 // WasResized is usually processed before the renderer is painted.
574 WasResized();
577 bool RenderWidgetHostImpl::GetResizeParams(
578 ViewMsg_Resize_Params* resize_params) {
579 *resize_params = ViewMsg_Resize_Params();
581 GetWebScreenInfo(&resize_params->screen_info);
582 resize_params->resizer_rect = GetRootWindowResizerRect();
584 if (view_) {
585 resize_params->new_size = view_->GetRequestedRendererSize();
586 resize_params->physical_backing_size = view_->GetPhysicalBackingSize();
587 resize_params->top_controls_height = view_->GetTopControlsHeight();
588 resize_params->top_controls_shrink_blink_size =
589 view_->DoTopControlsShrinkBlinkSize();
590 resize_params->visible_viewport_size = view_->GetVisibleViewportSize();
591 resize_params->is_fullscreen_granted = IsFullscreenGranted();
592 resize_params->display_mode = GetDisplayMode();
595 const bool size_changed =
596 !old_resize_params_ ||
597 old_resize_params_->new_size != resize_params->new_size ||
598 (old_resize_params_->physical_backing_size.IsEmpty() &&
599 !resize_params->physical_backing_size.IsEmpty());
600 bool dirty = size_changed ||
601 old_resize_params_->screen_info != resize_params->screen_info ||
602 old_resize_params_->physical_backing_size !=
603 resize_params->physical_backing_size ||
604 old_resize_params_->is_fullscreen_granted !=
605 resize_params->is_fullscreen_granted ||
606 old_resize_params_->display_mode != resize_params->display_mode ||
607 old_resize_params_->top_controls_height !=
608 resize_params->top_controls_height ||
609 old_resize_params_->top_controls_shrink_blink_size !=
610 resize_params->top_controls_shrink_blink_size ||
611 old_resize_params_->visible_viewport_size !=
612 resize_params->visible_viewport_size;
614 // We don't expect to receive an ACK when the requested size or the physical
615 // backing size is empty, or when the main viewport size didn't change.
616 resize_params->needs_resize_ack =
617 g_check_for_pending_resize_ack && !resize_params->new_size.IsEmpty() &&
618 !resize_params->physical_backing_size.IsEmpty() && size_changed;
620 return dirty;
623 void RenderWidgetHostImpl::SetInitialRenderSizeParams(
624 const ViewMsg_Resize_Params& resize_params) {
625 resize_ack_pending_ = resize_params.needs_resize_ack;
627 old_resize_params_ =
628 make_scoped_ptr(new ViewMsg_Resize_Params(resize_params));
631 void RenderWidgetHostImpl::WasResized() {
632 // Skip if the |delegate_| has already been detached because
633 // it's web contents is being deleted.
634 if (resize_ack_pending_ || !process_->HasConnection() || !view_ ||
635 !renderer_initialized_ || auto_resize_enabled_ || !delegate_) {
636 return;
639 scoped_ptr<ViewMsg_Resize_Params> params(new ViewMsg_Resize_Params);
640 if (!GetResizeParams(params.get()))
641 return;
643 bool width_changed =
644 !old_resize_params_ ||
645 old_resize_params_->new_size.width() != params->new_size.width();
646 if (Send(new ViewMsg_Resize(routing_id_, *params))) {
647 resize_ack_pending_ = params->needs_resize_ack;
648 old_resize_params_.swap(params);
651 if (delegate_)
652 delegate_->RenderWidgetWasResized(this, width_changed);
655 void RenderWidgetHostImpl::ResizeRectChanged(const gfx::Rect& new_rect) {
656 Send(new ViewMsg_ChangeResizeRect(routing_id_, new_rect));
659 void RenderWidgetHostImpl::GotFocus() {
660 Focus();
661 if (delegate_)
662 delegate_->RenderWidgetGotFocus(this);
665 void RenderWidgetHostImpl::Focus() {
666 is_focused_ = true;
668 Send(new InputMsg_SetFocus(routing_id_, true));
671 void RenderWidgetHostImpl::Blur() {
672 is_focused_ = false;
674 // If there is a pending mouse lock request, we don't want to reject it at
675 // this point. The user can switch focus back to this view and approve the
676 // request later.
677 if (IsMouseLocked())
678 view_->UnlockMouse();
680 if (touch_emulator_)
681 touch_emulator_->CancelTouch();
683 Send(new InputMsg_SetFocus(routing_id_, false));
686 void RenderWidgetHostImpl::LostCapture() {
687 if (touch_emulator_)
688 touch_emulator_->CancelTouch();
690 Send(new InputMsg_MouseCaptureLost(routing_id_));
693 void RenderWidgetHostImpl::SetActive(bool active) {
694 Send(new ViewMsg_SetActive(routing_id_, active));
697 void RenderWidgetHostImpl::LostMouseLock() {
698 Send(new ViewMsg_MouseLockLost(routing_id_));
701 void RenderWidgetHostImpl::ViewDestroyed() {
702 RejectMouseLockOrUnlockIfNecessary();
704 // TODO(evanm): tracking this may no longer be necessary;
705 // eliminate this function if so.
706 SetView(NULL);
709 void RenderWidgetHostImpl::CopyFromBackingStore(
710 const gfx::Rect& src_subrect,
711 const gfx::Size& accelerated_dst_size,
712 ReadbackRequestCallback& callback,
713 const SkColorType preferred_color_type) {
714 if (view_) {
715 TRACE_EVENT0("browser",
716 "RenderWidgetHostImpl::CopyFromBackingStore::FromCompositingSurface");
717 gfx::Rect accelerated_copy_rect = src_subrect.IsEmpty() ?
718 gfx::Rect(view_->GetViewBounds().size()) : src_subrect;
719 view_->CopyFromCompositingSurface(accelerated_copy_rect,
720 accelerated_dst_size, callback,
721 preferred_color_type);
722 return;
725 callback.Run(SkBitmap(), content::READBACK_FAILED);
728 bool RenderWidgetHostImpl::CanCopyFromBackingStore() {
729 if (view_)
730 return view_->IsSurfaceAvailableForCopy();
731 return false;
734 #if defined(OS_ANDROID)
735 void RenderWidgetHostImpl::LockBackingStore() {
736 if (view_)
737 view_->LockCompositingSurface();
740 void RenderWidgetHostImpl::UnlockBackingStore() {
741 if (view_)
742 view_->UnlockCompositingSurface();
744 #endif
746 #if defined(OS_MACOSX)
747 void RenderWidgetHostImpl::PauseForPendingResizeOrRepaints() {
748 TRACE_EVENT0("browser",
749 "RenderWidgetHostImpl::PauseForPendingResizeOrRepaints");
751 if (!CanPauseForPendingResizeOrRepaints())
752 return;
754 WaitForSurface();
757 bool RenderWidgetHostImpl::CanPauseForPendingResizeOrRepaints() {
758 // Do not pause if the view is hidden.
759 if (is_hidden())
760 return false;
762 // Do not pause if there is not a paint or resize already coming.
763 if (!repaint_ack_pending_ && !resize_ack_pending_)
764 return false;
766 return true;
769 void RenderWidgetHostImpl::WaitForSurface() {
770 // How long to (synchronously) wait for the renderer to respond with a
771 // new frame when our current frame doesn't exist or is the wrong size.
772 // This timeout impacts the "choppiness" of our window resize.
773 const int kPaintMsgTimeoutMS = 50;
775 if (!view_)
776 return;
778 // The view_size will be current_size_ for auto-sized views and otherwise the
779 // size of the view_. (For auto-sized views, current_size_ is updated during
780 // UpdateRect messages.)
781 gfx::Size view_size = current_size_;
782 if (!auto_resize_enabled_) {
783 // Get the desired size from the current view bounds.
784 gfx::Rect view_rect = view_->GetViewBounds();
785 if (view_rect.IsEmpty())
786 return;
787 view_size = view_rect.size();
790 TRACE_EVENT2("renderer_host",
791 "RenderWidgetHostImpl::WaitForSurface",
792 "width",
793 base::IntToString(view_size.width()),
794 "height",
795 base::IntToString(view_size.height()));
797 // We should not be asked to paint while we are hidden. If we are hidden,
798 // then it means that our consumer failed to call WasShown.
799 DCHECK(!is_hidden_) << "WaitForSurface called while hidden!";
801 // We should never be called recursively; this can theoretically lead to
802 // infinite recursion and almost certainly leads to lower performance.
803 DCHECK(!in_get_backing_store_) << "WaitForSurface called recursively!";
804 base::AutoReset<bool> auto_reset_in_get_backing_store(
805 &in_get_backing_store_, true);
807 // We might have a surface that we can use already.
808 if (view_->HasAcceleratedSurface(view_size))
809 return;
811 // Request that the renderer produce a frame of the right size, if it
812 // hasn't been requested already.
813 if (!repaint_ack_pending_ && !resize_ack_pending_) {
814 repaint_start_time_ = TimeTicks::Now();
815 repaint_ack_pending_ = true;
816 TRACE_EVENT_ASYNC_BEGIN0(
817 "renderer_host", "RenderWidgetHostImpl::repaint_ack_pending_", this);
818 Send(new ViewMsg_Repaint(routing_id_, view_size));
821 // Pump a nested message loop until we time out or get a frame of the right
822 // size.
823 TimeTicks start_time = TimeTicks::Now();
824 TimeDelta time_left = TimeDelta::FromMilliseconds(kPaintMsgTimeoutMS);
825 TimeTicks timeout_time = start_time + time_left;
826 while (1) {
827 TRACE_EVENT0("renderer_host", "WaitForSurface::WaitForSingleTaskToRun");
828 if (RenderWidgetResizeHelper::Get()->WaitForSingleTaskToRun(time_left)) {
829 // For auto-resized views, current_size_ determines the view_size and it
830 // may have changed during the handling of an UpdateRect message.
831 if (auto_resize_enabled_)
832 view_size = current_size_;
833 if (view_->HasAcceleratedSurface(view_size))
834 break;
836 time_left = timeout_time - TimeTicks::Now();
837 if (time_left <= TimeDelta::FromSeconds(0)) {
838 TRACE_EVENT0("renderer_host", "WaitForSurface::Timeout");
839 break;
843 UMA_HISTOGRAM_CUSTOM_TIMES("OSX.RendererHost.SurfaceWaitTime",
844 TimeTicks::Now() - start_time,
845 TimeDelta::FromMilliseconds(1),
846 TimeDelta::FromMilliseconds(200), 50);
848 #endif
850 bool RenderWidgetHostImpl::ScheduleComposite() {
851 if (is_hidden_ || current_size_.IsEmpty() || repaint_ack_pending_ ||
852 resize_ack_pending_) {
853 return false;
856 // Send out a request to the renderer to paint the view if required.
857 repaint_start_time_ = TimeTicks::Now();
858 repaint_ack_pending_ = true;
859 TRACE_EVENT_ASYNC_BEGIN0(
860 "renderer_host", "RenderWidgetHostImpl::repaint_ack_pending_", this);
861 Send(new ViewMsg_Repaint(routing_id_, current_size_));
862 return true;
865 void RenderWidgetHostImpl::StartHangMonitorTimeout(base::TimeDelta delay) {
866 if (hang_monitor_timeout_)
867 hang_monitor_timeout_->Start(delay);
870 void RenderWidgetHostImpl::RestartHangMonitorTimeout() {
871 if (hang_monitor_timeout_)
872 hang_monitor_timeout_->Restart(hung_renderer_delay_);
875 void RenderWidgetHostImpl::StopHangMonitorTimeout() {
876 if (hang_monitor_timeout_)
877 hang_monitor_timeout_->Stop();
878 RendererIsResponsive();
881 void RenderWidgetHostImpl::ForwardMouseEvent(const WebMouseEvent& mouse_event) {
882 ForwardMouseEventWithLatencyInfo(mouse_event, ui::LatencyInfo());
885 void RenderWidgetHostImpl::ForwardMouseEventWithLatencyInfo(
886 const blink::WebMouseEvent& mouse_event,
887 const ui::LatencyInfo& ui_latency) {
888 TRACE_EVENT2("input", "RenderWidgetHostImpl::ForwardMouseEvent",
889 "x", mouse_event.x, "y", mouse_event.y);
891 for (size_t i = 0; i < mouse_event_callbacks_.size(); ++i) {
892 if (mouse_event_callbacks_[i].Run(mouse_event))
893 return;
896 if (IgnoreInputEvents())
897 return;
899 if (touch_emulator_ && touch_emulator_->HandleMouseEvent(mouse_event))
900 return;
902 MouseEventWithLatencyInfo mouse_with_latency(mouse_event, ui_latency);
903 latency_tracker_.OnInputEvent(mouse_event, &mouse_with_latency.latency);
904 input_router_->SendMouseEvent(mouse_with_latency);
906 // Pass mouse state to gpu service if the subscribe uniform
907 // extension is enabled.
908 if (process_->SubscribeUniformEnabled()) {
909 gpu::ValueState state;
910 state.int_value[0] = mouse_event.x;
911 state.int_value[1] = mouse_event.y;
912 // TODO(orglofch) Separate the mapping of pending value states to the
913 // Gpu Service to be per RWH not per process
914 process_->SendUpdateValueState(GL_MOUSE_POSITION_CHROMIUM, state);
918 void RenderWidgetHostImpl::ForwardWheelEvent(
919 const WebMouseWheelEvent& wheel_event) {
920 ForwardWheelEventWithLatencyInfo(wheel_event, ui::LatencyInfo());
923 void RenderWidgetHostImpl::ForwardWheelEventWithLatencyInfo(
924 const blink::WebMouseWheelEvent& wheel_event,
925 const ui::LatencyInfo& ui_latency) {
926 TRACE_EVENT0("input", "RenderWidgetHostImpl::ForwardWheelEvent");
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 ui::LatencyInfo latency;
1056 latency_tracker_.OnInputEvent(key_event, &latency);
1057 input_router_->SendKeyboardEvent(key_event, 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::SetInputMethodActive(bool activate) {
1253 input_method_active_ = activate;
1254 Send(new ViewMsg_SetInputMethodActive(GetRoutingID(), activate));
1257 void RenderWidgetHostImpl::ImeSetComposition(
1258 const base::string16& text,
1259 const std::vector<blink::WebCompositionUnderline>& underlines,
1260 int selection_start,
1261 int selection_end) {
1262 Send(new InputMsg_ImeSetComposition(
1263 GetRoutingID(), text, underlines, selection_start, selection_end));
1266 void RenderWidgetHostImpl::ImeConfirmComposition(
1267 const base::string16& text,
1268 const gfx::Range& replacement_range,
1269 bool keep_selection) {
1270 Send(new InputMsg_ImeConfirmComposition(
1271 GetRoutingID(), text, replacement_range, keep_selection));
1274 void RenderWidgetHostImpl::ImeCancelComposition() {
1275 Send(new InputMsg_ImeSetComposition(GetRoutingID(), base::string16(),
1276 std::vector<blink::WebCompositionUnderline>(), 0, 0));
1279 gfx::Rect RenderWidgetHostImpl::GetRootWindowResizerRect() const {
1280 return gfx::Rect();
1283 void RenderWidgetHostImpl::RequestToLockMouse(bool user_gesture,
1284 bool last_unlocked_by_target) {
1285 // Directly reject to lock the mouse. Subclass can override this method to
1286 // decide whether to allow mouse lock or not.
1287 GotResponseToLockMouseRequest(false);
1290 void RenderWidgetHostImpl::RejectMouseLockOrUnlockIfNecessary() {
1291 DCHECK(!pending_mouse_lock_request_ || !IsMouseLocked());
1292 if (pending_mouse_lock_request_) {
1293 pending_mouse_lock_request_ = false;
1294 Send(new ViewMsg_LockMouse_ACK(routing_id_, false));
1295 } else if (IsMouseLocked()) {
1296 view_->UnlockMouse();
1300 bool RenderWidgetHostImpl::IsMouseLocked() const {
1301 return view_ ? view_->IsMouseLocked() : false;
1304 bool RenderWidgetHostImpl::IsFullscreenGranted() const {
1305 return false;
1308 blink::WebDisplayMode RenderWidgetHostImpl::GetDisplayMode() const {
1309 return blink::WebDisplayModeBrowser;
1312 void RenderWidgetHostImpl::SetAutoResize(bool enable,
1313 const gfx::Size& min_size,
1314 const gfx::Size& max_size) {
1315 auto_resize_enabled_ = enable;
1316 min_size_for_auto_resize_ = min_size;
1317 max_size_for_auto_resize_ = max_size;
1320 void RenderWidgetHostImpl::Destroy() {
1321 NotificationService::current()->Notify(
1322 NOTIFICATION_RENDER_WIDGET_HOST_DESTROYED,
1323 Source<RenderWidgetHost>(this),
1324 NotificationService::NoDetails());
1326 // Tell the view to die.
1327 // Note that in the process of the view shutting down, it can call a ton
1328 // of other messages on us. So if you do any other deinitialization here,
1329 // do it after this call to view_->Destroy().
1330 if (view_) {
1331 view_->Destroy();
1332 view_ = nullptr;
1335 delete this;
1338 void RenderWidgetHostImpl::RendererIsUnresponsive() {
1339 NotificationService::current()->Notify(
1340 NOTIFICATION_RENDER_WIDGET_HOST_HANG,
1341 Source<RenderWidgetHost>(this),
1342 NotificationService::NoDetails());
1343 is_unresponsive_ = true;
1344 NotifyRendererUnresponsive();
1347 void RenderWidgetHostImpl::RendererIsResponsive() {
1348 if (is_unresponsive_) {
1349 is_unresponsive_ = false;
1350 NotifyRendererResponsive();
1354 void RenderWidgetHostImpl::OnRenderViewReady() {
1355 SendScreenRects();
1356 WasResized();
1359 void RenderWidgetHostImpl::OnRenderProcessGone(int status, int exit_code) {
1360 // RenderFrameHost owns a RenderWidgetHost when it needs one, in which case
1361 // it handles destruction.
1362 if (!owned_by_render_frame_host_) {
1363 // TODO(evanm): This synchronously ends up calling "delete this".
1364 // Is that really what we want in response to this message? I'm matching
1365 // previous behavior of the code here.
1366 Destroy();
1367 } else {
1368 RendererExited(static_cast<base::TerminationStatus>(status), exit_code);
1372 void RenderWidgetHostImpl::OnClose() {
1373 Shutdown();
1376 void RenderWidgetHostImpl::OnSetTooltipText(
1377 const base::string16& tooltip_text,
1378 WebTextDirection text_direction_hint) {
1379 // First, add directionality marks around tooltip text if necessary.
1380 // A naive solution would be to simply always wrap the text. However, on
1381 // windows, Unicode directional embedding characters can't be displayed on
1382 // systems that lack RTL fonts and are instead displayed as empty squares.
1384 // To get around this we only wrap the string when we deem it necessary i.e.
1385 // when the locale direction is different than the tooltip direction hint.
1387 // Currently, we use element's directionality as the tooltip direction hint.
1388 // An alternate solution would be to set the overall directionality based on
1389 // trying to detect the directionality from the tooltip text rather than the
1390 // element direction. One could argue that would be a preferable solution
1391 // but we use the current approach to match Fx & IE's behavior.
1392 base::string16 wrapped_tooltip_text = tooltip_text;
1393 if (!tooltip_text.empty()) {
1394 if (text_direction_hint == blink::WebTextDirectionLeftToRight) {
1395 // Force the tooltip to have LTR directionality.
1396 wrapped_tooltip_text =
1397 base::i18n::GetDisplayStringInLTRDirectionality(wrapped_tooltip_text);
1398 } else if (text_direction_hint == blink::WebTextDirectionRightToLeft &&
1399 !base::i18n::IsRTL()) {
1400 // Force the tooltip to have RTL directionality.
1401 base::i18n::WrapStringWithRTLFormatting(&wrapped_tooltip_text);
1404 if (GetView())
1405 view_->SetTooltipText(wrapped_tooltip_text);
1408 void RenderWidgetHostImpl::OnUpdateScreenRectsAck() {
1409 waiting_for_screen_rects_ack_ = false;
1410 if (!view_)
1411 return;
1413 if (view_->GetViewBounds() == last_view_screen_rect_ &&
1414 view_->GetBoundsInRootWindow() == last_window_screen_rect_) {
1415 return;
1418 SendScreenRects();
1421 void RenderWidgetHostImpl::OnRequestMove(const gfx::Rect& pos) {
1422 if (view_) {
1423 view_->SetBounds(pos);
1424 Send(new ViewMsg_Move_ACK(routing_id_));
1428 bool RenderWidgetHostImpl::OnSwapCompositorFrame(
1429 const IPC::Message& message) {
1430 // This trace event is used in
1431 // chrome/browser/extensions/api/cast_streaming/performance_test.cc
1432 TRACE_EVENT0("test_fps,benchmark", "OnSwapCompositorFrame");
1433 ViewHostMsg_SwapCompositorFrame::Param param;
1434 if (!ViewHostMsg_SwapCompositorFrame::Read(&message, &param))
1435 return false;
1436 scoped_ptr<cc::CompositorFrame> frame(new cc::CompositorFrame);
1437 uint32 output_surface_id = base::get<0>(param);
1438 base::get<1>(param).AssignTo(frame.get());
1439 std::vector<IPC::Message> messages_to_deliver_with_frame;
1440 messages_to_deliver_with_frame.swap(base::get<2>(param));
1442 latency_tracker_.OnSwapCompositorFrame(&frame->metadata.latency_info);
1444 bool is_mobile_optimized = IsMobileOptimizedFrame(frame->metadata);
1445 input_router_->NotifySiteIsMobileOptimized(is_mobile_optimized);
1446 if (touch_emulator_)
1447 touch_emulator_->SetDoubleTapSupportForPageEnabled(!is_mobile_optimized);
1449 if (view_) {
1450 view_->OnSwapCompositorFrame(output_surface_id, frame.Pass());
1451 view_->DidReceiveRendererFrame();
1452 } else {
1453 cc::CompositorFrameAck ack;
1454 if (frame->gl_frame_data) {
1455 ack.gl_frame_data = frame->gl_frame_data.Pass();
1456 ack.gl_frame_data->sync_point = 0;
1457 } else if (frame->delegated_frame_data) {
1458 cc::TransferableResource::ReturnResources(
1459 frame->delegated_frame_data->resource_list,
1460 &ack.resources);
1461 } else if (frame->software_frame_data) {
1462 ack.last_software_frame_id = frame->software_frame_data->id;
1464 SendSwapCompositorFrameAck(routing_id_, output_surface_id,
1465 process_->GetID(), ack);
1468 RenderProcessHost* rph = GetProcess();
1469 for (std::vector<IPC::Message>::const_iterator i =
1470 messages_to_deliver_with_frame.begin();
1471 i != messages_to_deliver_with_frame.end();
1472 ++i) {
1473 rph->OnMessageReceived(*i);
1474 if (i->dispatch_error())
1475 rph->OnBadMessageReceived(*i);
1477 messages_to_deliver_with_frame.clear();
1479 return true;
1482 void RenderWidgetHostImpl::OnUpdateRect(
1483 const ViewHostMsg_UpdateRect_Params& params) {
1484 TRACE_EVENT0("renderer_host", "RenderWidgetHostImpl::OnUpdateRect");
1485 TimeTicks paint_start = TimeTicks::Now();
1487 // Update our knowledge of the RenderWidget's size.
1488 current_size_ = params.view_size;
1490 bool is_resize_ack =
1491 ViewHostMsg_UpdateRect_Flags::is_resize_ack(params.flags);
1493 // resize_ack_pending_ needs to be cleared before we call DidPaintRect, since
1494 // that will end up reaching GetBackingStore.
1495 if (is_resize_ack) {
1496 DCHECK(!g_check_for_pending_resize_ack || resize_ack_pending_);
1497 resize_ack_pending_ = false;
1500 bool is_repaint_ack =
1501 ViewHostMsg_UpdateRect_Flags::is_repaint_ack(params.flags);
1502 if (is_repaint_ack) {
1503 DCHECK(repaint_ack_pending_);
1504 TRACE_EVENT_ASYNC_END0(
1505 "renderer_host", "RenderWidgetHostImpl::repaint_ack_pending_", this);
1506 repaint_ack_pending_ = false;
1507 TimeDelta delta = TimeTicks::Now() - repaint_start_time_;
1508 UMA_HISTOGRAM_TIMES("MPArch.RWH_RepaintDelta", delta);
1511 DCHECK(!params.view_size.IsEmpty());
1513 DidUpdateBackingStore(params, paint_start);
1515 if (auto_resize_enabled_) {
1516 bool post_callback = new_auto_size_.IsEmpty();
1517 new_auto_size_ = params.view_size;
1518 if (post_callback) {
1519 base::ThreadTaskRunnerHandle::Get()->PostTask(
1520 FROM_HERE, base::Bind(&RenderWidgetHostImpl::DelayedAutoResized,
1521 weak_factory_.GetWeakPtr()));
1525 // Log the time delta for processing a paint message. On platforms that don't
1526 // support asynchronous painting, this is equivalent to
1527 // MPArch.RWH_TotalPaintTime.
1528 TimeDelta delta = TimeTicks::Now() - paint_start;
1529 UMA_HISTOGRAM_TIMES("MPArch.RWH_OnMsgUpdateRect", delta);
1532 void RenderWidgetHostImpl::DidUpdateBackingStore(
1533 const ViewHostMsg_UpdateRect_Params& params,
1534 const TimeTicks& paint_start) {
1535 TRACE_EVENT0("renderer_host", "RenderWidgetHostImpl::DidUpdateBackingStore");
1536 TimeTicks update_start = TimeTicks::Now();
1538 // Move the plugins if the view hasn't already been destroyed. Plugin moves
1539 // will not be re-issued, so must move them now, regardless of whether we
1540 // paint or not. MovePluginWindows attempts to move the plugin windows and
1541 // in the process could dispatch other window messages which could cause the
1542 // view to be destroyed.
1543 if (view_)
1544 view_->MovePluginWindows(params.plugin_window_moves);
1546 NotificationService::current()->Notify(
1547 NOTIFICATION_RENDER_WIDGET_HOST_DID_UPDATE_BACKING_STORE,
1548 Source<RenderWidgetHost>(this),
1549 NotificationService::NoDetails());
1551 // We don't need to update the view if the view is hidden. We must do this
1552 // early return after the ACK is sent, however, or the renderer will not send
1553 // us more data.
1554 if (is_hidden_)
1555 return;
1557 // If we got a resize ack, then perhaps we have another resize to send?
1558 bool is_resize_ack =
1559 ViewHostMsg_UpdateRect_Flags::is_resize_ack(params.flags);
1560 if (is_resize_ack)
1561 WasResized();
1563 // Log the time delta for processing a paint message.
1564 TimeTicks now = TimeTicks::Now();
1565 TimeDelta delta = now - update_start;
1566 UMA_HISTOGRAM_TIMES("MPArch.RWH_DidUpdateBackingStore", delta);
1569 void RenderWidgetHostImpl::OnQueueSyntheticGesture(
1570 const SyntheticGesturePacket& gesture_packet) {
1571 // Only allow untrustworthy gestures if explicitly enabled.
1572 if (!base::CommandLine::ForCurrentProcess()->HasSwitch(
1573 cc::switches::kEnableGpuBenchmarking)) {
1574 bad_message::ReceivedBadMessage(GetProcess(),
1575 bad_message::RWH_SYNTHETIC_GESTURE);
1576 return;
1579 QueueSyntheticGesture(
1580 SyntheticGesture::Create(*gesture_packet.gesture_params()),
1581 base::Bind(&RenderWidgetHostImpl::OnSyntheticGestureCompleted,
1582 weak_factory_.GetWeakPtr()));
1585 void RenderWidgetHostImpl::OnFocus() {
1586 // Only RenderViewHost can deal with that message.
1587 bad_message::ReceivedBadMessage(GetProcess(), bad_message::RWH_FOCUS);
1590 void RenderWidgetHostImpl::OnBlur() {
1591 // Only RenderViewHost can deal with that message.
1592 bad_message::ReceivedBadMessage(GetProcess(), bad_message::RWH_BLUR);
1595 void RenderWidgetHostImpl::OnSetCursor(const WebCursor& cursor) {
1596 SetCursor(cursor);
1599 void RenderWidgetHostImpl::SetTouchEventEmulationEnabled(
1600 bool enabled, ui::GestureProviderConfigType config_type) {
1601 if (enabled) {
1602 if (!touch_emulator_)
1603 touch_emulator_.reset(new TouchEmulator(this));
1604 touch_emulator_->Enable(config_type);
1605 } else {
1606 if (touch_emulator_)
1607 touch_emulator_->Disable();
1611 void RenderWidgetHostImpl::OnTextInputTypeChanged(
1612 ui::TextInputType type,
1613 ui::TextInputMode input_mode,
1614 bool can_compose_inline,
1615 int flags) {
1616 if (view_)
1617 view_->TextInputTypeChanged(type, input_mode, can_compose_inline, flags);
1620 void RenderWidgetHostImpl::OnImeCompositionRangeChanged(
1621 const gfx::Range& range,
1622 const std::vector<gfx::Rect>& character_bounds) {
1623 if (view_)
1624 view_->ImeCompositionRangeChanged(range, character_bounds);
1627 void RenderWidgetHostImpl::OnImeCancelComposition() {
1628 if (view_)
1629 view_->ImeCancelComposition();
1632 void RenderWidgetHostImpl::OnLockMouse(bool user_gesture,
1633 bool last_unlocked_by_target,
1634 bool privileged) {
1636 if (pending_mouse_lock_request_) {
1637 Send(new ViewMsg_LockMouse_ACK(routing_id_, false));
1638 return;
1639 } else if (IsMouseLocked()) {
1640 Send(new ViewMsg_LockMouse_ACK(routing_id_, true));
1641 return;
1644 pending_mouse_lock_request_ = true;
1645 if (privileged && allow_privileged_mouse_lock_) {
1646 // Directly approve to lock the mouse.
1647 GotResponseToLockMouseRequest(true);
1648 } else {
1649 RequestToLockMouse(user_gesture, last_unlocked_by_target);
1653 void RenderWidgetHostImpl::OnUnlockMouse() {
1654 RejectMouseLockOrUnlockIfNecessary();
1657 void RenderWidgetHostImpl::OnShowDisambiguationPopup(
1658 const gfx::Rect& rect_pixels,
1659 const gfx::Size& size,
1660 const cc::SharedBitmapId& id) {
1661 DCHECK(!rect_pixels.IsEmpty());
1662 DCHECK(!size.IsEmpty());
1664 scoped_ptr<cc::SharedBitmap> bitmap =
1665 HostSharedBitmapManager::current()->GetSharedBitmapFromId(size, id);
1666 if (!bitmap) {
1667 bad_message::ReceivedBadMessage(GetProcess(),
1668 bad_message::RWH_SHARED_BITMAP);
1669 return;
1672 DCHECK(bitmap->pixels());
1674 SkImageInfo info = SkImageInfo::MakeN32Premul(size.width(), size.height());
1675 SkBitmap zoomed_bitmap;
1676 zoomed_bitmap.installPixels(info, bitmap->pixels(), info.minRowBytes());
1678 // Note that |rect| is in coordinates of pixels relative to the window origin.
1679 // Aura-based systems will want to convert this to DIPs.
1680 if (view_)
1681 view_->ShowDisambiguationPopup(rect_pixels, zoomed_bitmap);
1683 // It is assumed that the disambiguation popup will make a copy of the
1684 // provided zoomed image, so we delete this one.
1685 zoomed_bitmap.setPixels(0);
1686 Send(new ViewMsg_ReleaseDisambiguationPopupBitmap(GetRoutingID(), id));
1689 #if defined(OS_WIN)
1690 void RenderWidgetHostImpl::OnWindowlessPluginDummyWindowCreated(
1691 gfx::NativeViewId dummy_activation_window) {
1692 HWND hwnd = reinterpret_cast<HWND>(dummy_activation_window);
1694 // This may happen as a result of a race condition when the plugin is going
1695 // away.
1696 wchar_t window_title[MAX_PATH + 1] = {0};
1697 if (!IsWindow(hwnd) ||
1698 !GetWindowText(hwnd, window_title, arraysize(window_title)) ||
1699 lstrcmpiW(window_title, kDummyActivationWindowName) != 0) {
1700 return;
1703 #if defined(USE_AURA)
1704 SetParent(hwnd,
1705 reinterpret_cast<HWND>(view_->GetParentForWindowlessPlugin()));
1706 #else
1707 SetParent(hwnd, reinterpret_cast<HWND>(GetNativeViewId()));
1708 #endif
1709 dummy_windows_for_activation_.push_back(hwnd);
1712 void RenderWidgetHostImpl::OnWindowlessPluginDummyWindowDestroyed(
1713 gfx::NativeViewId dummy_activation_window) {
1714 HWND hwnd = reinterpret_cast<HWND>(dummy_activation_window);
1715 std::list<HWND>::iterator i = dummy_windows_for_activation_.begin();
1716 for (; i != dummy_windows_for_activation_.end(); ++i) {
1717 if ((*i) == hwnd) {
1718 dummy_windows_for_activation_.erase(i);
1719 return;
1722 NOTREACHED() << "Unknown dummy window";
1724 #endif
1726 void RenderWidgetHostImpl::SetIgnoreInputEvents(bool ignore_input_events) {
1727 ignore_input_events_ = ignore_input_events;
1730 bool RenderWidgetHostImpl::KeyPressListenersHandleEvent(
1731 const NativeWebKeyboardEvent& event) {
1732 if (event.skip_in_browser || event.type != WebKeyboardEvent::RawKeyDown)
1733 return false;
1735 for (size_t i = 0; i < key_press_event_callbacks_.size(); i++) {
1736 size_t original_size = key_press_event_callbacks_.size();
1737 if (key_press_event_callbacks_[i].Run(event))
1738 return true;
1740 // Check whether the callback that just ran removed itself, in which case
1741 // the iterator needs to be decremented to properly account for the removal.
1742 size_t current_size = key_press_event_callbacks_.size();
1743 if (current_size != original_size) {
1744 DCHECK_EQ(original_size - 1, current_size);
1745 --i;
1749 return false;
1752 InputEventAckState RenderWidgetHostImpl::FilterInputEvent(
1753 const blink::WebInputEvent& event, const ui::LatencyInfo& latency_info) {
1754 // Don't ignore touch cancel events, since they may be sent while input
1755 // events are being ignored in order to keep the renderer from getting
1756 // confused about how many touches are active.
1757 if (IgnoreInputEvents() && event.type != WebInputEvent::TouchCancel)
1758 return INPUT_EVENT_ACK_STATE_NO_CONSUMER_EXISTS;
1760 if (!process_->HasConnection())
1761 return INPUT_EVENT_ACK_STATE_UNKNOWN;
1763 if (event.type == WebInputEvent::MouseDown ||
1764 event.type == WebInputEvent::GestureTapDown) {
1765 OnUserGesture();
1768 return view_ ? view_->FilterInputEvent(event)
1769 : INPUT_EVENT_ACK_STATE_NOT_CONSUMED;
1772 void RenderWidgetHostImpl::IncrementInFlightEventCount() {
1773 increment_in_flight_event_count();
1774 if (!is_hidden_)
1775 StartHangMonitorTimeout(hung_renderer_delay_);
1778 void RenderWidgetHostImpl::DecrementInFlightEventCount() {
1779 if (decrement_in_flight_event_count() <= 0) {
1780 // Cancel pending hung renderer checks since the renderer is responsive.
1781 StopHangMonitorTimeout();
1782 } else {
1783 // The renderer is responsive, but there are in-flight events to wait for.
1784 if (!is_hidden_)
1785 RestartHangMonitorTimeout();
1789 void RenderWidgetHostImpl::OnHasTouchEventHandlers(bool has_handlers) {
1790 has_touch_handler_ = has_handlers;
1793 void RenderWidgetHostImpl::DidFlush() {
1794 if (synthetic_gesture_controller_)
1795 synthetic_gesture_controller_->OnDidFlushInput();
1798 void RenderWidgetHostImpl::DidOverscroll(const DidOverscrollParams& params) {
1799 if (view_)
1800 view_->DidOverscroll(params);
1803 void RenderWidgetHostImpl::DidStopFlinging() {
1804 if (view_)
1805 view_->DidStopFlinging();
1808 void RenderWidgetHostImpl::OnKeyboardEventAck(
1809 const NativeWebKeyboardEvent& event,
1810 InputEventAckState ack_result) {
1811 #if defined(OS_MACOSX)
1812 if (!is_hidden() && view_ && view_->PostProcessEventForPluginIme(event))
1813 return;
1814 #endif
1816 // We only send unprocessed key event upwards if we are not hidden,
1817 // because the user has moved away from us and no longer expect any effect
1818 // of this key event.
1819 const bool processed = (INPUT_EVENT_ACK_STATE_CONSUMED == ack_result);
1820 if (delegate_ && !processed && !is_hidden() && !event.skip_in_browser) {
1821 delegate_->HandleKeyboardEvent(event);
1823 // WARNING: This RenderWidgetHostImpl can be deallocated at this point
1824 // (i.e. in the case of Ctrl+W, where the call to
1825 // HandleKeyboardEvent destroys this RenderWidgetHostImpl).
1829 void RenderWidgetHostImpl::OnWheelEventAck(
1830 const MouseWheelEventWithLatencyInfo& wheel_event,
1831 InputEventAckState ack_result) {
1832 latency_tracker_.OnInputEventAck(wheel_event.event, &wheel_event.latency);
1834 if (!is_hidden() && view_) {
1835 if (ack_result != INPUT_EVENT_ACK_STATE_CONSUMED &&
1836 delegate_->HandleWheelEvent(wheel_event.event)) {
1837 ack_result = INPUT_EVENT_ACK_STATE_CONSUMED;
1839 view_->WheelEventAck(wheel_event.event, ack_result);
1843 void RenderWidgetHostImpl::OnGestureEventAck(
1844 const GestureEventWithLatencyInfo& event,
1845 InputEventAckState ack_result) {
1846 latency_tracker_.OnInputEventAck(event.event, &event.latency);
1848 if (view_)
1849 view_->GestureEventAck(event.event, ack_result);
1852 void RenderWidgetHostImpl::OnTouchEventAck(
1853 const TouchEventWithLatencyInfo& event,
1854 InputEventAckState ack_result) {
1855 latency_tracker_.OnInputEventAck(event.event, &event.latency);
1857 if (touch_emulator_ &&
1858 touch_emulator_->HandleTouchEventAck(event.event, ack_result)) {
1859 return;
1862 if (view_)
1863 view_->ProcessAckedTouchEvent(event, ack_result);
1866 void RenderWidgetHostImpl::OnUnexpectedEventAck(UnexpectedEventAckType type) {
1867 if (type == BAD_ACK_MESSAGE) {
1868 bad_message::ReceivedBadMessage(process_, bad_message::RWH_BAD_ACK_MESSAGE);
1869 } else if (type == UNEXPECTED_EVENT_TYPE) {
1870 suppress_next_char_events_ = false;
1874 void RenderWidgetHostImpl::OnSyntheticGestureCompleted(
1875 SyntheticGesture::Result result) {
1876 Send(new InputMsg_SyntheticGestureCompleted(GetRoutingID()));
1879 bool RenderWidgetHostImpl::IgnoreInputEvents() const {
1880 return ignore_input_events_ || process_->IgnoreInputEvents();
1883 void RenderWidgetHostImpl::StartUserGesture() {
1884 OnUserGesture();
1887 void RenderWidgetHostImpl::SetBackgroundOpaque(bool opaque) {
1888 Send(new ViewMsg_SetBackgroundOpaque(GetRoutingID(), opaque));
1891 void RenderWidgetHostImpl::SetEditCommandsForNextKeyEvent(
1892 const std::vector<EditCommand>& commands) {
1893 Send(new InputMsg_SetEditCommandsForNextKeyEvent(GetRoutingID(), commands));
1896 void RenderWidgetHostImpl::ExecuteEditCommand(const std::string& command,
1897 const std::string& value) {
1898 Send(new InputMsg_ExecuteEditCommand(GetRoutingID(), command, value));
1901 void RenderWidgetHostImpl::ScrollFocusedEditableNodeIntoRect(
1902 const gfx::Rect& rect) {
1903 Send(new InputMsg_ScrollFocusedEditableNodeIntoRect(GetRoutingID(), rect));
1906 void RenderWidgetHostImpl::MoveCaret(const gfx::Point& point) {
1907 Send(new InputMsg_MoveCaret(GetRoutingID(), point));
1910 bool RenderWidgetHostImpl::GotResponseToLockMouseRequest(bool allowed) {
1911 if (!allowed) {
1912 RejectMouseLockOrUnlockIfNecessary();
1913 return false;
1914 } else {
1915 if (!pending_mouse_lock_request_) {
1916 // This is possible, e.g., the plugin sends us an unlock request before
1917 // the user allows to lock to mouse.
1918 return false;
1921 pending_mouse_lock_request_ = false;
1922 if (!view_ || !view_->HasFocus()|| !view_->LockMouse()) {
1923 Send(new ViewMsg_LockMouse_ACK(routing_id_, false));
1924 return false;
1925 } else {
1926 Send(new ViewMsg_LockMouse_ACK(routing_id_, true));
1927 return true;
1932 // static
1933 void RenderWidgetHostImpl::SendSwapCompositorFrameAck(
1934 int32 route_id,
1935 uint32 output_surface_id,
1936 int renderer_host_id,
1937 const cc::CompositorFrameAck& ack) {
1938 RenderProcessHost* host = RenderProcessHost::FromID(renderer_host_id);
1939 if (!host)
1940 return;
1941 host->Send(new ViewMsg_SwapCompositorFrameAck(
1942 route_id, output_surface_id, ack));
1945 // static
1946 void RenderWidgetHostImpl::SendReclaimCompositorResources(
1947 int32 route_id,
1948 uint32 output_surface_id,
1949 int renderer_host_id,
1950 const cc::CompositorFrameAck& ack) {
1951 RenderProcessHost* host = RenderProcessHost::FromID(renderer_host_id);
1952 if (!host)
1953 return;
1954 host->Send(
1955 new ViewMsg_ReclaimCompositorResources(route_id, output_surface_id, ack));
1958 void RenderWidgetHostImpl::DelayedAutoResized() {
1959 gfx::Size new_size = new_auto_size_;
1960 // Clear the new_auto_size_ since the empty value is used as a flag to
1961 // indicate that no callback is in progress (i.e. without this line
1962 // DelayedAutoResized will not get called again).
1963 new_auto_size_.SetSize(0, 0);
1964 if (!auto_resize_enabled_)
1965 return;
1967 OnRenderAutoResized(new_size);
1970 void RenderWidgetHostImpl::DetachDelegate() {
1971 delegate_ = NULL;
1974 void RenderWidgetHostImpl::FrameSwapped(const ui::LatencyInfo& latency_info) {
1975 ui::LatencyInfo::LatencyComponent window_snapshot_component;
1976 if (latency_info.FindLatency(ui::WINDOW_SNAPSHOT_FRAME_NUMBER_COMPONENT,
1977 GetLatencyComponentId(),
1978 &window_snapshot_component)) {
1979 int sequence_number = static_cast<int>(
1980 window_snapshot_component.sequence_number);
1981 #if defined(OS_MACOSX)
1982 // On Mac, when using CoreAnmation, there is a delay between when content
1983 // is drawn to the screen, and when the snapshot will actually pick up
1984 // that content. Insert a manual delay of 1/6th of a second (to simulate
1985 // 10 frames at 60 fps) before actually taking the snapshot.
1986 base::MessageLoop::current()->PostDelayedTask(
1987 FROM_HERE,
1988 base::Bind(&RenderWidgetHostImpl::WindowSnapshotReachedScreen,
1989 weak_factory_.GetWeakPtr(),
1990 sequence_number),
1991 base::TimeDelta::FromSecondsD(1. / 6));
1992 #else
1993 WindowSnapshotReachedScreen(sequence_number);
1994 #endif
1997 latency_tracker_.OnFrameSwapped(latency_info);
2000 void RenderWidgetHostImpl::DidReceiveRendererFrame() {
2001 view_->DidReceiveRendererFrame();
2004 void RenderWidgetHostImpl::WindowSnapshotReachedScreen(int snapshot_id) {
2005 DCHECK(base::MessageLoopForUI::IsCurrent());
2007 gfx::Rect view_bounds = GetView()->GetViewBounds();
2008 gfx::Rect snapshot_bounds(view_bounds.size());
2010 std::vector<unsigned char> png;
2011 if (ui::GrabViewSnapshot(
2012 GetView()->GetNativeView(), &png, snapshot_bounds)) {
2013 OnSnapshotDataReceived(snapshot_id, &png.front(), png.size());
2014 return;
2017 ui::GrabViewSnapshotAsync(
2018 GetView()->GetNativeView(),
2019 snapshot_bounds,
2020 base::ThreadTaskRunnerHandle::Get(),
2021 base::Bind(&RenderWidgetHostImpl::OnSnapshotDataReceivedAsync,
2022 weak_factory_.GetWeakPtr(),
2023 snapshot_id));
2026 void RenderWidgetHostImpl::OnSnapshotDataReceived(int snapshot_id,
2027 const unsigned char* data,
2028 size_t size) {
2029 // Any pending snapshots with a lower ID than the one received are considered
2030 // to be implicitly complete, and returned the same snapshot data.
2031 PendingSnapshotMap::iterator it = pending_browser_snapshots_.begin();
2032 while(it != pending_browser_snapshots_.end()) {
2033 if (it->first <= snapshot_id) {
2034 it->second.Run(data, size);
2035 pending_browser_snapshots_.erase(it++);
2036 } else {
2037 ++it;
2042 void RenderWidgetHostImpl::OnSnapshotDataReceivedAsync(
2043 int snapshot_id,
2044 scoped_refptr<base::RefCountedBytes> png_data) {
2045 if (png_data.get())
2046 OnSnapshotDataReceived(snapshot_id, png_data->front(), png_data->size());
2047 else
2048 OnSnapshotDataReceived(snapshot_id, NULL, 0);
2051 // static
2052 void RenderWidgetHostImpl::CompositorFrameDrawn(
2053 const std::vector<ui::LatencyInfo>& latency_info) {
2054 for (size_t i = 0; i < latency_info.size(); i++) {
2055 std::set<RenderWidgetHostImpl*> rwhi_set;
2056 for (ui::LatencyInfo::LatencyMap::const_iterator b =
2057 latency_info[i].latency_components.begin();
2058 b != latency_info[i].latency_components.end();
2059 ++b) {
2060 if (b->first.first == ui::INPUT_EVENT_LATENCY_BEGIN_RWH_COMPONENT ||
2061 b->first.first == ui::WINDOW_SNAPSHOT_FRAME_NUMBER_COMPONENT ||
2062 b->first.first == ui::TAB_SHOW_COMPONENT) {
2063 // Matches with GetLatencyComponentId
2064 int routing_id = b->first.second & 0xffffffff;
2065 int process_id = (b->first.second >> 32) & 0xffffffff;
2066 RenderWidgetHost* rwh =
2067 RenderWidgetHost::FromID(process_id, routing_id);
2068 if (!rwh) {
2069 continue;
2071 RenderWidgetHostImpl* rwhi = RenderWidgetHostImpl::From(rwh);
2072 if (rwhi_set.insert(rwhi).second)
2073 rwhi->FrameSwapped(latency_info[i]);
2079 BrowserAccessibilityManager*
2080 RenderWidgetHostImpl::GetRootBrowserAccessibilityManager() {
2081 return delegate_ ? delegate_->GetRootBrowserAccessibilityManager() : NULL;
2084 BrowserAccessibilityManager*
2085 RenderWidgetHostImpl::GetOrCreateRootBrowserAccessibilityManager() {
2086 return delegate_ ?
2087 delegate_->GetOrCreateRootBrowserAccessibilityManager() : NULL;
2090 base::TimeDelta RenderWidgetHostImpl::GetEstimatedBrowserCompositeTime() const {
2091 return latency_tracker_.GetEstimatedBrowserCompositeTime();
2094 #if defined(OS_WIN)
2095 gfx::NativeViewAccessible
2096 RenderWidgetHostImpl::GetParentNativeViewAccessible() {
2097 return delegate_ ? delegate_->GetParentNativeViewAccessible() : NULL;
2099 #endif
2101 } // namespace content