[Chromoting] Run jscompile over JS for HTML files (GN-only)
[chromium-blink-merge.git] / content / browser / renderer_host / render_widget_host_impl.cc
blob41245f2d80a965125b0e9077df50bacb928a71c0
1 // Copyright (c) 2012 The Chromium Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
5 #include "content/browser/renderer_host/render_widget_host_impl.h"
7 #include <math.h>
8 #include <set>
9 #include <utility>
11 #include "base/auto_reset.h"
12 #include "base/bind.h"
13 #include "base/command_line.h"
14 #include "base/containers/hash_tables.h"
15 #include "base/i18n/rtl.h"
16 #include "base/lazy_instance.h"
17 #include "base/message_loop/message_loop.h"
18 #include "base/metrics/field_trial.h"
19 #include "base/metrics/histogram.h"
20 #include "base/strings/string_number_conversions.h"
21 #include "base/strings/utf_string_conversions.h"
22 #include "base/thread_task_runner_handle.h"
23 #include "base/trace_event/trace_event.h"
24 #include "cc/base/switches.h"
25 #include "cc/output/compositor_frame.h"
26 #include "cc/output/compositor_frame_ack.h"
27 #include "content/browser/accessibility/accessibility_mode_helper.h"
28 #include "content/browser/accessibility/browser_accessibility_state_impl.h"
29 #include "content/browser/bad_message.h"
30 #include "content/browser/browser_plugin/browser_plugin_guest.h"
31 #include "content/browser/gpu/compositor_util.h"
32 #include "content/browser/gpu/gpu_process_host.h"
33 #include "content/browser/gpu/gpu_process_host_ui_shim.h"
34 #include "content/browser/gpu/gpu_surface_tracker.h"
35 #include "content/browser/renderer_host/dip_util.h"
36 #include "content/browser/renderer_host/frame_metadata_util.h"
37 #include "content/browser/renderer_host/input/input_router_config_helper.h"
38 #include "content/browser/renderer_host/input/input_router_impl.h"
39 #include "content/browser/renderer_host/input/synthetic_gesture.h"
40 #include "content/browser/renderer_host/input/synthetic_gesture_controller.h"
41 #include "content/browser/renderer_host/input/synthetic_gesture_target.h"
42 #include "content/browser/renderer_host/input/timeout_monitor.h"
43 #include "content/browser/renderer_host/input/touch_emulator.h"
44 #include "content/browser/renderer_host/render_process_host_impl.h"
45 #include "content/browser/renderer_host/render_view_host_impl.h"
46 #include "content/browser/renderer_host/render_widget_helper.h"
47 #include "content/browser/renderer_host/render_widget_host_delegate.h"
48 #include "content/browser/renderer_host/render_widget_host_view_base.h"
49 #include "content/browser/renderer_host/render_widget_resize_helper.h"
50 #include "content/common/content_constants_internal.h"
51 #include "content/common/cursors/webcursor.h"
52 #include "content/common/frame_messages.h"
53 #include "content/common/gpu/gpu_messages.h"
54 #include "content/common/host_shared_bitmap_manager.h"
55 #include "content/common/input_messages.h"
56 #include "content/common/view_messages.h"
57 #include "content/public/browser/native_web_keyboard_event.h"
58 #include "content/public/browser/notification_service.h"
59 #include "content/public/browser/notification_types.h"
60 #include "content/public/browser/render_widget_host_iterator.h"
61 #include "content/public/common/content_constants.h"
62 #include "content/public/common/content_switches.h"
63 #include "content/public/common/result_codes.h"
64 #include "content/public/common/web_preferences.h"
65 #include "gpu/GLES2/gl2extchromium.h"
66 #include "gpu/command_buffer/service/gpu_switches.h"
67 #include "skia/ext/image_operations.h"
68 #include "skia/ext/platform_canvas.h"
69 #include "third_party/WebKit/public/web/WebCompositionUnderline.h"
70 #include "ui/events/event.h"
71 #include "ui/events/keycodes/keyboard_codes.h"
72 #include "ui/gfx/geometry/size_conversions.h"
73 #include "ui/gfx/geometry/vector2d_conversions.h"
74 #include "ui/gfx/skbitmap_operations.h"
75 #include "ui/snapshot/snapshot.h"
77 #if defined(OS_WIN)
78 #include "content/common/plugin_constants_win.h"
79 #endif
81 using base::Time;
82 using base::TimeDelta;
83 using base::TimeTicks;
84 using blink::WebGestureEvent;
85 using blink::WebInputEvent;
86 using blink::WebKeyboardEvent;
87 using blink::WebMouseEvent;
88 using blink::WebMouseWheelEvent;
89 using blink::WebTextDirection;
91 namespace content {
92 namespace {
94 bool g_check_for_pending_resize_ack = true;
96 typedef std::pair<int32, int32> RenderWidgetHostID;
97 typedef base::hash_map<RenderWidgetHostID, RenderWidgetHostImpl*>
98 RoutingIDWidgetMap;
99 base::LazyInstance<RoutingIDWidgetMap> g_routing_id_widget_map =
100 LAZY_INSTANCE_INITIALIZER;
102 int GetInputRouterViewFlagsFromCompositorFrameMetadata(
103 const cc::CompositorFrameMetadata metadata) {
104 int view_flags = InputRouter::VIEW_FLAGS_NONE;
106 if (metadata.min_page_scale_factor == metadata.max_page_scale_factor)
107 view_flags |= InputRouter::FIXED_PAGE_SCALE;
109 const float window_width_dip = std::ceil(
110 metadata.page_scale_factor * metadata.scrollable_viewport_size.width());
111 const float content_width_css = metadata.root_layer_size.width();
112 if (content_width_css <= window_width_dip)
113 view_flags |= InputRouter::MOBILE_VIEWPORT;
115 return view_flags;
118 // Implements the RenderWidgetHostIterator interface. It keeps a list of
119 // RenderWidgetHosts, and makes sure it returns a live RenderWidgetHost at each
120 // iteration (or NULL if there isn't any left).
121 class RenderWidgetHostIteratorImpl : public RenderWidgetHostIterator {
122 public:
123 RenderWidgetHostIteratorImpl()
124 : current_index_(0) {
127 ~RenderWidgetHostIteratorImpl() override {}
129 void Add(RenderWidgetHost* host) {
130 hosts_.push_back(RenderWidgetHostID(host->GetProcess()->GetID(),
131 host->GetRoutingID()));
134 // RenderWidgetHostIterator:
135 RenderWidgetHost* GetNextHost() override {
136 RenderWidgetHost* host = NULL;
137 while (current_index_ < hosts_.size() && !host) {
138 RenderWidgetHostID id = hosts_[current_index_];
139 host = RenderWidgetHost::FromID(id.first, id.second);
140 ++current_index_;
142 return host;
145 private:
146 std::vector<RenderWidgetHostID> hosts_;
147 size_t current_index_;
149 DISALLOW_COPY_AND_ASSIGN(RenderWidgetHostIteratorImpl);
152 } // namespace
154 ///////////////////////////////////////////////////////////////////////////////
155 // RenderWidgetHostImpl
157 RenderWidgetHostImpl::RenderWidgetHostImpl(RenderWidgetHostDelegate* delegate,
158 RenderProcessHost* process,
159 int routing_id,
160 bool hidden)
161 : view_(NULL),
162 hung_renderer_delay_(
163 base::TimeDelta::FromMilliseconds(kHungRendererDelayMs)),
164 renderer_initialized_(false),
165 delegate_(delegate),
166 process_(process),
167 routing_id_(routing_id),
168 surface_id_(0),
169 is_loading_(false),
170 is_hidden_(hidden),
171 repaint_ack_pending_(false),
172 resize_ack_pending_(false),
173 auto_resize_enabled_(false),
174 waiting_for_screen_rects_ack_(false),
175 needs_repainting_on_restore_(false),
176 is_unresponsive_(false),
177 in_flight_event_count_(0),
178 in_get_backing_store_(false),
179 ignore_input_events_(false),
180 input_method_active_(false),
181 text_direction_updated_(false),
182 text_direction_(blink::WebTextDirectionLeftToRight),
183 text_direction_canceled_(false),
184 suppress_next_char_events_(false),
185 pending_mouse_lock_request_(false),
186 allow_privileged_mouse_lock_(false),
187 has_touch_handler_(false),
188 next_browser_snapshot_id_(1),
189 owned_by_render_frame_host_(false),
190 is_focused_(false),
191 weak_factory_(this) {
192 CHECK(delegate_);
193 if (routing_id_ == MSG_ROUTING_NONE) {
194 routing_id_ = process_->GetNextRoutingID();
195 surface_id_ = GpuSurfaceTracker::Get()->AddSurfaceForRenderer(
196 process_->GetID(),
197 routing_id_);
198 } else {
199 // TODO(piman): This is a O(N) lookup, where we could forward the
200 // information from the RenderWidgetHelper. The problem is that doing so
201 // currently leaks outside of content all the way to chrome classes, and
202 // would be a layering violation. Since we don't expect more than a few
203 // hundreds of RWH, this seems acceptable. Revisit if performance become a
204 // problem, for example by tracking in the RenderWidgetHelper the routing id
205 // (and surface id) that have been created, but whose RWH haven't yet.
206 surface_id_ = GpuSurfaceTracker::Get()->LookupSurfaceForRenderer(
207 process_->GetID(),
208 routing_id_);
209 DCHECK(surface_id_);
212 std::pair<RoutingIDWidgetMap::iterator, bool> result =
213 g_routing_id_widget_map.Get().insert(std::make_pair(
214 RenderWidgetHostID(process->GetID(), routing_id_), this));
215 CHECK(result.second) << "Inserting a duplicate item!";
216 process_->AddRoute(routing_id_, this);
218 // If we're initially visible, tell the process host that we're alive.
219 // Otherwise we'll notify the process host when we are first shown.
220 if (!hidden)
221 process_->WidgetRestored();
223 latency_tracker_.Initialize(routing_id_, GetProcess()->GetID());
225 input_router_.reset(new InputRouterImpl(
226 process_, this, this, routing_id_, GetInputRouterConfigForPlatform()));
228 touch_emulator_.reset();
230 RenderViewHostImpl* rvh = static_cast<RenderViewHostImpl*>(
231 IsRenderView() ? RenderViewHost::From(this) : NULL);
232 if (BrowserPluginGuest::IsGuest(rvh) ||
233 !base::CommandLine::ForCurrentProcess()->HasSwitch(
234 switches::kDisableHangMonitor)) {
235 hang_monitor_timeout_.reset(new TimeoutMonitor(
236 base::Bind(&RenderWidgetHostImpl::RendererIsUnresponsive,
237 weak_factory_.GetWeakPtr())));
241 RenderWidgetHostImpl::~RenderWidgetHostImpl() {
242 if (view_weak_)
243 view_weak_->RenderWidgetHostGone();
244 SetView(NULL);
246 GpuSurfaceTracker::Get()->RemoveSurface(surface_id_);
247 surface_id_ = 0;
249 process_->RemoveRoute(routing_id_);
250 g_routing_id_widget_map.Get().erase(
251 RenderWidgetHostID(process_->GetID(), routing_id_));
253 if (delegate_)
254 delegate_->RenderWidgetDeleted(this);
257 // static
258 RenderWidgetHost* RenderWidgetHost::FromID(
259 int32 process_id,
260 int32 routing_id) {
261 return RenderWidgetHostImpl::FromID(process_id, routing_id);
264 // static
265 RenderWidgetHostImpl* RenderWidgetHostImpl::FromID(
266 int32 process_id,
267 int32 routing_id) {
268 DCHECK_CURRENTLY_ON(BrowserThread::UI);
269 RoutingIDWidgetMap* widgets = g_routing_id_widget_map.Pointer();
270 RoutingIDWidgetMap::iterator it = widgets->find(
271 RenderWidgetHostID(process_id, routing_id));
272 return it == widgets->end() ? NULL : it->second;
275 // static
276 scoped_ptr<RenderWidgetHostIterator> RenderWidgetHost::GetRenderWidgetHosts() {
277 RenderWidgetHostIteratorImpl* hosts = new RenderWidgetHostIteratorImpl();
278 RoutingIDWidgetMap* widgets = g_routing_id_widget_map.Pointer();
279 for (RoutingIDWidgetMap::const_iterator it = widgets->begin();
280 it != widgets->end();
281 ++it) {
282 RenderWidgetHost* widget = it->second;
284 if (!widget->IsRenderView()) {
285 hosts->Add(widget);
286 continue;
289 // Add only active RenderViewHosts.
290 RenderViewHost* rvh = RenderViewHost::From(widget);
291 if (static_cast<RenderViewHostImpl*>(rvh)->is_active())
292 hosts->Add(widget);
295 return scoped_ptr<RenderWidgetHostIterator>(hosts);
298 // static
299 scoped_ptr<RenderWidgetHostIterator>
300 RenderWidgetHostImpl::GetAllRenderWidgetHosts() {
301 RenderWidgetHostIteratorImpl* hosts = new RenderWidgetHostIteratorImpl();
302 RoutingIDWidgetMap* widgets = g_routing_id_widget_map.Pointer();
303 for (RoutingIDWidgetMap::const_iterator it = widgets->begin();
304 it != widgets->end();
305 ++it) {
306 hosts->Add(it->second);
309 return scoped_ptr<RenderWidgetHostIterator>(hosts);
312 // static
313 RenderWidgetHostImpl* RenderWidgetHostImpl::From(RenderWidgetHost* rwh) {
314 return rwh->AsRenderWidgetHostImpl();
317 void RenderWidgetHostImpl::SetView(RenderWidgetHostViewBase* view) {
318 if (view)
319 view_weak_ = view->GetWeakPtr();
320 else
321 view_weak_.reset();
322 view_ = view;
324 // If the renderer has not yet been initialized, then the surface ID
325 // namespace will be sent during initialization.
326 if (view_ && renderer_initialized_) {
327 Send(new ViewMsg_SetSurfaceIdNamespace(routing_id_,
328 view_->GetSurfaceIdNamespace()));
331 GpuSurfaceTracker::Get()->SetSurfaceHandle(
332 surface_id_, GetCompositingSurface());
334 synthetic_gesture_controller_.reset();
337 RenderProcessHost* RenderWidgetHostImpl::GetProcess() const {
338 return process_;
341 int RenderWidgetHostImpl::GetRoutingID() const {
342 return routing_id_;
345 RenderWidgetHostView* RenderWidgetHostImpl::GetView() const {
346 return view_;
349 RenderWidgetHostImpl* RenderWidgetHostImpl::AsRenderWidgetHostImpl() {
350 return this;
353 gfx::NativeViewId RenderWidgetHostImpl::GetNativeViewId() const {
354 if (view_)
355 return view_->GetNativeViewId();
356 return 0;
359 gfx::GLSurfaceHandle RenderWidgetHostImpl::GetCompositingSurface() {
360 if (view_)
361 return view_->GetCompositingSurface();
362 return gfx::GLSurfaceHandle();
365 void RenderWidgetHostImpl::ResetSizeAndRepaintPendingFlags() {
366 resize_ack_pending_ = false;
367 if (repaint_ack_pending_) {
368 TRACE_EVENT_ASYNC_END0(
369 "renderer_host", "RenderWidgetHostImpl::repaint_ack_pending_", this);
371 repaint_ack_pending_ = false;
372 if (old_resize_params_)
373 old_resize_params_->new_size = gfx::Size();
376 void RenderWidgetHostImpl::SendScreenRects() {
377 if (!renderer_initialized_ || waiting_for_screen_rects_ack_)
378 return;
380 if (is_hidden_) {
381 // On GTK, this comes in for backgrounded tabs. Ignore, to match what
382 // happens on Win & Mac, and when the view is shown it'll call this again.
383 return;
386 if (!view_)
387 return;
389 last_view_screen_rect_ = view_->GetViewBounds();
390 last_window_screen_rect_ = view_->GetBoundsInRootWindow();
391 Send(new ViewMsg_UpdateScreenRects(
392 GetRoutingID(), last_view_screen_rect_, last_window_screen_rect_));
393 if (delegate_)
394 delegate_->DidSendScreenRects(this);
395 waiting_for_screen_rects_ack_ = true;
398 void RenderWidgetHostImpl::SuppressNextCharEvents() {
399 suppress_next_char_events_ = true;
402 void RenderWidgetHostImpl::FlushInput() {
403 input_router_->RequestNotificationWhenFlushed();
404 if (synthetic_gesture_controller_)
405 synthetic_gesture_controller_->Flush(base::TimeTicks::Now());
408 void RenderWidgetHostImpl::SetNeedsFlush() {
409 if (view_)
410 view_->OnSetNeedsFlushInput();
413 void RenderWidgetHostImpl::Init() {
414 DCHECK(process_->HasConnection());
416 renderer_initialized_ = true;
418 GpuSurfaceTracker::Get()->SetSurfaceHandle(
419 surface_id_, GetCompositingSurface());
421 // Send the ack along with the information on placement.
422 Send(new ViewMsg_CreatingNew_ACK(routing_id_));
423 GetProcess()->ResumeRequestsForView(routing_id_);
425 // If the RWHV has not yet been set, the surface ID namespace will get
426 // passed down by the call to SetView().
427 if (view_) {
428 Send(new ViewMsg_SetSurfaceIdNamespace(routing_id_,
429 view_->GetSurfaceIdNamespace()));
432 WasResized();
435 void RenderWidgetHostImpl::InitForFrame() {
436 DCHECK(process_->HasConnection());
437 renderer_initialized_ = true;
440 void RenderWidgetHostImpl::Shutdown() {
441 RejectMouseLockOrUnlockIfNecessary();
443 if (process_->HasConnection()) {
444 // Tell the renderer object to close.
445 bool rv = Send(new ViewMsg_Close(routing_id_));
446 DCHECK(rv);
449 Destroy();
452 bool RenderWidgetHostImpl::IsLoading() const {
453 return is_loading_;
456 bool RenderWidgetHostImpl::IsRenderView() const {
457 return false;
460 bool RenderWidgetHostImpl::OnMessageReceived(const IPC::Message &msg) {
461 bool handled = true;
462 IPC_BEGIN_MESSAGE_MAP(RenderWidgetHostImpl, msg)
463 IPC_MESSAGE_HANDLER(FrameHostMsg_RenderProcessGone, OnRenderProcessGone)
464 IPC_MESSAGE_HANDLER(InputHostMsg_QueueSyntheticGesture,
465 OnQueueSyntheticGesture)
466 IPC_MESSAGE_HANDLER(InputHostMsg_ImeCancelComposition,
467 OnImeCancelComposition)
468 IPC_MESSAGE_HANDLER(ViewHostMsg_RenderViewReady, OnRenderViewReady)
469 IPC_MESSAGE_HANDLER(ViewHostMsg_Close, OnClose)
470 IPC_MESSAGE_HANDLER(ViewHostMsg_UpdateScreenRects_ACK,
471 OnUpdateScreenRectsAck)
472 IPC_MESSAGE_HANDLER(ViewHostMsg_RequestMove, OnRequestMove)
473 IPC_MESSAGE_HANDLER(ViewHostMsg_SetTooltipText, OnSetTooltipText)
474 IPC_MESSAGE_HANDLER_GENERIC(ViewHostMsg_SwapCompositorFrame,
475 OnSwapCompositorFrame(msg))
476 IPC_MESSAGE_HANDLER(ViewHostMsg_UpdateRect, OnUpdateRect)
477 IPC_MESSAGE_HANDLER(ViewHostMsg_Focus, OnFocus)
478 IPC_MESSAGE_HANDLER(ViewHostMsg_Blur, OnBlur)
479 IPC_MESSAGE_HANDLER(ViewHostMsg_SetCursor, OnSetCursor)
480 IPC_MESSAGE_HANDLER(ViewHostMsg_TextInputTypeChanged,
481 OnTextInputTypeChanged)
482 IPC_MESSAGE_HANDLER(ViewHostMsg_LockMouse, OnLockMouse)
483 IPC_MESSAGE_HANDLER(ViewHostMsg_UnlockMouse, OnUnlockMouse)
484 IPC_MESSAGE_HANDLER(ViewHostMsg_ShowDisambiguationPopup,
485 OnShowDisambiguationPopup)
486 IPC_MESSAGE_HANDLER(ViewHostMsg_SelectionChanged, OnSelectionChanged)
487 IPC_MESSAGE_HANDLER(ViewHostMsg_SelectionBoundsChanged,
488 OnSelectionBoundsChanged)
489 #if defined(OS_WIN)
490 IPC_MESSAGE_HANDLER(ViewHostMsg_WindowlessPluginDummyWindowCreated,
491 OnWindowlessPluginDummyWindowCreated)
492 IPC_MESSAGE_HANDLER(ViewHostMsg_WindowlessPluginDummyWindowDestroyed,
493 OnWindowlessPluginDummyWindowDestroyed)
494 #endif
495 IPC_MESSAGE_HANDLER(InputHostMsg_ImeCompositionRangeChanged,
496 OnImeCompositionRangeChanged)
497 IPC_MESSAGE_UNHANDLED(handled = false)
498 IPC_END_MESSAGE_MAP()
500 if (!handled && input_router_ && input_router_->OnMessageReceived(msg))
501 return true;
503 if (!handled && view_ && view_->OnMessageReceived(msg))
504 return true;
506 return handled;
509 bool RenderWidgetHostImpl::Send(IPC::Message* msg) {
510 if (IPC_MESSAGE_ID_CLASS(msg->type()) == InputMsgStart)
511 return input_router_->SendInput(make_scoped_ptr(msg));
513 return process_->Send(msg);
516 void RenderWidgetHostImpl::SetIsLoading(bool is_loading) {
517 is_loading_ = is_loading;
518 if (!view_)
519 return;
520 view_->SetIsLoading(is_loading);
523 void RenderWidgetHostImpl::WasHidden() {
524 if (is_hidden_)
525 return;
527 TRACE_EVENT0("renderer_host", "RenderWidgetHostImpl::WasHidden");
528 is_hidden_ = true;
530 // Don't bother reporting hung state when we aren't active.
531 StopHangMonitorTimeout();
533 // If we have a renderer, then inform it that we are being hidden so it can
534 // reduce its resource utilization.
535 Send(new ViewMsg_WasHidden(routing_id_));
537 // Tell the RenderProcessHost we were hidden.
538 process_->WidgetHidden();
540 bool is_visible = false;
541 NotificationService::current()->Notify(
542 NOTIFICATION_RENDER_WIDGET_VISIBILITY_CHANGED,
543 Source<RenderWidgetHost>(this),
544 Details<bool>(&is_visible));
547 void RenderWidgetHostImpl::WasShown(const ui::LatencyInfo& latency_info) {
548 if (!is_hidden_)
549 return;
551 TRACE_EVENT0("renderer_host", "RenderWidgetHostImpl::WasShown");
552 is_hidden_ = false;
554 SendScreenRects();
556 // When hidden, timeout monitoring for input events is disabled. Restore it
557 // now to ensure consistent hang detection.
558 if (in_flight_event_count_)
559 RestartHangMonitorTimeout();
561 // Always repaint on restore.
562 bool needs_repainting = true;
563 needs_repainting_on_restore_ = false;
564 Send(new ViewMsg_WasShown(routing_id_, needs_repainting, latency_info));
566 process_->WidgetRestored();
568 bool is_visible = true;
569 NotificationService::current()->Notify(
570 NOTIFICATION_RENDER_WIDGET_VISIBILITY_CHANGED,
571 Source<RenderWidgetHost>(this),
572 Details<bool>(&is_visible));
574 // It's possible for our size to be out of sync with the renderer. The
575 // following is one case that leads to this:
576 // 1. WasResized -> Send ViewMsg_Resize to render
577 // 2. WasResized -> do nothing as resize_ack_pending_ is true
578 // 3. WasHidden
579 // 4. OnUpdateRect from (1) processed. Does NOT invoke WasResized as view
580 // is hidden. Now renderer/browser out of sync with what they think size
581 // is.
582 // By invoking WasResized the renderer is updated as necessary. WasResized
583 // does nothing if the sizes are already in sync.
585 // TODO: ideally ViewMsg_WasShown would take a size. This way, the renderer
586 // could handle both the restore and resize at once. This isn't that big a
587 // deal as RenderWidget::WasShown delays updating, so that the resize from
588 // WasResized is usually processed before the renderer is painted.
589 WasResized();
592 bool RenderWidgetHostImpl::GetResizeParams(
593 ViewMsg_Resize_Params* resize_params) {
594 *resize_params = ViewMsg_Resize_Params();
596 GetWebScreenInfo(&resize_params->screen_info);
597 resize_params->resizer_rect = GetRootWindowResizerRect();
599 if (view_) {
600 resize_params->new_size = view_->GetRequestedRendererSize();
601 resize_params->physical_backing_size = view_->GetPhysicalBackingSize();
602 resize_params->top_controls_height = view_->GetTopControlsHeight();
603 resize_params->top_controls_shrink_blink_size =
604 view_->DoTopControlsShrinkBlinkSize();
605 resize_params->visible_viewport_size = view_->GetVisibleViewportSize();
606 resize_params->is_fullscreen_granted = IsFullscreenGranted();
607 resize_params->display_mode = GetDisplayMode();
610 const bool size_changed =
611 !old_resize_params_ ||
612 old_resize_params_->new_size != resize_params->new_size ||
613 (old_resize_params_->physical_backing_size.IsEmpty() &&
614 !resize_params->physical_backing_size.IsEmpty());
615 bool dirty = size_changed ||
616 old_resize_params_->screen_info != resize_params->screen_info ||
617 old_resize_params_->physical_backing_size !=
618 resize_params->physical_backing_size ||
619 old_resize_params_->is_fullscreen_granted !=
620 resize_params->is_fullscreen_granted ||
621 old_resize_params_->display_mode != resize_params->display_mode ||
622 old_resize_params_->top_controls_height !=
623 resize_params->top_controls_height ||
624 old_resize_params_->top_controls_shrink_blink_size !=
625 resize_params->top_controls_shrink_blink_size ||
626 old_resize_params_->visible_viewport_size !=
627 resize_params->visible_viewport_size;
629 // We don't expect to receive an ACK when the requested size or the physical
630 // backing size is empty, or when the main viewport size didn't change.
631 resize_params->needs_resize_ack =
632 g_check_for_pending_resize_ack && !resize_params->new_size.IsEmpty() &&
633 !resize_params->physical_backing_size.IsEmpty() && size_changed;
635 return dirty;
638 void RenderWidgetHostImpl::SetInitialRenderSizeParams(
639 const ViewMsg_Resize_Params& resize_params) {
640 resize_ack_pending_ = resize_params.needs_resize_ack;
642 old_resize_params_ =
643 make_scoped_ptr(new ViewMsg_Resize_Params(resize_params));
646 void RenderWidgetHostImpl::WasResized() {
647 // Skip if the |delegate_| has already been detached because
648 // it's web contents is being deleted.
649 if (resize_ack_pending_ || !process_->HasConnection() || !view_ ||
650 !renderer_initialized_ || auto_resize_enabled_ || !delegate_) {
651 return;
654 scoped_ptr<ViewMsg_Resize_Params> params(new ViewMsg_Resize_Params);
655 if (!GetResizeParams(params.get()))
656 return;
658 bool width_changed =
659 !old_resize_params_ ||
660 old_resize_params_->new_size.width() != params->new_size.width();
661 if (Send(new ViewMsg_Resize(routing_id_, *params))) {
662 resize_ack_pending_ = params->needs_resize_ack;
663 old_resize_params_.swap(params);
666 if (delegate_)
667 delegate_->RenderWidgetWasResized(this, width_changed);
670 void RenderWidgetHostImpl::ResizeRectChanged(const gfx::Rect& new_rect) {
671 Send(new ViewMsg_ChangeResizeRect(routing_id_, new_rect));
674 void RenderWidgetHostImpl::GotFocus() {
675 Focus();
676 if (delegate_)
677 delegate_->RenderWidgetGotFocus(this);
680 void RenderWidgetHostImpl::Focus() {
681 is_focused_ = true;
683 Send(new InputMsg_SetFocus(routing_id_, true));
686 void RenderWidgetHostImpl::Blur() {
687 is_focused_ = false;
689 // If there is a pending mouse lock request, we don't want to reject it at
690 // this point. The user can switch focus back to this view and approve the
691 // request later.
692 if (IsMouseLocked())
693 view_->UnlockMouse();
695 if (touch_emulator_)
696 touch_emulator_->CancelTouch();
698 Send(new InputMsg_SetFocus(routing_id_, false));
701 void RenderWidgetHostImpl::LostCapture() {
702 if (touch_emulator_)
703 touch_emulator_->CancelTouch();
705 Send(new InputMsg_MouseCaptureLost(routing_id_));
708 void RenderWidgetHostImpl::SetActive(bool active) {
709 Send(new ViewMsg_SetActive(routing_id_, active));
712 void RenderWidgetHostImpl::LostMouseLock() {
713 Send(new ViewMsg_MouseLockLost(routing_id_));
716 void RenderWidgetHostImpl::ViewDestroyed() {
717 RejectMouseLockOrUnlockIfNecessary();
719 // TODO(evanm): tracking this may no longer be necessary;
720 // eliminate this function if so.
721 SetView(NULL);
724 void RenderWidgetHostImpl::CopyFromBackingStore(
725 const gfx::Rect& src_subrect,
726 const gfx::Size& accelerated_dst_size,
727 ReadbackRequestCallback& callback,
728 const SkColorType preferred_color_type) {
729 if (view_) {
730 TRACE_EVENT0("browser",
731 "RenderWidgetHostImpl::CopyFromBackingStore::FromCompositingSurface");
732 gfx::Rect accelerated_copy_rect = src_subrect.IsEmpty() ?
733 gfx::Rect(view_->GetViewBounds().size()) : src_subrect;
734 view_->CopyFromCompositingSurface(accelerated_copy_rect,
735 accelerated_dst_size, callback,
736 preferred_color_type);
737 return;
740 callback.Run(SkBitmap(), content::READBACK_FAILED);
743 bool RenderWidgetHostImpl::CanCopyFromBackingStore() {
744 if (view_)
745 return view_->IsSurfaceAvailableForCopy();
746 return false;
749 #if defined(OS_ANDROID)
750 void RenderWidgetHostImpl::LockBackingStore() {
751 if (view_)
752 view_->LockCompositingSurface();
755 void RenderWidgetHostImpl::UnlockBackingStore() {
756 if (view_)
757 view_->UnlockCompositingSurface();
759 #endif
761 #if defined(OS_MACOSX)
762 void RenderWidgetHostImpl::PauseForPendingResizeOrRepaints() {
763 TRACE_EVENT0("browser",
764 "RenderWidgetHostImpl::PauseForPendingResizeOrRepaints");
766 if (!CanPauseForPendingResizeOrRepaints())
767 return;
769 WaitForSurface();
772 bool RenderWidgetHostImpl::CanPauseForPendingResizeOrRepaints() {
773 // Do not pause if the view is hidden.
774 if (is_hidden())
775 return false;
777 // Do not pause if there is not a paint or resize already coming.
778 if (!repaint_ack_pending_ && !resize_ack_pending_)
779 return false;
781 return true;
784 void RenderWidgetHostImpl::WaitForSurface() {
785 // How long to (synchronously) wait for the renderer to respond with a
786 // new frame when our current frame doesn't exist or is the wrong size.
787 // This timeout impacts the "choppiness" of our window resize.
788 const int kPaintMsgTimeoutMS = 50;
790 if (!view_)
791 return;
793 // The view_size will be current_size_ for auto-sized views and otherwise the
794 // size of the view_. (For auto-sized views, current_size_ is updated during
795 // UpdateRect messages.)
796 gfx::Size view_size = current_size_;
797 if (!auto_resize_enabled_) {
798 // Get the desired size from the current view bounds.
799 gfx::Rect view_rect = view_->GetViewBounds();
800 if (view_rect.IsEmpty())
801 return;
802 view_size = view_rect.size();
805 TRACE_EVENT2("renderer_host",
806 "RenderWidgetHostImpl::WaitForSurface",
807 "width",
808 base::IntToString(view_size.width()),
809 "height",
810 base::IntToString(view_size.height()));
812 // We should not be asked to paint while we are hidden. If we are hidden,
813 // then it means that our consumer failed to call WasShown.
814 DCHECK(!is_hidden_) << "WaitForSurface called while hidden!";
816 // We should never be called recursively; this can theoretically lead to
817 // infinite recursion and almost certainly leads to lower performance.
818 DCHECK(!in_get_backing_store_) << "WaitForSurface called recursively!";
819 base::AutoReset<bool> auto_reset_in_get_backing_store(
820 &in_get_backing_store_, true);
822 // We might have a surface that we can use already.
823 if (view_->HasAcceleratedSurface(view_size))
824 return;
826 // Request that the renderer produce a frame of the right size, if it
827 // hasn't been requested already.
828 if (!repaint_ack_pending_ && !resize_ack_pending_) {
829 repaint_start_time_ = TimeTicks::Now();
830 repaint_ack_pending_ = true;
831 TRACE_EVENT_ASYNC_BEGIN0(
832 "renderer_host", "RenderWidgetHostImpl::repaint_ack_pending_", this);
833 Send(new ViewMsg_Repaint(routing_id_, view_size));
836 // Pump a nested message loop until we time out or get a frame of the right
837 // size.
838 TimeTicks start_time = TimeTicks::Now();
839 TimeDelta time_left = TimeDelta::FromMilliseconds(kPaintMsgTimeoutMS);
840 TimeTicks timeout_time = start_time + time_left;
841 while (1) {
842 TRACE_EVENT0("renderer_host", "WaitForSurface::WaitForSingleTaskToRun");
843 if (RenderWidgetResizeHelper::Get()->WaitForSingleTaskToRun(time_left)) {
844 // For auto-resized views, current_size_ determines the view_size and it
845 // may have changed during the handling of an UpdateRect message.
846 if (auto_resize_enabled_)
847 view_size = current_size_;
848 if (view_->HasAcceleratedSurface(view_size))
849 break;
851 time_left = timeout_time - TimeTicks::Now();
852 if (time_left <= TimeDelta::FromSeconds(0)) {
853 TRACE_EVENT0("renderer_host", "WaitForSurface::Timeout");
854 break;
858 UMA_HISTOGRAM_CUSTOM_TIMES("OSX.RendererHost.SurfaceWaitTime",
859 TimeTicks::Now() - start_time,
860 TimeDelta::FromMilliseconds(1),
861 TimeDelta::FromMilliseconds(200), 50);
863 #endif
865 bool RenderWidgetHostImpl::ScheduleComposite() {
866 if (is_hidden_ || current_size_.IsEmpty() || repaint_ack_pending_ ||
867 resize_ack_pending_) {
868 return false;
871 // Send out a request to the renderer to paint the view if required.
872 repaint_start_time_ = TimeTicks::Now();
873 repaint_ack_pending_ = true;
874 TRACE_EVENT_ASYNC_BEGIN0(
875 "renderer_host", "RenderWidgetHostImpl::repaint_ack_pending_", this);
876 Send(new ViewMsg_Repaint(routing_id_, current_size_));
877 return true;
880 void RenderWidgetHostImpl::StartHangMonitorTimeout(base::TimeDelta delay) {
881 if (hang_monitor_timeout_)
882 hang_monitor_timeout_->Start(delay);
885 void RenderWidgetHostImpl::RestartHangMonitorTimeout() {
886 if (hang_monitor_timeout_)
887 hang_monitor_timeout_->Restart(hung_renderer_delay_);
890 void RenderWidgetHostImpl::StopHangMonitorTimeout() {
891 if (hang_monitor_timeout_)
892 hang_monitor_timeout_->Stop();
893 RendererIsResponsive();
896 void RenderWidgetHostImpl::ForwardMouseEvent(const WebMouseEvent& mouse_event) {
897 ForwardMouseEventWithLatencyInfo(mouse_event, ui::LatencyInfo());
900 void RenderWidgetHostImpl::ForwardMouseEventWithLatencyInfo(
901 const blink::WebMouseEvent& mouse_event,
902 const ui::LatencyInfo& ui_latency) {
903 TRACE_EVENT2("input", "RenderWidgetHostImpl::ForwardMouseEvent",
904 "x", mouse_event.x, "y", mouse_event.y);
906 for (size_t i = 0; i < mouse_event_callbacks_.size(); ++i) {
907 if (mouse_event_callbacks_[i].Run(mouse_event))
908 return;
911 if (IgnoreInputEvents())
912 return;
914 if (touch_emulator_ && touch_emulator_->HandleMouseEvent(mouse_event))
915 return;
917 MouseEventWithLatencyInfo mouse_with_latency(mouse_event, ui_latency);
918 latency_tracker_.OnInputEvent(mouse_event, &mouse_with_latency.latency);
919 input_router_->SendMouseEvent(mouse_with_latency);
921 // Pass mouse state to gpu service if the subscribe uniform
922 // extension is enabled.
923 if (process_->SubscribeUniformEnabled()) {
924 gpu::ValueState state;
925 state.int_value[0] = mouse_event.x;
926 state.int_value[1] = mouse_event.y;
927 // TODO(orglofch) Separate the mapping of pending value states to the
928 // Gpu Service to be per RWH not per process
929 process_->SendUpdateValueState(GL_MOUSE_POSITION_CHROMIUM, state);
933 void RenderWidgetHostImpl::ForwardWheelEvent(
934 const WebMouseWheelEvent& wheel_event) {
935 ForwardWheelEventWithLatencyInfo(wheel_event, ui::LatencyInfo());
938 void RenderWidgetHostImpl::ForwardWheelEventWithLatencyInfo(
939 const blink::WebMouseWheelEvent& wheel_event,
940 const ui::LatencyInfo& ui_latency) {
941 TRACE_EVENT0("input", "RenderWidgetHostImpl::ForwardWheelEvent");
943 if (IgnoreInputEvents())
944 return;
946 if (touch_emulator_ && touch_emulator_->HandleMouseWheelEvent(wheel_event))
947 return;
949 MouseWheelEventWithLatencyInfo wheel_with_latency(wheel_event, ui_latency);
950 latency_tracker_.OnInputEvent(wheel_event, &wheel_with_latency.latency);
951 input_router_->SendWheelEvent(wheel_with_latency);
954 void RenderWidgetHostImpl::ForwardGestureEvent(
955 const blink::WebGestureEvent& gesture_event) {
956 ForwardGestureEventWithLatencyInfo(gesture_event, ui::LatencyInfo());
959 void RenderWidgetHostImpl::ForwardGestureEventWithLatencyInfo(
960 const blink::WebGestureEvent& gesture_event,
961 const ui::LatencyInfo& ui_latency) {
962 TRACE_EVENT0("input", "RenderWidgetHostImpl::ForwardGestureEvent");
963 // Early out if necessary, prior to performing latency logic.
964 if (IgnoreInputEvents())
965 return;
967 if (delegate_->PreHandleGestureEvent(gesture_event))
968 return;
970 GestureEventWithLatencyInfo gesture_with_latency(gesture_event, ui_latency);
971 latency_tracker_.OnInputEvent(gesture_event, &gesture_with_latency.latency);
972 input_router_->SendGestureEvent(gesture_with_latency);
975 void RenderWidgetHostImpl::ForwardEmulatedTouchEvent(
976 const blink::WebTouchEvent& touch_event) {
977 TRACE_EVENT0("input", "RenderWidgetHostImpl::ForwardEmulatedTouchEvent");
979 TouchEventWithLatencyInfo touch_with_latency(touch_event);
980 latency_tracker_.OnInputEvent(touch_event, &touch_with_latency.latency);
981 input_router_->SendTouchEvent(touch_with_latency);
984 void RenderWidgetHostImpl::ForwardTouchEventWithLatencyInfo(
985 const blink::WebTouchEvent& touch_event,
986 const ui::LatencyInfo& ui_latency) {
987 TRACE_EVENT0("input", "RenderWidgetHostImpl::ForwardTouchEvent");
989 // Always forward TouchEvents for touch stream consistency. They will be
990 // ignored if appropriate in FilterInputEvent().
992 TouchEventWithLatencyInfo touch_with_latency(touch_event, ui_latency);
993 if (touch_emulator_ &&
994 touch_emulator_->HandleTouchEvent(touch_with_latency.event)) {
995 if (view_) {
996 view_->ProcessAckedTouchEvent(
997 touch_with_latency, INPUT_EVENT_ACK_STATE_CONSUMED);
999 return;
1002 latency_tracker_.OnInputEvent(touch_event, &touch_with_latency.latency);
1003 input_router_->SendTouchEvent(touch_with_latency);
1006 void RenderWidgetHostImpl::ForwardKeyboardEvent(
1007 const NativeWebKeyboardEvent& key_event) {
1008 TRACE_EVENT0("input", "RenderWidgetHostImpl::ForwardKeyboardEvent");
1009 if (IgnoreInputEvents())
1010 return;
1012 if (!process_->HasConnection())
1013 return;
1015 // First, let keypress listeners take a shot at handling the event. If a
1016 // listener handles the event, it should not be propagated to the renderer.
1017 if (KeyPressListenersHandleEvent(key_event)) {
1018 // Some keypresses that are accepted by the listener might have follow up
1019 // char events, which should be ignored.
1020 if (key_event.type == WebKeyboardEvent::RawKeyDown)
1021 suppress_next_char_events_ = true;
1022 return;
1025 if (key_event.type == WebKeyboardEvent::Char &&
1026 (key_event.windowsKeyCode == ui::VKEY_RETURN ||
1027 key_event.windowsKeyCode == ui::VKEY_SPACE)) {
1028 OnUserGesture();
1031 // Double check the type to make sure caller hasn't sent us nonsense that
1032 // will mess up our key queue.
1033 if (!WebInputEvent::isKeyboardEventType(key_event.type))
1034 return;
1036 if (suppress_next_char_events_) {
1037 // If preceding RawKeyDown event was handled by the browser, then we need
1038 // suppress all Char events generated by it. Please note that, one
1039 // RawKeyDown event may generate multiple Char events, so we can't reset
1040 // |suppress_next_char_events_| until we get a KeyUp or a RawKeyDown.
1041 if (key_event.type == WebKeyboardEvent::Char)
1042 return;
1043 // We get a KeyUp or a RawKeyDown event.
1044 suppress_next_char_events_ = false;
1047 bool is_shortcut = false;
1049 // Only pre-handle the key event if it's not handled by the input method.
1050 if (delegate_ && !key_event.skip_in_browser) {
1051 // We need to set |suppress_next_char_events_| to true if
1052 // PreHandleKeyboardEvent() returns true, but |this| may already be
1053 // destroyed at that time. So set |suppress_next_char_events_| true here,
1054 // then revert it afterwards when necessary.
1055 if (key_event.type == WebKeyboardEvent::RawKeyDown)
1056 suppress_next_char_events_ = true;
1058 // Tab switching/closing accelerators aren't sent to the renderer to avoid
1059 // a hung/malicious renderer from interfering.
1060 if (delegate_->PreHandleKeyboardEvent(key_event, &is_shortcut))
1061 return;
1063 if (key_event.type == WebKeyboardEvent::RawKeyDown)
1064 suppress_next_char_events_ = false;
1067 if (touch_emulator_ && touch_emulator_->HandleKeyboardEvent(key_event))
1068 return;
1070 ui::LatencyInfo latency;
1071 latency_tracker_.OnInputEvent(key_event, &latency);
1072 input_router_->SendKeyboardEvent(key_event, latency, is_shortcut);
1075 void RenderWidgetHostImpl::QueueSyntheticGesture(
1076 scoped_ptr<SyntheticGesture> synthetic_gesture,
1077 const base::Callback<void(SyntheticGesture::Result)>& on_complete) {
1078 if (!synthetic_gesture_controller_ && view_) {
1079 synthetic_gesture_controller_.reset(
1080 new SyntheticGestureController(
1081 view_->CreateSyntheticGestureTarget().Pass()));
1083 if (synthetic_gesture_controller_) {
1084 synthetic_gesture_controller_->QueueSyntheticGesture(
1085 synthetic_gesture.Pass(), on_complete);
1089 void RenderWidgetHostImpl::SetCursor(const WebCursor& cursor) {
1090 if (!view_)
1091 return;
1092 view_->UpdateCursor(cursor);
1095 void RenderWidgetHostImpl::ShowContextMenuAtPoint(const gfx::Point& point) {
1096 Send(new ViewMsg_ShowContextMenu(
1097 GetRoutingID(), ui::MENU_SOURCE_MOUSE, point));
1100 void RenderWidgetHostImpl::SendCursorVisibilityState(bool is_visible) {
1101 Send(new InputMsg_CursorVisibilityChange(GetRoutingID(), is_visible));
1104 int64 RenderWidgetHostImpl::GetLatencyComponentId() const {
1105 return latency_tracker_.latency_component_id();
1108 // static
1109 void RenderWidgetHostImpl::DisableResizeAckCheckForTesting() {
1110 g_check_for_pending_resize_ack = false;
1113 void RenderWidgetHostImpl::AddKeyPressEventCallback(
1114 const KeyPressEventCallback& callback) {
1115 key_press_event_callbacks_.push_back(callback);
1118 void RenderWidgetHostImpl::RemoveKeyPressEventCallback(
1119 const KeyPressEventCallback& callback) {
1120 for (size_t i = 0; i < key_press_event_callbacks_.size(); ++i) {
1121 if (key_press_event_callbacks_[i].Equals(callback)) {
1122 key_press_event_callbacks_.erase(
1123 key_press_event_callbacks_.begin() + i);
1124 return;
1129 void RenderWidgetHostImpl::AddMouseEventCallback(
1130 const MouseEventCallback& callback) {
1131 mouse_event_callbacks_.push_back(callback);
1134 void RenderWidgetHostImpl::RemoveMouseEventCallback(
1135 const MouseEventCallback& callback) {
1136 for (size_t i = 0; i < mouse_event_callbacks_.size(); ++i) {
1137 if (mouse_event_callbacks_[i].Equals(callback)) {
1138 mouse_event_callbacks_.erase(mouse_event_callbacks_.begin() + i);
1139 return;
1144 void RenderWidgetHostImpl::GetWebScreenInfo(blink::WebScreenInfo* result) {
1145 TRACE_EVENT0("renderer_host", "RenderWidgetHostImpl::GetWebScreenInfo");
1146 if (view_)
1147 view_->GetScreenInfo(result);
1148 else
1149 RenderWidgetHostViewBase::GetDefaultScreenInfo(result);
1150 // TODO(sievers): find a way to make this done another way so the method
1151 // can be const.
1152 latency_tracker_.set_device_scale_factor(result->deviceScaleFactor);
1155 const NativeWebKeyboardEvent*
1156 RenderWidgetHostImpl::GetLastKeyboardEvent() const {
1157 return input_router_->GetLastKeyboardEvent();
1160 void RenderWidgetHostImpl::NotifyScreenInfoChanged() {
1161 if (delegate_)
1162 delegate_->ScreenInfoChanged();
1164 // The resize message (which may not happen immediately) will carry with it
1165 // the screen info as well as the new size (if the screen has changed scale
1166 // factor).
1167 WasResized();
1170 void RenderWidgetHostImpl::GetSnapshotFromBrowser(
1171 const base::Callback<void(const unsigned char*,size_t)> callback) {
1172 int id = next_browser_snapshot_id_++;
1173 pending_browser_snapshots_.insert(std::make_pair(id, callback));
1174 Send(new ViewMsg_ForceRedraw(GetRoutingID(), id));
1177 void RenderWidgetHostImpl::OnSelectionChanged(const base::string16& text,
1178 size_t offset,
1179 const gfx::Range& range) {
1180 if (view_)
1181 view_->SelectionChanged(text, offset, range);
1184 void RenderWidgetHostImpl::OnSelectionBoundsChanged(
1185 const ViewHostMsg_SelectionBounds_Params& params) {
1186 if (view_) {
1187 view_->SelectionBoundsChanged(params);
1191 void RenderWidgetHostImpl::UpdateVSyncParameters(base::TimeTicks timebase,
1192 base::TimeDelta interval) {
1193 Send(new ViewMsg_UpdateVSyncParameters(GetRoutingID(), timebase, interval));
1196 void RenderWidgetHostImpl::RendererExited(base::TerminationStatus status,
1197 int exit_code) {
1198 // Clearing this flag causes us to re-create the renderer when recovering
1199 // from a crashed renderer.
1200 renderer_initialized_ = false;
1202 waiting_for_screen_rects_ack_ = false;
1204 // Must reset these to ensure that keyboard events work with a new renderer.
1205 suppress_next_char_events_ = false;
1207 // Reset some fields in preparation for recovering from a crash.
1208 ResetSizeAndRepaintPendingFlags();
1209 current_size_.SetSize(0, 0);
1210 // After the renderer crashes, the view is destroyed and so the
1211 // RenderWidgetHost cannot track its visibility anymore. We assume such
1212 // RenderWidgetHost to be visible for the sake of internal accounting - be
1213 // careful about changing this - see http://crbug.com/401859.
1215 // We need to at least make sure that the RenderProcessHost is notified about
1216 // the |is_hidden_| change, so that the renderer will have correct visibility
1217 // set when respawned.
1218 if (is_hidden_) {
1219 process_->WidgetRestored();
1220 is_hidden_ = false;
1223 // Reset this to ensure the hung renderer mechanism is working properly.
1224 in_flight_event_count_ = 0;
1225 StopHangMonitorTimeout();
1227 if (view_) {
1228 GpuSurfaceTracker::Get()->SetSurfaceHandle(surface_id_,
1229 gfx::GLSurfaceHandle());
1230 view_->RenderProcessGone(status, exit_code);
1231 view_ = NULL; // The View should be deleted by RenderProcessGone.
1232 view_weak_.reset();
1235 // Reconstruct the input router to ensure that it has fresh state for a new
1236 // renderer. Otherwise it may be stuck waiting for the old renderer to ack an
1237 // event. (In particular, the above call to view_->RenderProcessGone will
1238 // destroy the aura window, which may dispatch a synthetic mouse move.)
1239 input_router_.reset(new InputRouterImpl(
1240 process_, this, this, routing_id_, GetInputRouterConfigForPlatform()));
1242 synthetic_gesture_controller_.reset();
1245 void RenderWidgetHostImpl::UpdateTextDirection(WebTextDirection direction) {
1246 text_direction_updated_ = true;
1247 text_direction_ = direction;
1250 void RenderWidgetHostImpl::CancelUpdateTextDirection() {
1251 if (text_direction_updated_)
1252 text_direction_canceled_ = true;
1255 void RenderWidgetHostImpl::NotifyTextDirection() {
1256 if (text_direction_updated_) {
1257 if (!text_direction_canceled_)
1258 Send(new ViewMsg_SetTextDirection(GetRoutingID(), text_direction_));
1259 text_direction_updated_ = false;
1260 text_direction_canceled_ = false;
1264 void RenderWidgetHostImpl::SetInputMethodActive(bool activate) {
1265 input_method_active_ = activate;
1266 Send(new ViewMsg_SetInputMethodActive(GetRoutingID(), activate));
1269 void RenderWidgetHostImpl::CandidateWindowShown() {
1270 Send(new ViewMsg_CandidateWindowShown(GetRoutingID()));
1273 void RenderWidgetHostImpl::CandidateWindowUpdated() {
1274 Send(new ViewMsg_CandidateWindowUpdated(GetRoutingID()));
1277 void RenderWidgetHostImpl::CandidateWindowHidden() {
1278 Send(new ViewMsg_CandidateWindowHidden(GetRoutingID()));
1281 void RenderWidgetHostImpl::ImeSetComposition(
1282 const base::string16& text,
1283 const std::vector<blink::WebCompositionUnderline>& underlines,
1284 int selection_start,
1285 int selection_end) {
1286 Send(new InputMsg_ImeSetComposition(
1287 GetRoutingID(), text, underlines, selection_start, selection_end));
1290 void RenderWidgetHostImpl::ImeConfirmComposition(
1291 const base::string16& text,
1292 const gfx::Range& replacement_range,
1293 bool keep_selection) {
1294 Send(new InputMsg_ImeConfirmComposition(
1295 GetRoutingID(), text, replacement_range, keep_selection));
1298 void RenderWidgetHostImpl::ImeCancelComposition() {
1299 Send(new InputMsg_ImeSetComposition(GetRoutingID(), base::string16(),
1300 std::vector<blink::WebCompositionUnderline>(), 0, 0));
1303 gfx::Rect RenderWidgetHostImpl::GetRootWindowResizerRect() const {
1304 return gfx::Rect();
1307 void RenderWidgetHostImpl::RequestToLockMouse(bool user_gesture,
1308 bool last_unlocked_by_target) {
1309 // Directly reject to lock the mouse. Subclass can override this method to
1310 // decide whether to allow mouse lock or not.
1311 GotResponseToLockMouseRequest(false);
1314 void RenderWidgetHostImpl::RejectMouseLockOrUnlockIfNecessary() {
1315 DCHECK(!pending_mouse_lock_request_ || !IsMouseLocked());
1316 if (pending_mouse_lock_request_) {
1317 pending_mouse_lock_request_ = false;
1318 Send(new ViewMsg_LockMouse_ACK(routing_id_, false));
1319 } else if (IsMouseLocked()) {
1320 view_->UnlockMouse();
1324 bool RenderWidgetHostImpl::IsMouseLocked() const {
1325 return view_ ? view_->IsMouseLocked() : false;
1328 bool RenderWidgetHostImpl::IsFullscreenGranted() const {
1329 return false;
1332 blink::WebDisplayMode RenderWidgetHostImpl::GetDisplayMode() const {
1333 return blink::WebDisplayModeBrowser;
1336 void RenderWidgetHostImpl::SetAutoResize(bool enable,
1337 const gfx::Size& min_size,
1338 const gfx::Size& max_size) {
1339 auto_resize_enabled_ = enable;
1340 min_size_for_auto_resize_ = min_size;
1341 max_size_for_auto_resize_ = max_size;
1344 void RenderWidgetHostImpl::Destroy() {
1345 NotificationService::current()->Notify(
1346 NOTIFICATION_RENDER_WIDGET_HOST_DESTROYED,
1347 Source<RenderWidgetHost>(this),
1348 NotificationService::NoDetails());
1350 // Tell the view to die.
1351 // Note that in the process of the view shutting down, it can call a ton
1352 // of other messages on us. So if you do any other deinitialization here,
1353 // do it after this call to view_->Destroy().
1354 if (view_) {
1355 view_->Destroy();
1356 view_ = nullptr;
1359 delete this;
1362 void RenderWidgetHostImpl::RendererIsUnresponsive() {
1363 NotificationService::current()->Notify(
1364 NOTIFICATION_RENDER_WIDGET_HOST_HANG,
1365 Source<RenderWidgetHost>(this),
1366 NotificationService::NoDetails());
1367 is_unresponsive_ = true;
1368 NotifyRendererUnresponsive();
1371 void RenderWidgetHostImpl::RendererIsResponsive() {
1372 if (is_unresponsive_) {
1373 is_unresponsive_ = false;
1374 NotifyRendererResponsive();
1378 void RenderWidgetHostImpl::OnRenderViewReady() {
1379 SendScreenRects();
1380 WasResized();
1383 void RenderWidgetHostImpl::OnRenderProcessGone(int status, int exit_code) {
1384 // RenderFrameHost owns a RenderWidgetHost when it needs one, in which case
1385 // it handles destruction.
1386 if (!owned_by_render_frame_host_) {
1387 // TODO(evanm): This synchronously ends up calling "delete this".
1388 // Is that really what we want in response to this message? I'm matching
1389 // previous behavior of the code here.
1390 Destroy();
1391 } else {
1392 RendererExited(static_cast<base::TerminationStatus>(status), exit_code);
1396 void RenderWidgetHostImpl::OnClose() {
1397 Shutdown();
1400 void RenderWidgetHostImpl::OnSetTooltipText(
1401 const base::string16& tooltip_text,
1402 WebTextDirection text_direction_hint) {
1403 // First, add directionality marks around tooltip text if necessary.
1404 // A naive solution would be to simply always wrap the text. However, on
1405 // windows, Unicode directional embedding characters can't be displayed on
1406 // systems that lack RTL fonts and are instead displayed as empty squares.
1408 // To get around this we only wrap the string when we deem it necessary i.e.
1409 // when the locale direction is different than the tooltip direction hint.
1411 // Currently, we use element's directionality as the tooltip direction hint.
1412 // An alternate solution would be to set the overall directionality based on
1413 // trying to detect the directionality from the tooltip text rather than the
1414 // element direction. One could argue that would be a preferable solution
1415 // but we use the current approach to match Fx & IE's behavior.
1416 base::string16 wrapped_tooltip_text = tooltip_text;
1417 if (!tooltip_text.empty()) {
1418 if (text_direction_hint == blink::WebTextDirectionLeftToRight) {
1419 // Force the tooltip to have LTR directionality.
1420 wrapped_tooltip_text =
1421 base::i18n::GetDisplayStringInLTRDirectionality(wrapped_tooltip_text);
1422 } else if (text_direction_hint == blink::WebTextDirectionRightToLeft &&
1423 !base::i18n::IsRTL()) {
1424 // Force the tooltip to have RTL directionality.
1425 base::i18n::WrapStringWithRTLFormatting(&wrapped_tooltip_text);
1428 if (GetView())
1429 view_->SetTooltipText(wrapped_tooltip_text);
1432 void RenderWidgetHostImpl::OnUpdateScreenRectsAck() {
1433 waiting_for_screen_rects_ack_ = false;
1434 if (!view_)
1435 return;
1437 if (view_->GetViewBounds() == last_view_screen_rect_ &&
1438 view_->GetBoundsInRootWindow() == last_window_screen_rect_) {
1439 return;
1442 SendScreenRects();
1445 void RenderWidgetHostImpl::OnRequestMove(const gfx::Rect& pos) {
1446 if (view_) {
1447 view_->SetBounds(pos);
1448 Send(new ViewMsg_Move_ACK(routing_id_));
1452 bool RenderWidgetHostImpl::OnSwapCompositorFrame(
1453 const IPC::Message& message) {
1454 // This trace event is used in
1455 // chrome/browser/extensions/api/cast_streaming/performance_test.cc
1456 TRACE_EVENT0("test_fps,benchmark", "OnSwapCompositorFrame");
1457 ViewHostMsg_SwapCompositorFrame::Param param;
1458 if (!ViewHostMsg_SwapCompositorFrame::Read(&message, &param))
1459 return false;
1460 scoped_ptr<cc::CompositorFrame> frame(new cc::CompositorFrame);
1461 uint32 output_surface_id = get<0>(param);
1462 get<1>(param).AssignTo(frame.get());
1463 std::vector<IPC::Message> messages_to_deliver_with_frame;
1464 messages_to_deliver_with_frame.swap(get<2>(param));
1466 latency_tracker_.OnSwapCompositorFrame(&frame->metadata.latency_info);
1468 input_router_->OnViewUpdated(
1469 GetInputRouterViewFlagsFromCompositorFrameMetadata(frame->metadata));
1471 if (touch_emulator_) {
1472 touch_emulator_->SetDoubleTapSupportForPageEnabled(
1473 !IsMobileOptimizedFrame(frame->metadata));
1476 if (view_) {
1477 view_->OnSwapCompositorFrame(output_surface_id, frame.Pass());
1478 view_->DidReceiveRendererFrame();
1479 } else {
1480 cc::CompositorFrameAck ack;
1481 if (frame->gl_frame_data) {
1482 ack.gl_frame_data = frame->gl_frame_data.Pass();
1483 ack.gl_frame_data->sync_point = 0;
1484 } else if (frame->delegated_frame_data) {
1485 cc::TransferableResource::ReturnResources(
1486 frame->delegated_frame_data->resource_list,
1487 &ack.resources);
1488 } else if (frame->software_frame_data) {
1489 ack.last_software_frame_id = frame->software_frame_data->id;
1491 SendSwapCompositorFrameAck(routing_id_, output_surface_id,
1492 process_->GetID(), ack);
1495 RenderProcessHost* rph = GetProcess();
1496 for (std::vector<IPC::Message>::const_iterator i =
1497 messages_to_deliver_with_frame.begin();
1498 i != messages_to_deliver_with_frame.end();
1499 ++i) {
1500 rph->OnMessageReceived(*i);
1501 if (i->dispatch_error())
1502 rph->OnBadMessageReceived(*i);
1504 messages_to_deliver_with_frame.clear();
1506 return true;
1509 void RenderWidgetHostImpl::OnUpdateRect(
1510 const ViewHostMsg_UpdateRect_Params& params) {
1511 TRACE_EVENT0("renderer_host", "RenderWidgetHostImpl::OnUpdateRect");
1512 TimeTicks paint_start = TimeTicks::Now();
1514 // Update our knowledge of the RenderWidget's size.
1515 current_size_ = params.view_size;
1517 bool is_resize_ack =
1518 ViewHostMsg_UpdateRect_Flags::is_resize_ack(params.flags);
1520 // resize_ack_pending_ needs to be cleared before we call DidPaintRect, since
1521 // that will end up reaching GetBackingStore.
1522 if (is_resize_ack) {
1523 DCHECK(!g_check_for_pending_resize_ack || resize_ack_pending_);
1524 resize_ack_pending_ = false;
1527 bool is_repaint_ack =
1528 ViewHostMsg_UpdateRect_Flags::is_repaint_ack(params.flags);
1529 if (is_repaint_ack) {
1530 DCHECK(repaint_ack_pending_);
1531 TRACE_EVENT_ASYNC_END0(
1532 "renderer_host", "RenderWidgetHostImpl::repaint_ack_pending_", this);
1533 repaint_ack_pending_ = false;
1534 TimeDelta delta = TimeTicks::Now() - repaint_start_time_;
1535 UMA_HISTOGRAM_TIMES("MPArch.RWH_RepaintDelta", delta);
1538 DCHECK(!params.view_size.IsEmpty());
1540 DidUpdateBackingStore(params, paint_start);
1542 if (auto_resize_enabled_) {
1543 bool post_callback = new_auto_size_.IsEmpty();
1544 new_auto_size_ = params.view_size;
1545 if (post_callback) {
1546 base::MessageLoop::current()->PostTask(
1547 FROM_HERE,
1548 base::Bind(&RenderWidgetHostImpl::DelayedAutoResized,
1549 weak_factory_.GetWeakPtr()));
1553 // Log the time delta for processing a paint message. On platforms that don't
1554 // support asynchronous painting, this is equivalent to
1555 // MPArch.RWH_TotalPaintTime.
1556 TimeDelta delta = TimeTicks::Now() - paint_start;
1557 UMA_HISTOGRAM_TIMES("MPArch.RWH_OnMsgUpdateRect", delta);
1560 void RenderWidgetHostImpl::DidUpdateBackingStore(
1561 const ViewHostMsg_UpdateRect_Params& params,
1562 const TimeTicks& paint_start) {
1563 TRACE_EVENT0("renderer_host", "RenderWidgetHostImpl::DidUpdateBackingStore");
1564 TimeTicks update_start = TimeTicks::Now();
1566 // Move the plugins if the view hasn't already been destroyed. Plugin moves
1567 // will not be re-issued, so must move them now, regardless of whether we
1568 // paint or not. MovePluginWindows attempts to move the plugin windows and
1569 // in the process could dispatch other window messages which could cause the
1570 // view to be destroyed.
1571 if (view_)
1572 view_->MovePluginWindows(params.plugin_window_moves);
1574 NotificationService::current()->Notify(
1575 NOTIFICATION_RENDER_WIDGET_HOST_DID_UPDATE_BACKING_STORE,
1576 Source<RenderWidgetHost>(this),
1577 NotificationService::NoDetails());
1579 // We don't need to update the view if the view is hidden. We must do this
1580 // early return after the ACK is sent, however, or the renderer will not send
1581 // us more data.
1582 if (is_hidden_)
1583 return;
1585 // If we got a resize ack, then perhaps we have another resize to send?
1586 bool is_resize_ack =
1587 ViewHostMsg_UpdateRect_Flags::is_resize_ack(params.flags);
1588 if (is_resize_ack)
1589 WasResized();
1591 // Log the time delta for processing a paint message.
1592 TimeTicks now = TimeTicks::Now();
1593 TimeDelta delta = now - update_start;
1594 UMA_HISTOGRAM_TIMES("MPArch.RWH_DidUpdateBackingStore", delta);
1597 void RenderWidgetHostImpl::OnQueueSyntheticGesture(
1598 const SyntheticGesturePacket& gesture_packet) {
1599 // Only allow untrustworthy gestures if explicitly enabled.
1600 if (!base::CommandLine::ForCurrentProcess()->HasSwitch(
1601 cc::switches::kEnableGpuBenchmarking)) {
1602 bad_message::ReceivedBadMessage(GetProcess(),
1603 bad_message::RWH_SYNTHETIC_GESTURE);
1604 return;
1607 QueueSyntheticGesture(
1608 SyntheticGesture::Create(*gesture_packet.gesture_params()),
1609 base::Bind(&RenderWidgetHostImpl::OnSyntheticGestureCompleted,
1610 weak_factory_.GetWeakPtr()));
1613 void RenderWidgetHostImpl::OnFocus() {
1614 // Only RenderViewHost can deal with that message.
1615 bad_message::ReceivedBadMessage(GetProcess(), bad_message::RWH_FOCUS);
1618 void RenderWidgetHostImpl::OnBlur() {
1619 // Only RenderViewHost can deal with that message.
1620 bad_message::ReceivedBadMessage(GetProcess(), bad_message::RWH_BLUR);
1623 void RenderWidgetHostImpl::OnSetCursor(const WebCursor& cursor) {
1624 SetCursor(cursor);
1627 void RenderWidgetHostImpl::SetTouchEventEmulationEnabled(
1628 bool enabled, ui::GestureProviderConfigType config_type) {
1629 if (enabled) {
1630 if (!touch_emulator_)
1631 touch_emulator_.reset(new TouchEmulator(this));
1632 touch_emulator_->Enable(config_type);
1633 } else {
1634 if (touch_emulator_)
1635 touch_emulator_->Disable();
1639 void RenderWidgetHostImpl::OnTextInputTypeChanged(
1640 ui::TextInputType type,
1641 ui::TextInputMode input_mode,
1642 bool can_compose_inline,
1643 int flags) {
1644 if (view_)
1645 view_->TextInputTypeChanged(type, input_mode, can_compose_inline, flags);
1648 void RenderWidgetHostImpl::OnImeCompositionRangeChanged(
1649 const gfx::Range& range,
1650 const std::vector<gfx::Rect>& character_bounds) {
1651 if (view_)
1652 view_->ImeCompositionRangeChanged(range, character_bounds);
1655 void RenderWidgetHostImpl::OnImeCancelComposition() {
1656 if (view_)
1657 view_->ImeCancelComposition();
1660 void RenderWidgetHostImpl::OnLockMouse(bool user_gesture,
1661 bool last_unlocked_by_target,
1662 bool privileged) {
1664 if (pending_mouse_lock_request_) {
1665 Send(new ViewMsg_LockMouse_ACK(routing_id_, false));
1666 return;
1667 } else if (IsMouseLocked()) {
1668 Send(new ViewMsg_LockMouse_ACK(routing_id_, true));
1669 return;
1672 pending_mouse_lock_request_ = true;
1673 if (privileged && allow_privileged_mouse_lock_) {
1674 // Directly approve to lock the mouse.
1675 GotResponseToLockMouseRequest(true);
1676 } else {
1677 RequestToLockMouse(user_gesture, last_unlocked_by_target);
1681 void RenderWidgetHostImpl::OnUnlockMouse() {
1682 RejectMouseLockOrUnlockIfNecessary();
1685 void RenderWidgetHostImpl::OnShowDisambiguationPopup(
1686 const gfx::Rect& rect_pixels,
1687 const gfx::Size& size,
1688 const cc::SharedBitmapId& id) {
1689 DCHECK(!rect_pixels.IsEmpty());
1690 DCHECK(!size.IsEmpty());
1692 scoped_ptr<cc::SharedBitmap> bitmap =
1693 HostSharedBitmapManager::current()->GetSharedBitmapFromId(size, id);
1694 if (!bitmap) {
1695 bad_message::ReceivedBadMessage(GetProcess(),
1696 bad_message::RWH_SHARED_BITMAP);
1697 return;
1700 DCHECK(bitmap->pixels());
1702 SkImageInfo info = SkImageInfo::MakeN32Premul(size.width(), size.height());
1703 SkBitmap zoomed_bitmap;
1704 zoomed_bitmap.installPixels(info, bitmap->pixels(), info.minRowBytes());
1706 // Note that |rect| is in coordinates of pixels relative to the window origin.
1707 // Aura-based systems will want to convert this to DIPs.
1708 if (view_)
1709 view_->ShowDisambiguationPopup(rect_pixels, zoomed_bitmap);
1711 // It is assumed that the disambiguation popup will make a copy of the
1712 // provided zoomed image, so we delete this one.
1713 zoomed_bitmap.setPixels(0);
1714 Send(new ViewMsg_ReleaseDisambiguationPopupBitmap(GetRoutingID(), id));
1717 #if defined(OS_WIN)
1718 void RenderWidgetHostImpl::OnWindowlessPluginDummyWindowCreated(
1719 gfx::NativeViewId dummy_activation_window) {
1720 HWND hwnd = reinterpret_cast<HWND>(dummy_activation_window);
1722 // This may happen as a result of a race condition when the plugin is going
1723 // away.
1724 wchar_t window_title[MAX_PATH + 1] = {0};
1725 if (!IsWindow(hwnd) ||
1726 !GetWindowText(hwnd, window_title, arraysize(window_title)) ||
1727 lstrcmpiW(window_title, kDummyActivationWindowName) != 0) {
1728 return;
1731 #if defined(USE_AURA)
1732 SetParent(hwnd,
1733 reinterpret_cast<HWND>(view_->GetParentForWindowlessPlugin()));
1734 #else
1735 SetParent(hwnd, reinterpret_cast<HWND>(GetNativeViewId()));
1736 #endif
1737 dummy_windows_for_activation_.push_back(hwnd);
1740 void RenderWidgetHostImpl::OnWindowlessPluginDummyWindowDestroyed(
1741 gfx::NativeViewId dummy_activation_window) {
1742 HWND hwnd = reinterpret_cast<HWND>(dummy_activation_window);
1743 std::list<HWND>::iterator i = dummy_windows_for_activation_.begin();
1744 for (; i != dummy_windows_for_activation_.end(); ++i) {
1745 if ((*i) == hwnd) {
1746 dummy_windows_for_activation_.erase(i);
1747 return;
1750 NOTREACHED() << "Unknown dummy window";
1752 #endif
1754 void RenderWidgetHostImpl::SetIgnoreInputEvents(bool ignore_input_events) {
1755 ignore_input_events_ = ignore_input_events;
1758 bool RenderWidgetHostImpl::KeyPressListenersHandleEvent(
1759 const NativeWebKeyboardEvent& event) {
1760 if (event.skip_in_browser || event.type != WebKeyboardEvent::RawKeyDown)
1761 return false;
1763 for (size_t i = 0; i < key_press_event_callbacks_.size(); i++) {
1764 size_t original_size = key_press_event_callbacks_.size();
1765 if (key_press_event_callbacks_[i].Run(event))
1766 return true;
1768 // Check whether the callback that just ran removed itself, in which case
1769 // the iterator needs to be decremented to properly account for the removal.
1770 size_t current_size = key_press_event_callbacks_.size();
1771 if (current_size != original_size) {
1772 DCHECK_EQ(original_size - 1, current_size);
1773 --i;
1777 return false;
1780 InputEventAckState RenderWidgetHostImpl::FilterInputEvent(
1781 const blink::WebInputEvent& event, const ui::LatencyInfo& latency_info) {
1782 // Don't ignore touch cancel events, since they may be sent while input
1783 // events are being ignored in order to keep the renderer from getting
1784 // confused about how many touches are active.
1785 if (IgnoreInputEvents() && event.type != WebInputEvent::TouchCancel)
1786 return INPUT_EVENT_ACK_STATE_NO_CONSUMER_EXISTS;
1788 if (!process_->HasConnection())
1789 return INPUT_EVENT_ACK_STATE_UNKNOWN;
1791 if (event.type == WebInputEvent::MouseDown ||
1792 event.type == WebInputEvent::GestureTapDown) {
1793 OnUserGesture();
1796 return view_ ? view_->FilterInputEvent(event)
1797 : INPUT_EVENT_ACK_STATE_NOT_CONSUMED;
1800 void RenderWidgetHostImpl::IncrementInFlightEventCount() {
1801 increment_in_flight_event_count();
1802 if (!is_hidden_)
1803 StartHangMonitorTimeout(hung_renderer_delay_);
1806 void RenderWidgetHostImpl::DecrementInFlightEventCount() {
1807 if (decrement_in_flight_event_count() <= 0) {
1808 // Cancel pending hung renderer checks since the renderer is responsive.
1809 StopHangMonitorTimeout();
1810 } else {
1811 // The renderer is responsive, but there are in-flight events to wait for.
1812 if (!is_hidden_)
1813 RestartHangMonitorTimeout();
1817 void RenderWidgetHostImpl::OnHasTouchEventHandlers(bool has_handlers) {
1818 has_touch_handler_ = has_handlers;
1821 void RenderWidgetHostImpl::DidFlush() {
1822 if (synthetic_gesture_controller_)
1823 synthetic_gesture_controller_->OnDidFlushInput();
1826 void RenderWidgetHostImpl::DidOverscroll(const DidOverscrollParams& params) {
1827 if (view_)
1828 view_->DidOverscroll(params);
1831 void RenderWidgetHostImpl::DidStopFlinging() {
1832 if (view_)
1833 view_->DidStopFlinging();
1836 void RenderWidgetHostImpl::OnKeyboardEventAck(
1837 const NativeWebKeyboardEvent& event,
1838 InputEventAckState ack_result) {
1839 #if defined(OS_MACOSX)
1840 if (!is_hidden() && view_ && view_->PostProcessEventForPluginIme(event))
1841 return;
1842 #endif
1844 // We only send unprocessed key event upwards if we are not hidden,
1845 // because the user has moved away from us and no longer expect any effect
1846 // of this key event.
1847 const bool processed = (INPUT_EVENT_ACK_STATE_CONSUMED == ack_result);
1848 if (delegate_ && !processed && !is_hidden() && !event.skip_in_browser) {
1849 delegate_->HandleKeyboardEvent(event);
1851 // WARNING: This RenderWidgetHostImpl can be deallocated at this point
1852 // (i.e. in the case of Ctrl+W, where the call to
1853 // HandleKeyboardEvent destroys this RenderWidgetHostImpl).
1857 void RenderWidgetHostImpl::OnWheelEventAck(
1858 const MouseWheelEventWithLatencyInfo& wheel_event,
1859 InputEventAckState ack_result) {
1860 latency_tracker_.OnInputEventAck(wheel_event.event, &wheel_event.latency);
1862 if (!is_hidden() && view_) {
1863 if (ack_result != INPUT_EVENT_ACK_STATE_CONSUMED &&
1864 delegate_->HandleWheelEvent(wheel_event.event)) {
1865 ack_result = INPUT_EVENT_ACK_STATE_CONSUMED;
1867 view_->WheelEventAck(wheel_event.event, ack_result);
1871 void RenderWidgetHostImpl::OnGestureEventAck(
1872 const GestureEventWithLatencyInfo& event,
1873 InputEventAckState ack_result) {
1874 latency_tracker_.OnInputEventAck(event.event, &event.latency);
1876 if (view_)
1877 view_->GestureEventAck(event.event, ack_result);
1880 void RenderWidgetHostImpl::OnTouchEventAck(
1881 const TouchEventWithLatencyInfo& event,
1882 InputEventAckState ack_result) {
1883 latency_tracker_.OnInputEventAck(event.event, &event.latency);
1885 if (touch_emulator_ &&
1886 touch_emulator_->HandleTouchEventAck(event.event, ack_result)) {
1887 return;
1890 if (view_)
1891 view_->ProcessAckedTouchEvent(event, ack_result);
1894 void RenderWidgetHostImpl::OnUnexpectedEventAck(UnexpectedEventAckType type) {
1895 if (type == BAD_ACK_MESSAGE) {
1896 bad_message::ReceivedBadMessage(process_, bad_message::RWH_BAD_ACK_MESSAGE);
1897 } else if (type == UNEXPECTED_EVENT_TYPE) {
1898 suppress_next_char_events_ = false;
1902 void RenderWidgetHostImpl::OnSyntheticGestureCompleted(
1903 SyntheticGesture::Result result) {
1904 Send(new InputMsg_SyntheticGestureCompleted(GetRoutingID()));
1907 bool RenderWidgetHostImpl::IgnoreInputEvents() const {
1908 return ignore_input_events_ || process_->IgnoreInputEvents();
1911 void RenderWidgetHostImpl::StartUserGesture() {
1912 OnUserGesture();
1915 void RenderWidgetHostImpl::SetBackgroundOpaque(bool opaque) {
1916 Send(new ViewMsg_SetBackgroundOpaque(GetRoutingID(), opaque));
1919 void RenderWidgetHostImpl::SetEditCommandsForNextKeyEvent(
1920 const std::vector<EditCommand>& commands) {
1921 Send(new InputMsg_SetEditCommandsForNextKeyEvent(GetRoutingID(), commands));
1924 void RenderWidgetHostImpl::ExecuteEditCommand(const std::string& command,
1925 const std::string& value) {
1926 Send(new InputMsg_ExecuteEditCommand(GetRoutingID(), command, value));
1929 void RenderWidgetHostImpl::ScrollFocusedEditableNodeIntoRect(
1930 const gfx::Rect& rect) {
1931 Send(new InputMsg_ScrollFocusedEditableNodeIntoRect(GetRoutingID(), rect));
1934 void RenderWidgetHostImpl::MoveCaret(const gfx::Point& point) {
1935 Send(new InputMsg_MoveCaret(GetRoutingID(), point));
1938 bool RenderWidgetHostImpl::GotResponseToLockMouseRequest(bool allowed) {
1939 if (!allowed) {
1940 RejectMouseLockOrUnlockIfNecessary();
1941 return false;
1942 } else {
1943 if (!pending_mouse_lock_request_) {
1944 // This is possible, e.g., the plugin sends us an unlock request before
1945 // the user allows to lock to mouse.
1946 return false;
1949 pending_mouse_lock_request_ = false;
1950 if (!view_ || !view_->HasFocus()|| !view_->LockMouse()) {
1951 Send(new ViewMsg_LockMouse_ACK(routing_id_, false));
1952 return false;
1953 } else {
1954 Send(new ViewMsg_LockMouse_ACK(routing_id_, true));
1955 return true;
1960 // static
1961 void RenderWidgetHostImpl::SendSwapCompositorFrameAck(
1962 int32 route_id,
1963 uint32 output_surface_id,
1964 int renderer_host_id,
1965 const cc::CompositorFrameAck& ack) {
1966 RenderProcessHost* host = RenderProcessHost::FromID(renderer_host_id);
1967 if (!host)
1968 return;
1969 host->Send(new ViewMsg_SwapCompositorFrameAck(
1970 route_id, output_surface_id, ack));
1973 // static
1974 void RenderWidgetHostImpl::SendReclaimCompositorResources(
1975 int32 route_id,
1976 uint32 output_surface_id,
1977 int renderer_host_id,
1978 const cc::CompositorFrameAck& ack) {
1979 RenderProcessHost* host = RenderProcessHost::FromID(renderer_host_id);
1980 if (!host)
1981 return;
1982 host->Send(
1983 new ViewMsg_ReclaimCompositorResources(route_id, output_surface_id, ack));
1986 void RenderWidgetHostImpl::DelayedAutoResized() {
1987 gfx::Size new_size = new_auto_size_;
1988 // Clear the new_auto_size_ since the empty value is used as a flag to
1989 // indicate that no callback is in progress (i.e. without this line
1990 // DelayedAutoResized will not get called again).
1991 new_auto_size_.SetSize(0, 0);
1992 if (!auto_resize_enabled_)
1993 return;
1995 OnRenderAutoResized(new_size);
1998 void RenderWidgetHostImpl::DetachDelegate() {
1999 delegate_ = NULL;
2002 void RenderWidgetHostImpl::FrameSwapped(const ui::LatencyInfo& latency_info) {
2003 ui::LatencyInfo::LatencyComponent window_snapshot_component;
2004 if (latency_info.FindLatency(ui::WINDOW_SNAPSHOT_FRAME_NUMBER_COMPONENT,
2005 GetLatencyComponentId(),
2006 &window_snapshot_component)) {
2007 int sequence_number = static_cast<int>(
2008 window_snapshot_component.sequence_number);
2009 #if defined(OS_MACOSX)
2010 // On Mac, when using CoreAnmation, there is a delay between when content
2011 // is drawn to the screen, and when the snapshot will actually pick up
2012 // that content. Insert a manual delay of 1/6th of a second (to simulate
2013 // 10 frames at 60 fps) before actually taking the snapshot.
2014 base::MessageLoop::current()->PostDelayedTask(
2015 FROM_HERE,
2016 base::Bind(&RenderWidgetHostImpl::WindowSnapshotReachedScreen,
2017 weak_factory_.GetWeakPtr(),
2018 sequence_number),
2019 base::TimeDelta::FromSecondsD(1. / 6));
2020 #else
2021 WindowSnapshotReachedScreen(sequence_number);
2022 #endif
2025 latency_tracker_.OnFrameSwapped(latency_info);
2028 void RenderWidgetHostImpl::DidReceiveRendererFrame() {
2029 view_->DidReceiveRendererFrame();
2032 void RenderWidgetHostImpl::WindowSnapshotReachedScreen(int snapshot_id) {
2033 DCHECK(base::MessageLoopForUI::IsCurrent());
2035 gfx::Rect view_bounds = GetView()->GetViewBounds();
2036 gfx::Rect snapshot_bounds(view_bounds.size());
2038 std::vector<unsigned char> png;
2039 if (ui::GrabViewSnapshot(
2040 GetView()->GetNativeView(), &png, snapshot_bounds)) {
2041 OnSnapshotDataReceived(snapshot_id, &png.front(), png.size());
2042 return;
2045 ui::GrabViewSnapshotAsync(
2046 GetView()->GetNativeView(),
2047 snapshot_bounds,
2048 base::ThreadTaskRunnerHandle::Get(),
2049 base::Bind(&RenderWidgetHostImpl::OnSnapshotDataReceivedAsync,
2050 weak_factory_.GetWeakPtr(),
2051 snapshot_id));
2054 void RenderWidgetHostImpl::OnSnapshotDataReceived(int snapshot_id,
2055 const unsigned char* data,
2056 size_t size) {
2057 // Any pending snapshots with a lower ID than the one received are considered
2058 // to be implicitly complete, and returned the same snapshot data.
2059 PendingSnapshotMap::iterator it = pending_browser_snapshots_.begin();
2060 while(it != pending_browser_snapshots_.end()) {
2061 if (it->first <= snapshot_id) {
2062 it->second.Run(data, size);
2063 pending_browser_snapshots_.erase(it++);
2064 } else {
2065 ++it;
2070 void RenderWidgetHostImpl::OnSnapshotDataReceivedAsync(
2071 int snapshot_id,
2072 scoped_refptr<base::RefCountedBytes> png_data) {
2073 if (png_data.get())
2074 OnSnapshotDataReceived(snapshot_id, png_data->front(), png_data->size());
2075 else
2076 OnSnapshotDataReceived(snapshot_id, NULL, 0);
2079 // static
2080 void RenderWidgetHostImpl::CompositorFrameDrawn(
2081 const std::vector<ui::LatencyInfo>& latency_info) {
2082 for (size_t i = 0; i < latency_info.size(); i++) {
2083 std::set<RenderWidgetHostImpl*> rwhi_set;
2084 for (ui::LatencyInfo::LatencyMap::const_iterator b =
2085 latency_info[i].latency_components.begin();
2086 b != latency_info[i].latency_components.end();
2087 ++b) {
2088 if (b->first.first == ui::INPUT_EVENT_LATENCY_BEGIN_RWH_COMPONENT ||
2089 b->first.first == ui::WINDOW_SNAPSHOT_FRAME_NUMBER_COMPONENT ||
2090 b->first.first == ui::TAB_SHOW_COMPONENT) {
2091 // Matches with GetLatencyComponentId
2092 int routing_id = b->first.second & 0xffffffff;
2093 int process_id = (b->first.second >> 32) & 0xffffffff;
2094 RenderWidgetHost* rwh =
2095 RenderWidgetHost::FromID(process_id, routing_id);
2096 if (!rwh) {
2097 continue;
2099 RenderWidgetHostImpl* rwhi = RenderWidgetHostImpl::From(rwh);
2100 if (rwhi_set.insert(rwhi).second)
2101 rwhi->FrameSwapped(latency_info[i]);
2107 BrowserAccessibilityManager*
2108 RenderWidgetHostImpl::GetRootBrowserAccessibilityManager() {
2109 return delegate_ ? delegate_->GetRootBrowserAccessibilityManager() : NULL;
2112 BrowserAccessibilityManager*
2113 RenderWidgetHostImpl::GetOrCreateRootBrowserAccessibilityManager() {
2114 return delegate_ ?
2115 delegate_->GetOrCreateRootBrowserAccessibilityManager() : NULL;
2118 base::TimeDelta RenderWidgetHostImpl::GetEstimatedBrowserCompositeTime() const {
2119 return latency_tracker_.GetEstimatedBrowserCompositeTime();
2122 #if defined(OS_WIN)
2123 gfx::NativeViewAccessible
2124 RenderWidgetHostImpl::GetParentNativeViewAccessible() {
2125 return delegate_ ? delegate_->GetParentNativeViewAccessible() : NULL;
2127 #endif
2129 } // namespace content