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