Process Alt-Svc headers.
[chromium-blink-merge.git] / content / browser / renderer_host / render_widget_host_impl.cc
blob004ea6f29d4c7a4083f38d47fdc718bd07253a53
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_EVENT0("input", "RenderWidgetHostImpl::ForwardWheelEvent");
927 if (IgnoreInputEvents())
928 return;
930 if (touch_emulator_ && touch_emulator_->HandleMouseWheelEvent(wheel_event))
931 return;
933 MouseWheelEventWithLatencyInfo wheel_with_latency(wheel_event, ui_latency);
934 latency_tracker_.OnInputEvent(wheel_event, &wheel_with_latency.latency);
935 input_router_->SendWheelEvent(wheel_with_latency);
938 void RenderWidgetHostImpl::ForwardGestureEvent(
939 const blink::WebGestureEvent& gesture_event) {
940 ForwardGestureEventWithLatencyInfo(gesture_event, ui::LatencyInfo());
943 void RenderWidgetHostImpl::ForwardGestureEventWithLatencyInfo(
944 const blink::WebGestureEvent& gesture_event,
945 const ui::LatencyInfo& ui_latency) {
946 TRACE_EVENT0("input", "RenderWidgetHostImpl::ForwardGestureEvent");
947 // Early out if necessary, prior to performing latency logic.
948 if (IgnoreInputEvents())
949 return;
951 if (delegate_->PreHandleGestureEvent(gesture_event))
952 return;
954 GestureEventWithLatencyInfo gesture_with_latency(gesture_event, ui_latency);
955 latency_tracker_.OnInputEvent(gesture_event, &gesture_with_latency.latency);
956 input_router_->SendGestureEvent(gesture_with_latency);
959 void RenderWidgetHostImpl::ForwardEmulatedTouchEvent(
960 const blink::WebTouchEvent& touch_event) {
961 TRACE_EVENT0("input", "RenderWidgetHostImpl::ForwardEmulatedTouchEvent");
963 TouchEventWithLatencyInfo touch_with_latency(touch_event);
964 latency_tracker_.OnInputEvent(touch_event, &touch_with_latency.latency);
965 input_router_->SendTouchEvent(touch_with_latency);
968 void RenderWidgetHostImpl::ForwardTouchEventWithLatencyInfo(
969 const blink::WebTouchEvent& touch_event,
970 const ui::LatencyInfo& ui_latency) {
971 TRACE_EVENT0("input", "RenderWidgetHostImpl::ForwardTouchEvent");
973 // Always forward TouchEvents for touch stream consistency. They will be
974 // ignored if appropriate in FilterInputEvent().
976 TouchEventWithLatencyInfo touch_with_latency(touch_event, ui_latency);
977 if (touch_emulator_ &&
978 touch_emulator_->HandleTouchEvent(touch_with_latency.event)) {
979 if (view_) {
980 view_->ProcessAckedTouchEvent(
981 touch_with_latency, INPUT_EVENT_ACK_STATE_CONSUMED);
983 return;
986 latency_tracker_.OnInputEvent(touch_event, &touch_with_latency.latency);
987 input_router_->SendTouchEvent(touch_with_latency);
990 void RenderWidgetHostImpl::ForwardKeyboardEvent(
991 const NativeWebKeyboardEvent& key_event) {
992 TRACE_EVENT0("input", "RenderWidgetHostImpl::ForwardKeyboardEvent");
993 if (IgnoreInputEvents())
994 return;
996 if (!process_->HasConnection())
997 return;
999 // First, let keypress listeners take a shot at handling the event. If a
1000 // listener handles the event, it should not be propagated to the renderer.
1001 if (KeyPressListenersHandleEvent(key_event)) {
1002 // Some keypresses that are accepted by the listener might have follow up
1003 // char events, which should be ignored.
1004 if (key_event.type == WebKeyboardEvent::RawKeyDown)
1005 suppress_next_char_events_ = true;
1006 return;
1009 if (key_event.type == WebKeyboardEvent::Char &&
1010 (key_event.windowsKeyCode == ui::VKEY_RETURN ||
1011 key_event.windowsKeyCode == ui::VKEY_SPACE)) {
1012 OnUserGesture();
1015 // Double check the type to make sure caller hasn't sent us nonsense that
1016 // will mess up our key queue.
1017 if (!WebInputEvent::isKeyboardEventType(key_event.type))
1018 return;
1020 if (suppress_next_char_events_) {
1021 // If preceding RawKeyDown event was handled by the browser, then we need
1022 // suppress all Char events generated by it. Please note that, one
1023 // RawKeyDown event may generate multiple Char events, so we can't reset
1024 // |suppress_next_char_events_| until we get a KeyUp or a RawKeyDown.
1025 if (key_event.type == WebKeyboardEvent::Char)
1026 return;
1027 // We get a KeyUp or a RawKeyDown event.
1028 suppress_next_char_events_ = false;
1031 bool is_shortcut = false;
1033 // Only pre-handle the key event if it's not handled by the input method.
1034 if (delegate_ && !key_event.skip_in_browser) {
1035 // We need to set |suppress_next_char_events_| to true if
1036 // PreHandleKeyboardEvent() returns true, but |this| may already be
1037 // destroyed at that time. So set |suppress_next_char_events_| true here,
1038 // then revert it afterwards when necessary.
1039 if (key_event.type == WebKeyboardEvent::RawKeyDown)
1040 suppress_next_char_events_ = true;
1042 // Tab switching/closing accelerators aren't sent to the renderer to avoid
1043 // a hung/malicious renderer from interfering.
1044 if (delegate_->PreHandleKeyboardEvent(key_event, &is_shortcut))
1045 return;
1047 if (key_event.type == WebKeyboardEvent::RawKeyDown)
1048 suppress_next_char_events_ = false;
1051 if (touch_emulator_ && touch_emulator_->HandleKeyboardEvent(key_event))
1052 return;
1054 ui::LatencyInfo latency;
1055 latency_tracker_.OnInputEvent(key_event, &latency);
1056 input_router_->SendKeyboardEvent(key_event, latency, is_shortcut);
1059 void RenderWidgetHostImpl::QueueSyntheticGesture(
1060 scoped_ptr<SyntheticGesture> synthetic_gesture,
1061 const base::Callback<void(SyntheticGesture::Result)>& on_complete) {
1062 if (!synthetic_gesture_controller_ && view_) {
1063 synthetic_gesture_controller_.reset(
1064 new SyntheticGestureController(
1065 view_->CreateSyntheticGestureTarget().Pass()));
1067 if (synthetic_gesture_controller_) {
1068 synthetic_gesture_controller_->QueueSyntheticGesture(
1069 synthetic_gesture.Pass(), on_complete);
1073 void RenderWidgetHostImpl::SetCursor(const WebCursor& cursor) {
1074 if (!view_)
1075 return;
1076 view_->UpdateCursor(cursor);
1079 void RenderWidgetHostImpl::ShowContextMenuAtPoint(const gfx::Point& point) {
1080 Send(new ViewMsg_ShowContextMenu(
1081 GetRoutingID(), ui::MENU_SOURCE_MOUSE, point));
1084 void RenderWidgetHostImpl::SendCursorVisibilityState(bool is_visible) {
1085 Send(new InputMsg_CursorVisibilityChange(GetRoutingID(), is_visible));
1088 int64 RenderWidgetHostImpl::GetLatencyComponentId() const {
1089 return latency_tracker_.latency_component_id();
1092 // static
1093 void RenderWidgetHostImpl::DisableResizeAckCheckForTesting() {
1094 g_check_for_pending_resize_ack = false;
1097 void RenderWidgetHostImpl::AddKeyPressEventCallback(
1098 const KeyPressEventCallback& callback) {
1099 key_press_event_callbacks_.push_back(callback);
1102 void RenderWidgetHostImpl::RemoveKeyPressEventCallback(
1103 const KeyPressEventCallback& callback) {
1104 for (size_t i = 0; i < key_press_event_callbacks_.size(); ++i) {
1105 if (key_press_event_callbacks_[i].Equals(callback)) {
1106 key_press_event_callbacks_.erase(
1107 key_press_event_callbacks_.begin() + i);
1108 return;
1113 void RenderWidgetHostImpl::AddMouseEventCallback(
1114 const MouseEventCallback& callback) {
1115 mouse_event_callbacks_.push_back(callback);
1118 void RenderWidgetHostImpl::RemoveMouseEventCallback(
1119 const MouseEventCallback& callback) {
1120 for (size_t i = 0; i < mouse_event_callbacks_.size(); ++i) {
1121 if (mouse_event_callbacks_[i].Equals(callback)) {
1122 mouse_event_callbacks_.erase(mouse_event_callbacks_.begin() + i);
1123 return;
1128 void RenderWidgetHostImpl::GetWebScreenInfo(blink::WebScreenInfo* result) {
1129 TRACE_EVENT0("renderer_host", "RenderWidgetHostImpl::GetWebScreenInfo");
1130 if (view_)
1131 view_->GetScreenInfo(result);
1132 else
1133 RenderWidgetHostViewBase::GetDefaultScreenInfo(result);
1134 // TODO(sievers): find a way to make this done another way so the method
1135 // can be const.
1136 latency_tracker_.set_device_scale_factor(result->deviceScaleFactor);
1139 const NativeWebKeyboardEvent*
1140 RenderWidgetHostImpl::GetLastKeyboardEvent() const {
1141 return input_router_->GetLastKeyboardEvent();
1144 void RenderWidgetHostImpl::NotifyScreenInfoChanged() {
1145 if (delegate_)
1146 delegate_->ScreenInfoChanged();
1148 // The resize message (which may not happen immediately) will carry with it
1149 // the screen info as well as the new size (if the screen has changed scale
1150 // factor).
1151 WasResized();
1154 void RenderWidgetHostImpl::GetSnapshotFromBrowser(
1155 const base::Callback<void(const unsigned char*,size_t)> callback) {
1156 int id = next_browser_snapshot_id_++;
1157 pending_browser_snapshots_.insert(std::make_pair(id, callback));
1158 Send(new ViewMsg_ForceRedraw(GetRoutingID(), id));
1161 void RenderWidgetHostImpl::OnSelectionChanged(const base::string16& text,
1162 size_t offset,
1163 const gfx::Range& range) {
1164 if (view_)
1165 view_->SelectionChanged(text, offset, range);
1168 void RenderWidgetHostImpl::OnSelectionBoundsChanged(
1169 const ViewHostMsg_SelectionBounds_Params& params) {
1170 if (view_) {
1171 view_->SelectionBoundsChanged(params);
1175 void RenderWidgetHostImpl::UpdateVSyncParameters(base::TimeTicks timebase,
1176 base::TimeDelta interval) {
1177 Send(new ViewMsg_UpdateVSyncParameters(GetRoutingID(), timebase, interval));
1180 void RenderWidgetHostImpl::RendererExited(base::TerminationStatus status,
1181 int exit_code) {
1182 if (!renderer_initialized_)
1183 return;
1185 // Clearing this flag causes us to re-create the renderer when recovering
1186 // from a crashed renderer.
1187 renderer_initialized_ = false;
1189 waiting_for_screen_rects_ack_ = false;
1191 // Must reset these to ensure that keyboard events work with a new renderer.
1192 suppress_next_char_events_ = false;
1194 // Reset some fields in preparation for recovering from a crash.
1195 ResetSizeAndRepaintPendingFlags();
1196 current_size_.SetSize(0, 0);
1197 // After the renderer crashes, the view is destroyed and so the
1198 // RenderWidgetHost cannot track its visibility anymore. We assume such
1199 // RenderWidgetHost to be visible for the sake of internal accounting - be
1200 // careful about changing this - see http://crbug.com/401859.
1202 // We need to at least make sure that the RenderProcessHost is notified about
1203 // the |is_hidden_| change, so that the renderer will have correct visibility
1204 // set when respawned.
1205 if (is_hidden_) {
1206 process_->WidgetRestored();
1207 is_hidden_ = false;
1210 // Reset this to ensure the hung renderer mechanism is working properly.
1211 in_flight_event_count_ = 0;
1212 StopHangMonitorTimeout();
1214 if (view_) {
1215 GpuSurfaceTracker::Get()->SetSurfaceHandle(surface_id_,
1216 gfx::GLSurfaceHandle());
1217 view_->RenderProcessGone(status, exit_code);
1218 view_ = NULL; // The View should be deleted by RenderProcessGone.
1219 view_weak_.reset();
1222 // Reconstruct the input router to ensure that it has fresh state for a new
1223 // renderer. Otherwise it may be stuck waiting for the old renderer to ack an
1224 // event. (In particular, the above call to view_->RenderProcessGone will
1225 // destroy the aura window, which may dispatch a synthetic mouse move.)
1226 input_router_.reset(new InputRouterImpl(
1227 process_, this, this, routing_id_, GetInputRouterConfigForPlatform()));
1229 synthetic_gesture_controller_.reset();
1232 void RenderWidgetHostImpl::UpdateTextDirection(WebTextDirection direction) {
1233 text_direction_updated_ = true;
1234 text_direction_ = direction;
1237 void RenderWidgetHostImpl::CancelUpdateTextDirection() {
1238 if (text_direction_updated_)
1239 text_direction_canceled_ = true;
1242 void RenderWidgetHostImpl::NotifyTextDirection() {
1243 if (text_direction_updated_) {
1244 if (!text_direction_canceled_)
1245 Send(new ViewMsg_SetTextDirection(GetRoutingID(), text_direction_));
1246 text_direction_updated_ = false;
1247 text_direction_canceled_ = false;
1251 void RenderWidgetHostImpl::ImeSetComposition(
1252 const base::string16& text,
1253 const std::vector<blink::WebCompositionUnderline>& underlines,
1254 int selection_start,
1255 int selection_end) {
1256 Send(new InputMsg_ImeSetComposition(
1257 GetRoutingID(), text, underlines, selection_start, selection_end));
1260 void RenderWidgetHostImpl::ImeConfirmComposition(
1261 const base::string16& text,
1262 const gfx::Range& replacement_range,
1263 bool keep_selection) {
1264 Send(new InputMsg_ImeConfirmComposition(
1265 GetRoutingID(), text, replacement_range, keep_selection));
1268 void RenderWidgetHostImpl::ImeCancelComposition() {
1269 Send(new InputMsg_ImeSetComposition(GetRoutingID(), base::string16(),
1270 std::vector<blink::WebCompositionUnderline>(), 0, 0));
1273 gfx::Rect RenderWidgetHostImpl::GetRootWindowResizerRect() const {
1274 return gfx::Rect();
1277 void RenderWidgetHostImpl::RequestToLockMouse(bool user_gesture,
1278 bool last_unlocked_by_target) {
1279 // Directly reject to lock the mouse. Subclass can override this method to
1280 // decide whether to allow mouse lock or not.
1281 GotResponseToLockMouseRequest(false);
1284 void RenderWidgetHostImpl::RejectMouseLockOrUnlockIfNecessary() {
1285 DCHECK(!pending_mouse_lock_request_ || !IsMouseLocked());
1286 if (pending_mouse_lock_request_) {
1287 pending_mouse_lock_request_ = false;
1288 Send(new ViewMsg_LockMouse_ACK(routing_id_, false));
1289 } else if (IsMouseLocked()) {
1290 view_->UnlockMouse();
1294 bool RenderWidgetHostImpl::IsMouseLocked() const {
1295 return view_ ? view_->IsMouseLocked() : false;
1298 bool RenderWidgetHostImpl::IsFullscreenGranted() const {
1299 return false;
1302 blink::WebDisplayMode RenderWidgetHostImpl::GetDisplayMode() const {
1303 return blink::WebDisplayModeBrowser;
1306 void RenderWidgetHostImpl::SetAutoResize(bool enable,
1307 const gfx::Size& min_size,
1308 const gfx::Size& max_size) {
1309 auto_resize_enabled_ = enable;
1310 min_size_for_auto_resize_ = min_size;
1311 max_size_for_auto_resize_ = max_size;
1314 void RenderWidgetHostImpl::Destroy() {
1315 NotificationService::current()->Notify(
1316 NOTIFICATION_RENDER_WIDGET_HOST_DESTROYED,
1317 Source<RenderWidgetHost>(this),
1318 NotificationService::NoDetails());
1320 // Tell the view to die.
1321 // Note that in the process of the view shutting down, it can call a ton
1322 // of other messages on us. So if you do any other deinitialization here,
1323 // do it after this call to view_->Destroy().
1324 if (view_) {
1325 view_->Destroy();
1326 view_ = nullptr;
1329 delete this;
1332 void RenderWidgetHostImpl::RendererIsUnresponsive() {
1333 NotificationService::current()->Notify(
1334 NOTIFICATION_RENDER_WIDGET_HOST_HANG,
1335 Source<RenderWidgetHost>(this),
1336 NotificationService::NoDetails());
1337 is_unresponsive_ = true;
1338 NotifyRendererUnresponsive();
1341 void RenderWidgetHostImpl::RendererIsResponsive() {
1342 if (is_unresponsive_) {
1343 is_unresponsive_ = false;
1344 NotifyRendererResponsive();
1348 void RenderWidgetHostImpl::OnRenderViewReady() {
1349 SendScreenRects();
1350 WasResized();
1353 void RenderWidgetHostImpl::OnRenderProcessGone(int status, int exit_code) {
1354 // RenderFrameHost owns a RenderWidgetHost when it needs one, in which case
1355 // it handles destruction.
1356 if (!owned_by_render_frame_host_) {
1357 // TODO(evanm): This synchronously ends up calling "delete this".
1358 // Is that really what we want in response to this message? I'm matching
1359 // previous behavior of the code here.
1360 Destroy();
1361 } else {
1362 RendererExited(static_cast<base::TerminationStatus>(status), exit_code);
1366 void RenderWidgetHostImpl::OnClose() {
1367 Shutdown();
1370 void RenderWidgetHostImpl::OnSetTooltipText(
1371 const base::string16& tooltip_text,
1372 WebTextDirection text_direction_hint) {
1373 // First, add directionality marks around tooltip text if necessary.
1374 // A naive solution would be to simply always wrap the text. However, on
1375 // windows, Unicode directional embedding characters can't be displayed on
1376 // systems that lack RTL fonts and are instead displayed as empty squares.
1378 // To get around this we only wrap the string when we deem it necessary i.e.
1379 // when the locale direction is different than the tooltip direction hint.
1381 // Currently, we use element's directionality as the tooltip direction hint.
1382 // An alternate solution would be to set the overall directionality based on
1383 // trying to detect the directionality from the tooltip text rather than the
1384 // element direction. One could argue that would be a preferable solution
1385 // but we use the current approach to match Fx & IE's behavior.
1386 base::string16 wrapped_tooltip_text = tooltip_text;
1387 if (!tooltip_text.empty()) {
1388 if (text_direction_hint == blink::WebTextDirectionLeftToRight) {
1389 // Force the tooltip to have LTR directionality.
1390 wrapped_tooltip_text =
1391 base::i18n::GetDisplayStringInLTRDirectionality(wrapped_tooltip_text);
1392 } else if (text_direction_hint == blink::WebTextDirectionRightToLeft &&
1393 !base::i18n::IsRTL()) {
1394 // Force the tooltip to have RTL directionality.
1395 base::i18n::WrapStringWithRTLFormatting(&wrapped_tooltip_text);
1398 if (GetView())
1399 view_->SetTooltipText(wrapped_tooltip_text);
1402 void RenderWidgetHostImpl::OnUpdateScreenRectsAck() {
1403 waiting_for_screen_rects_ack_ = false;
1404 if (!view_)
1405 return;
1407 if (view_->GetViewBounds() == last_view_screen_rect_ &&
1408 view_->GetBoundsInRootWindow() == last_window_screen_rect_) {
1409 return;
1412 SendScreenRects();
1415 void RenderWidgetHostImpl::OnRequestMove(const gfx::Rect& pos) {
1416 if (view_) {
1417 view_->SetBounds(pos);
1418 Send(new ViewMsg_Move_ACK(routing_id_));
1422 bool RenderWidgetHostImpl::OnSwapCompositorFrame(
1423 const IPC::Message& message) {
1424 // This trace event is used in
1425 // chrome/browser/extensions/api/cast_streaming/performance_test.cc
1426 TRACE_EVENT0("test_fps,benchmark", "OnSwapCompositorFrame");
1427 ViewHostMsg_SwapCompositorFrame::Param param;
1428 if (!ViewHostMsg_SwapCompositorFrame::Read(&message, &param))
1429 return false;
1430 scoped_ptr<cc::CompositorFrame> frame(new cc::CompositorFrame);
1431 uint32 output_surface_id = base::get<0>(param);
1432 base::get<1>(param).AssignTo(frame.get());
1433 std::vector<IPC::Message> messages_to_deliver_with_frame;
1434 messages_to_deliver_with_frame.swap(base::get<2>(param));
1436 latency_tracker_.OnSwapCompositorFrame(&frame->metadata.latency_info);
1438 bool is_mobile_optimized = IsMobileOptimizedFrame(frame->metadata);
1439 input_router_->NotifySiteIsMobileOptimized(is_mobile_optimized);
1440 if (touch_emulator_)
1441 touch_emulator_->SetDoubleTapSupportForPageEnabled(!is_mobile_optimized);
1443 if (view_) {
1444 view_->OnSwapCompositorFrame(output_surface_id, frame.Pass());
1445 view_->DidReceiveRendererFrame();
1446 } else {
1447 cc::CompositorFrameAck ack;
1448 if (frame->gl_frame_data) {
1449 ack.gl_frame_data = frame->gl_frame_data.Pass();
1450 ack.gl_frame_data->sync_point = 0;
1451 } else if (frame->delegated_frame_data) {
1452 cc::TransferableResource::ReturnResources(
1453 frame->delegated_frame_data->resource_list,
1454 &ack.resources);
1455 } else if (frame->software_frame_data) {
1456 ack.last_software_frame_id = frame->software_frame_data->id;
1458 SendSwapCompositorFrameAck(routing_id_, output_surface_id,
1459 process_->GetID(), ack);
1462 RenderProcessHost* rph = GetProcess();
1463 for (std::vector<IPC::Message>::const_iterator i =
1464 messages_to_deliver_with_frame.begin();
1465 i != messages_to_deliver_with_frame.end();
1466 ++i) {
1467 rph->OnMessageReceived(*i);
1468 if (i->dispatch_error())
1469 rph->OnBadMessageReceived(*i);
1471 messages_to_deliver_with_frame.clear();
1473 return true;
1476 void RenderWidgetHostImpl::OnUpdateRect(
1477 const ViewHostMsg_UpdateRect_Params& params) {
1478 TRACE_EVENT0("renderer_host", "RenderWidgetHostImpl::OnUpdateRect");
1479 TimeTicks paint_start = TimeTicks::Now();
1481 // Update our knowledge of the RenderWidget's size.
1482 current_size_ = params.view_size;
1484 bool is_resize_ack =
1485 ViewHostMsg_UpdateRect_Flags::is_resize_ack(params.flags);
1487 // resize_ack_pending_ needs to be cleared before we call DidPaintRect, since
1488 // that will end up reaching GetBackingStore.
1489 if (is_resize_ack) {
1490 DCHECK(!g_check_for_pending_resize_ack || resize_ack_pending_);
1491 resize_ack_pending_ = false;
1494 bool is_repaint_ack =
1495 ViewHostMsg_UpdateRect_Flags::is_repaint_ack(params.flags);
1496 if (is_repaint_ack) {
1497 DCHECK(repaint_ack_pending_);
1498 TRACE_EVENT_ASYNC_END0(
1499 "renderer_host", "RenderWidgetHostImpl::repaint_ack_pending_", this);
1500 repaint_ack_pending_ = false;
1501 TimeDelta delta = TimeTicks::Now() - repaint_start_time_;
1502 UMA_HISTOGRAM_TIMES("MPArch.RWH_RepaintDelta", delta);
1505 DCHECK(!params.view_size.IsEmpty());
1507 DidUpdateBackingStore(params, paint_start);
1509 if (auto_resize_enabled_) {
1510 bool post_callback = new_auto_size_.IsEmpty();
1511 new_auto_size_ = params.view_size;
1512 if (post_callback) {
1513 base::ThreadTaskRunnerHandle::Get()->PostTask(
1514 FROM_HERE, base::Bind(&RenderWidgetHostImpl::DelayedAutoResized,
1515 weak_factory_.GetWeakPtr()));
1519 // Log the time delta for processing a paint message. On platforms that don't
1520 // support asynchronous painting, this is equivalent to
1521 // MPArch.RWH_TotalPaintTime.
1522 TimeDelta delta = TimeTicks::Now() - paint_start;
1523 UMA_HISTOGRAM_TIMES("MPArch.RWH_OnMsgUpdateRect", delta);
1526 void RenderWidgetHostImpl::DidUpdateBackingStore(
1527 const ViewHostMsg_UpdateRect_Params& params,
1528 const TimeTicks& paint_start) {
1529 TRACE_EVENT0("renderer_host", "RenderWidgetHostImpl::DidUpdateBackingStore");
1530 TimeTicks update_start = TimeTicks::Now();
1532 // Move the plugins if the view hasn't already been destroyed. Plugin moves
1533 // will not be re-issued, so must move them now, regardless of whether we
1534 // paint or not. MovePluginWindows attempts to move the plugin windows and
1535 // in the process could dispatch other window messages which could cause the
1536 // view to be destroyed.
1537 if (view_)
1538 view_->MovePluginWindows(params.plugin_window_moves);
1540 NotificationService::current()->Notify(
1541 NOTIFICATION_RENDER_WIDGET_HOST_DID_UPDATE_BACKING_STORE,
1542 Source<RenderWidgetHost>(this),
1543 NotificationService::NoDetails());
1545 // We don't need to update the view if the view is hidden. We must do this
1546 // early return after the ACK is sent, however, or the renderer will not send
1547 // us more data.
1548 if (is_hidden_)
1549 return;
1551 // If we got a resize ack, then perhaps we have another resize to send?
1552 bool is_resize_ack =
1553 ViewHostMsg_UpdateRect_Flags::is_resize_ack(params.flags);
1554 if (is_resize_ack)
1555 WasResized();
1557 // Log the time delta for processing a paint message.
1558 TimeTicks now = TimeTicks::Now();
1559 TimeDelta delta = now - update_start;
1560 UMA_HISTOGRAM_TIMES("MPArch.RWH_DidUpdateBackingStore", delta);
1563 void RenderWidgetHostImpl::OnQueueSyntheticGesture(
1564 const SyntheticGesturePacket& gesture_packet) {
1565 // Only allow untrustworthy gestures if explicitly enabled.
1566 if (!base::CommandLine::ForCurrentProcess()->HasSwitch(
1567 cc::switches::kEnableGpuBenchmarking)) {
1568 bad_message::ReceivedBadMessage(GetProcess(),
1569 bad_message::RWH_SYNTHETIC_GESTURE);
1570 return;
1573 QueueSyntheticGesture(
1574 SyntheticGesture::Create(*gesture_packet.gesture_params()),
1575 base::Bind(&RenderWidgetHostImpl::OnSyntheticGestureCompleted,
1576 weak_factory_.GetWeakPtr()));
1579 void RenderWidgetHostImpl::OnFocus() {
1580 // Only RenderViewHost can deal with that message.
1581 bad_message::ReceivedBadMessage(GetProcess(), bad_message::RWH_FOCUS);
1584 void RenderWidgetHostImpl::OnBlur() {
1585 // Only RenderViewHost can deal with that message.
1586 bad_message::ReceivedBadMessage(GetProcess(), bad_message::RWH_BLUR);
1589 void RenderWidgetHostImpl::OnSetCursor(const WebCursor& cursor) {
1590 SetCursor(cursor);
1593 void RenderWidgetHostImpl::SetTouchEventEmulationEnabled(
1594 bool enabled, ui::GestureProviderConfigType config_type) {
1595 if (enabled) {
1596 if (!touch_emulator_) {
1597 touch_emulator_.reset(new TouchEmulator(
1598 this, view_ ? content::GetScaleFactorForView(view_) : 1.0f));
1600 touch_emulator_->Enable(config_type);
1601 } else {
1602 if (touch_emulator_)
1603 touch_emulator_->Disable();
1607 void RenderWidgetHostImpl::OnTextInputStateChanged(
1608 const ViewHostMsg_TextInputState_Params& params) {
1609 if (view_)
1610 view_->TextInputStateChanged(params);
1613 void RenderWidgetHostImpl::OnImeCompositionRangeChanged(
1614 const gfx::Range& range,
1615 const std::vector<gfx::Rect>& character_bounds) {
1616 if (view_)
1617 view_->ImeCompositionRangeChanged(range, character_bounds);
1620 void RenderWidgetHostImpl::OnImeCancelComposition() {
1621 if (view_)
1622 view_->ImeCancelComposition();
1625 void RenderWidgetHostImpl::OnLockMouse(bool user_gesture,
1626 bool last_unlocked_by_target,
1627 bool privileged) {
1629 if (pending_mouse_lock_request_) {
1630 Send(new ViewMsg_LockMouse_ACK(routing_id_, false));
1631 return;
1632 } else if (IsMouseLocked()) {
1633 Send(new ViewMsg_LockMouse_ACK(routing_id_, true));
1634 return;
1637 pending_mouse_lock_request_ = true;
1638 if (privileged && allow_privileged_mouse_lock_) {
1639 // Directly approve to lock the mouse.
1640 GotResponseToLockMouseRequest(true);
1641 } else {
1642 RequestToLockMouse(user_gesture, last_unlocked_by_target);
1646 void RenderWidgetHostImpl::OnUnlockMouse() {
1647 RejectMouseLockOrUnlockIfNecessary();
1650 void RenderWidgetHostImpl::OnShowDisambiguationPopup(
1651 const gfx::Rect& rect_pixels,
1652 const gfx::Size& size,
1653 const cc::SharedBitmapId& id) {
1654 DCHECK(!rect_pixels.IsEmpty());
1655 DCHECK(!size.IsEmpty());
1657 scoped_ptr<cc::SharedBitmap> bitmap =
1658 HostSharedBitmapManager::current()->GetSharedBitmapFromId(size, id);
1659 if (!bitmap) {
1660 bad_message::ReceivedBadMessage(GetProcess(),
1661 bad_message::RWH_SHARED_BITMAP);
1662 return;
1665 DCHECK(bitmap->pixels());
1667 SkImageInfo info = SkImageInfo::MakeN32Premul(size.width(), size.height());
1668 SkBitmap zoomed_bitmap;
1669 zoomed_bitmap.installPixels(info, bitmap->pixels(), info.minRowBytes());
1671 // Note that |rect| is in coordinates of pixels relative to the window origin.
1672 // Aura-based systems will want to convert this to DIPs.
1673 if (view_)
1674 view_->ShowDisambiguationPopup(rect_pixels, zoomed_bitmap);
1676 // It is assumed that the disambiguation popup will make a copy of the
1677 // provided zoomed image, so we delete this one.
1678 zoomed_bitmap.setPixels(0);
1679 Send(new ViewMsg_ReleaseDisambiguationPopupBitmap(GetRoutingID(), id));
1682 #if defined(OS_WIN)
1683 void RenderWidgetHostImpl::OnWindowlessPluginDummyWindowCreated(
1684 gfx::NativeViewId dummy_activation_window) {
1685 HWND hwnd = reinterpret_cast<HWND>(dummy_activation_window);
1687 // This may happen as a result of a race condition when the plugin is going
1688 // away.
1689 wchar_t window_title[MAX_PATH + 1] = {0};
1690 if (!IsWindow(hwnd) ||
1691 !GetWindowText(hwnd, window_title, arraysize(window_title)) ||
1692 lstrcmpiW(window_title, kDummyActivationWindowName) != 0) {
1693 return;
1696 #if defined(USE_AURA)
1697 SetParent(hwnd,
1698 reinterpret_cast<HWND>(view_->GetParentForWindowlessPlugin()));
1699 #else
1700 SetParent(hwnd, reinterpret_cast<HWND>(GetNativeViewId()));
1701 #endif
1702 dummy_windows_for_activation_.push_back(hwnd);
1705 void RenderWidgetHostImpl::OnWindowlessPluginDummyWindowDestroyed(
1706 gfx::NativeViewId dummy_activation_window) {
1707 HWND hwnd = reinterpret_cast<HWND>(dummy_activation_window);
1708 std::list<HWND>::iterator i = dummy_windows_for_activation_.begin();
1709 for (; i != dummy_windows_for_activation_.end(); ++i) {
1710 if ((*i) == hwnd) {
1711 dummy_windows_for_activation_.erase(i);
1712 return;
1715 NOTREACHED() << "Unknown dummy window";
1717 #endif
1719 void RenderWidgetHostImpl::SetIgnoreInputEvents(bool ignore_input_events) {
1720 ignore_input_events_ = ignore_input_events;
1723 bool RenderWidgetHostImpl::KeyPressListenersHandleEvent(
1724 const NativeWebKeyboardEvent& event) {
1725 if (event.skip_in_browser || event.type != WebKeyboardEvent::RawKeyDown)
1726 return false;
1728 for (size_t i = 0; i < key_press_event_callbacks_.size(); i++) {
1729 size_t original_size = key_press_event_callbacks_.size();
1730 if (key_press_event_callbacks_[i].Run(event))
1731 return true;
1733 // Check whether the callback that just ran removed itself, in which case
1734 // the iterator needs to be decremented to properly account for the removal.
1735 size_t current_size = key_press_event_callbacks_.size();
1736 if (current_size != original_size) {
1737 DCHECK_EQ(original_size - 1, current_size);
1738 --i;
1742 return false;
1745 InputEventAckState RenderWidgetHostImpl::FilterInputEvent(
1746 const blink::WebInputEvent& event, const ui::LatencyInfo& latency_info) {
1747 // Don't ignore touch cancel events, since they may be sent while input
1748 // events are being ignored in order to keep the renderer from getting
1749 // confused about how many touches are active.
1750 if (IgnoreInputEvents() && event.type != WebInputEvent::TouchCancel)
1751 return INPUT_EVENT_ACK_STATE_NO_CONSUMER_EXISTS;
1753 if (!process_->HasConnection())
1754 return INPUT_EVENT_ACK_STATE_UNKNOWN;
1756 if (event.type == WebInputEvent::MouseDown ||
1757 event.type == WebInputEvent::GestureTapDown) {
1758 OnUserGesture();
1761 return view_ ? view_->FilterInputEvent(event)
1762 : INPUT_EVENT_ACK_STATE_NOT_CONSUMED;
1765 void RenderWidgetHostImpl::IncrementInFlightEventCount() {
1766 increment_in_flight_event_count();
1767 if (!is_hidden_)
1768 StartHangMonitorTimeout(hung_renderer_delay_);
1771 void RenderWidgetHostImpl::DecrementInFlightEventCount() {
1772 if (decrement_in_flight_event_count() <= 0) {
1773 // Cancel pending hung renderer checks since the renderer is responsive.
1774 StopHangMonitorTimeout();
1775 } else {
1776 // The renderer is responsive, but there are in-flight events to wait for.
1777 if (!is_hidden_)
1778 RestartHangMonitorTimeout();
1782 void RenderWidgetHostImpl::OnHasTouchEventHandlers(bool has_handlers) {
1783 has_touch_handler_ = has_handlers;
1786 void RenderWidgetHostImpl::DidFlush() {
1787 if (synthetic_gesture_controller_)
1788 synthetic_gesture_controller_->OnDidFlushInput();
1791 void RenderWidgetHostImpl::DidOverscroll(const DidOverscrollParams& params) {
1792 if (view_)
1793 view_->DidOverscroll(params);
1796 void RenderWidgetHostImpl::DidStopFlinging() {
1797 if (view_)
1798 view_->DidStopFlinging();
1801 void RenderWidgetHostImpl::OnKeyboardEventAck(
1802 const NativeWebKeyboardEvent& event,
1803 InputEventAckState ack_result) {
1804 #if defined(OS_MACOSX)
1805 if (!is_hidden() && view_ && view_->PostProcessEventForPluginIme(event))
1806 return;
1807 #endif
1809 // We only send unprocessed key event upwards if we are not hidden,
1810 // because the user has moved away from us and no longer expect any effect
1811 // of this key event.
1812 const bool processed = (INPUT_EVENT_ACK_STATE_CONSUMED == ack_result);
1813 if (delegate_ && !processed && !is_hidden() && !event.skip_in_browser) {
1814 delegate_->HandleKeyboardEvent(event);
1816 // WARNING: This RenderWidgetHostImpl can be deallocated at this point
1817 // (i.e. in the case of Ctrl+W, where the call to
1818 // HandleKeyboardEvent destroys this RenderWidgetHostImpl).
1822 void RenderWidgetHostImpl::OnWheelEventAck(
1823 const MouseWheelEventWithLatencyInfo& wheel_event,
1824 InputEventAckState ack_result) {
1825 latency_tracker_.OnInputEventAck(wheel_event.event, &wheel_event.latency);
1827 if (!is_hidden() && view_) {
1828 if (ack_result != INPUT_EVENT_ACK_STATE_CONSUMED &&
1829 delegate_->HandleWheelEvent(wheel_event.event)) {
1830 ack_result = INPUT_EVENT_ACK_STATE_CONSUMED;
1832 view_->WheelEventAck(wheel_event.event, ack_result);
1836 void RenderWidgetHostImpl::OnGestureEventAck(
1837 const GestureEventWithLatencyInfo& event,
1838 InputEventAckState ack_result) {
1839 latency_tracker_.OnInputEventAck(event.event, &event.latency);
1841 if (view_)
1842 view_->GestureEventAck(event.event, ack_result);
1845 void RenderWidgetHostImpl::OnTouchEventAck(
1846 const TouchEventWithLatencyInfo& event,
1847 InputEventAckState ack_result) {
1848 latency_tracker_.OnInputEventAck(event.event, &event.latency);
1850 if (touch_emulator_ &&
1851 touch_emulator_->HandleTouchEventAck(event.event, ack_result)) {
1852 return;
1855 if (view_)
1856 view_->ProcessAckedTouchEvent(event, ack_result);
1859 void RenderWidgetHostImpl::OnUnexpectedEventAck(UnexpectedEventAckType type) {
1860 if (type == BAD_ACK_MESSAGE) {
1861 bad_message::ReceivedBadMessage(process_, bad_message::RWH_BAD_ACK_MESSAGE);
1862 } else if (type == UNEXPECTED_EVENT_TYPE) {
1863 suppress_next_char_events_ = false;
1867 void RenderWidgetHostImpl::OnSyntheticGestureCompleted(
1868 SyntheticGesture::Result result) {
1869 Send(new InputMsg_SyntheticGestureCompleted(GetRoutingID()));
1872 bool RenderWidgetHostImpl::IgnoreInputEvents() const {
1873 return ignore_input_events_ || process_->IgnoreInputEvents();
1876 void RenderWidgetHostImpl::StartUserGesture() {
1877 OnUserGesture();
1880 void RenderWidgetHostImpl::SetBackgroundOpaque(bool opaque) {
1881 Send(new ViewMsg_SetBackgroundOpaque(GetRoutingID(), opaque));
1884 void RenderWidgetHostImpl::SetEditCommandsForNextKeyEvent(
1885 const std::vector<EditCommand>& commands) {
1886 Send(new InputMsg_SetEditCommandsForNextKeyEvent(GetRoutingID(), commands));
1889 void RenderWidgetHostImpl::ExecuteEditCommand(const std::string& command,
1890 const std::string& value) {
1891 Send(new InputMsg_ExecuteEditCommand(GetRoutingID(), command, value));
1894 void RenderWidgetHostImpl::ScrollFocusedEditableNodeIntoRect(
1895 const gfx::Rect& rect) {
1896 Send(new InputMsg_ScrollFocusedEditableNodeIntoRect(GetRoutingID(), rect));
1899 void RenderWidgetHostImpl::MoveCaret(const gfx::Point& point) {
1900 Send(new InputMsg_MoveCaret(GetRoutingID(), point));
1903 bool RenderWidgetHostImpl::GotResponseToLockMouseRequest(bool allowed) {
1904 if (!allowed) {
1905 RejectMouseLockOrUnlockIfNecessary();
1906 return false;
1907 } else {
1908 if (!pending_mouse_lock_request_) {
1909 // This is possible, e.g., the plugin sends us an unlock request before
1910 // the user allows to lock to mouse.
1911 return false;
1914 pending_mouse_lock_request_ = false;
1915 if (!view_ || !view_->HasFocus()|| !view_->LockMouse()) {
1916 Send(new ViewMsg_LockMouse_ACK(routing_id_, false));
1917 return false;
1918 } else {
1919 Send(new ViewMsg_LockMouse_ACK(routing_id_, true));
1920 return true;
1925 // static
1926 void RenderWidgetHostImpl::SendSwapCompositorFrameAck(
1927 int32 route_id,
1928 uint32 output_surface_id,
1929 int renderer_host_id,
1930 const cc::CompositorFrameAck& ack) {
1931 RenderProcessHost* host = RenderProcessHost::FromID(renderer_host_id);
1932 if (!host)
1933 return;
1934 host->Send(new ViewMsg_SwapCompositorFrameAck(
1935 route_id, output_surface_id, ack));
1938 // static
1939 void RenderWidgetHostImpl::SendReclaimCompositorResources(
1940 int32 route_id,
1941 uint32 output_surface_id,
1942 int renderer_host_id,
1943 const cc::CompositorFrameAck& ack) {
1944 RenderProcessHost* host = RenderProcessHost::FromID(renderer_host_id);
1945 if (!host)
1946 return;
1947 host->Send(
1948 new ViewMsg_ReclaimCompositorResources(route_id, output_surface_id, ack));
1951 void RenderWidgetHostImpl::DelayedAutoResized() {
1952 gfx::Size new_size = new_auto_size_;
1953 // Clear the new_auto_size_ since the empty value is used as a flag to
1954 // indicate that no callback is in progress (i.e. without this line
1955 // DelayedAutoResized will not get called again).
1956 new_auto_size_.SetSize(0, 0);
1957 if (!auto_resize_enabled_)
1958 return;
1960 OnRenderAutoResized(new_size);
1963 void RenderWidgetHostImpl::DetachDelegate() {
1964 delegate_ = NULL;
1967 void RenderWidgetHostImpl::FrameSwapped(const ui::LatencyInfo& latency_info) {
1968 ui::LatencyInfo::LatencyComponent window_snapshot_component;
1969 if (latency_info.FindLatency(ui::WINDOW_SNAPSHOT_FRAME_NUMBER_COMPONENT,
1970 GetLatencyComponentId(),
1971 &window_snapshot_component)) {
1972 int sequence_number = static_cast<int>(
1973 window_snapshot_component.sequence_number);
1974 #if defined(OS_MACOSX)
1975 // On Mac, when using CoreAnmation, there is a delay between when content
1976 // is drawn to the screen, and when the snapshot will actually pick up
1977 // that content. Insert a manual delay of 1/6th of a second (to simulate
1978 // 10 frames at 60 fps) before actually taking the snapshot.
1979 base::MessageLoop::current()->PostDelayedTask(
1980 FROM_HERE,
1981 base::Bind(&RenderWidgetHostImpl::WindowSnapshotReachedScreen,
1982 weak_factory_.GetWeakPtr(),
1983 sequence_number),
1984 base::TimeDelta::FromSecondsD(1. / 6));
1985 #else
1986 WindowSnapshotReachedScreen(sequence_number);
1987 #endif
1990 latency_tracker_.OnFrameSwapped(latency_info);
1993 void RenderWidgetHostImpl::DidReceiveRendererFrame() {
1994 view_->DidReceiveRendererFrame();
1997 void RenderWidgetHostImpl::WindowSnapshotReachedScreen(int snapshot_id) {
1998 DCHECK(base::MessageLoopForUI::IsCurrent());
2000 gfx::Rect view_bounds = GetView()->GetViewBounds();
2001 gfx::Rect snapshot_bounds(view_bounds.size());
2003 std::vector<unsigned char> png;
2004 if (ui::GrabViewSnapshot(
2005 GetView()->GetNativeView(), &png, snapshot_bounds)) {
2006 OnSnapshotDataReceived(snapshot_id, &png.front(), png.size());
2007 return;
2010 ui::GrabViewSnapshotAsync(
2011 GetView()->GetNativeView(),
2012 snapshot_bounds,
2013 base::ThreadTaskRunnerHandle::Get(),
2014 base::Bind(&RenderWidgetHostImpl::OnSnapshotDataReceivedAsync,
2015 weak_factory_.GetWeakPtr(),
2016 snapshot_id));
2019 void RenderWidgetHostImpl::OnSnapshotDataReceived(int snapshot_id,
2020 const unsigned char* data,
2021 size_t size) {
2022 // Any pending snapshots with a lower ID than the one received are considered
2023 // to be implicitly complete, and returned the same snapshot data.
2024 PendingSnapshotMap::iterator it = pending_browser_snapshots_.begin();
2025 while(it != pending_browser_snapshots_.end()) {
2026 if (it->first <= snapshot_id) {
2027 it->second.Run(data, size);
2028 pending_browser_snapshots_.erase(it++);
2029 } else {
2030 ++it;
2035 void RenderWidgetHostImpl::OnSnapshotDataReceivedAsync(
2036 int snapshot_id,
2037 scoped_refptr<base::RefCountedBytes> png_data) {
2038 if (png_data.get())
2039 OnSnapshotDataReceived(snapshot_id, png_data->front(), png_data->size());
2040 else
2041 OnSnapshotDataReceived(snapshot_id, NULL, 0);
2044 // static
2045 void RenderWidgetHostImpl::CompositorFrameDrawn(
2046 const std::vector<ui::LatencyInfo>& latency_info) {
2047 for (size_t i = 0; i < latency_info.size(); i++) {
2048 std::set<RenderWidgetHostImpl*> rwhi_set;
2049 for (ui::LatencyInfo::LatencyMap::const_iterator b =
2050 latency_info[i].latency_components.begin();
2051 b != latency_info[i].latency_components.end();
2052 ++b) {
2053 if (b->first.first == ui::INPUT_EVENT_LATENCY_BEGIN_RWH_COMPONENT ||
2054 b->first.first == ui::WINDOW_SNAPSHOT_FRAME_NUMBER_COMPONENT ||
2055 b->first.first == ui::TAB_SHOW_COMPONENT) {
2056 // Matches with GetLatencyComponentId
2057 int routing_id = b->first.second & 0xffffffff;
2058 int process_id = (b->first.second >> 32) & 0xffffffff;
2059 RenderWidgetHost* rwh =
2060 RenderWidgetHost::FromID(process_id, routing_id);
2061 if (!rwh) {
2062 continue;
2064 RenderWidgetHostImpl* rwhi = RenderWidgetHostImpl::From(rwh);
2065 if (rwhi_set.insert(rwhi).second)
2066 rwhi->FrameSwapped(latency_info[i]);
2072 BrowserAccessibilityManager*
2073 RenderWidgetHostImpl::GetRootBrowserAccessibilityManager() {
2074 return delegate_ ? delegate_->GetRootBrowserAccessibilityManager() : NULL;
2077 BrowserAccessibilityManager*
2078 RenderWidgetHostImpl::GetOrCreateRootBrowserAccessibilityManager() {
2079 return delegate_ ?
2080 delegate_->GetOrCreateRootBrowserAccessibilityManager() : NULL;
2083 #if defined(OS_WIN)
2084 gfx::NativeViewAccessible
2085 RenderWidgetHostImpl::GetParentNativeViewAccessible() {
2086 return delegate_ ? delegate_->GetParentNativeViewAccessible() : NULL;
2088 #endif
2090 } // namespace content