Permission messages: Add a bunch of missing combinations/suppressions.
[chromium-blink-merge.git] / content / browser / renderer_host / render_widget_host_impl.cc
blob91456a9d107449be3808a62875fb593fa4b58cbc
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 int32 routing_id,
145 int32 surface_id,
146 bool hidden)
147 : view_(NULL),
148 hung_renderer_delay_(
149 base::TimeDelta::FromMilliseconds(kHungRendererDelayMs)),
150 renderer_initialized_(false),
151 delegate_(delegate),
152 process_(process),
153 routing_id_(routing_id),
154 surface_id_(surface_id),
155 is_loading_(false),
156 is_hidden_(hidden),
157 repaint_ack_pending_(false),
158 resize_ack_pending_(false),
159 color_profile_out_of_date_(false),
160 auto_resize_enabled_(false),
161 waiting_for_screen_rects_ack_(false),
162 needs_repainting_on_restore_(false),
163 is_unresponsive_(false),
164 in_flight_event_count_(0),
165 in_get_backing_store_(false),
166 ignore_input_events_(false),
167 text_direction_updated_(false),
168 text_direction_(blink::WebTextDirectionLeftToRight),
169 text_direction_canceled_(false),
170 suppress_next_char_events_(false),
171 pending_mouse_lock_request_(false),
172 allow_privileged_mouse_lock_(false),
173 has_touch_handler_(false),
174 next_browser_snapshot_id_(1),
175 owned_by_render_frame_host_(false),
176 is_focused_(false),
177 weak_factory_(this) {
178 CHECK(delegate_);
179 CHECK_NE(MSG_ROUTING_NONE, routing_id_);
180 DCHECK_EQ(surface_id_, GpuSurfaceTracker::Get()->LookupSurfaceForRenderer(
181 process_->GetID(), routing_id_));
183 std::pair<RoutingIDWidgetMap::iterator, bool> result =
184 g_routing_id_widget_map.Get().insert(std::make_pair(
185 RenderWidgetHostID(process->GetID(), routing_id_), this));
186 CHECK(result.second) << "Inserting a duplicate item!";
187 process_->AddRoute(routing_id_, this);
189 // If we're initially visible, tell the process host that we're alive.
190 // Otherwise we'll notify the process host when we are first shown.
191 if (!hidden)
192 process_->WidgetRestored();
194 latency_tracker_.Initialize(routing_id_, GetProcess()->GetID());
196 input_router_.reset(new InputRouterImpl(
197 process_, this, this, routing_id_, GetInputRouterConfigForPlatform()));
199 touch_emulator_.reset();
201 RenderViewHostImpl* rvh = static_cast<RenderViewHostImpl*>(
202 IsRenderView() ? RenderViewHost::From(this) : NULL);
203 if (BrowserPluginGuest::IsGuest(rvh) ||
204 !base::CommandLine::ForCurrentProcess()->HasSwitch(
205 switches::kDisableHangMonitor)) {
206 hang_monitor_timeout_.reset(new TimeoutMonitor(
207 base::Bind(&RenderWidgetHostImpl::RendererIsUnresponsive,
208 weak_factory_.GetWeakPtr())));
212 RenderWidgetHostImpl::~RenderWidgetHostImpl() {
213 if (view_weak_)
214 view_weak_->RenderWidgetHostGone();
215 SetView(NULL);
217 GpuSurfaceTracker::Get()->RemoveSurface(surface_id_);
218 surface_id_ = 0;
220 process_->RemoveRoute(routing_id_);
221 g_routing_id_widget_map.Get().erase(
222 RenderWidgetHostID(process_->GetID(), routing_id_));
224 if (delegate_)
225 delegate_->RenderWidgetDeleted(this);
228 // static
229 RenderWidgetHost* RenderWidgetHost::FromID(
230 int32 process_id,
231 int32 routing_id) {
232 return RenderWidgetHostImpl::FromID(process_id, routing_id);
235 // static
236 RenderWidgetHostImpl* RenderWidgetHostImpl::FromID(
237 int32 process_id,
238 int32 routing_id) {
239 DCHECK_CURRENTLY_ON(BrowserThread::UI);
240 RoutingIDWidgetMap* widgets = g_routing_id_widget_map.Pointer();
241 RoutingIDWidgetMap::iterator it = widgets->find(
242 RenderWidgetHostID(process_id, routing_id));
243 return it == widgets->end() ? NULL : it->second;
246 // static
247 scoped_ptr<RenderWidgetHostIterator> RenderWidgetHost::GetRenderWidgetHosts() {
248 RenderWidgetHostIteratorImpl* hosts = new RenderWidgetHostIteratorImpl();
249 RoutingIDWidgetMap* widgets = g_routing_id_widget_map.Pointer();
250 for (RoutingIDWidgetMap::const_iterator it = widgets->begin();
251 it != widgets->end();
252 ++it) {
253 RenderWidgetHost* widget = it->second;
255 if (!widget->IsRenderView()) {
256 hosts->Add(widget);
257 continue;
260 // Add only active RenderViewHosts.
261 RenderViewHost* rvh = RenderViewHost::From(widget);
262 if (static_cast<RenderViewHostImpl*>(rvh)->is_active())
263 hosts->Add(widget);
266 return scoped_ptr<RenderWidgetHostIterator>(hosts);
269 // static
270 scoped_ptr<RenderWidgetHostIterator>
271 RenderWidgetHostImpl::GetAllRenderWidgetHosts() {
272 RenderWidgetHostIteratorImpl* hosts = new RenderWidgetHostIteratorImpl();
273 RoutingIDWidgetMap* widgets = g_routing_id_widget_map.Pointer();
274 for (RoutingIDWidgetMap::const_iterator it = widgets->begin();
275 it != widgets->end();
276 ++it) {
277 hosts->Add(it->second);
280 return scoped_ptr<RenderWidgetHostIterator>(hosts);
283 // static
284 RenderWidgetHostImpl* RenderWidgetHostImpl::From(RenderWidgetHost* rwh) {
285 return rwh->AsRenderWidgetHostImpl();
288 void RenderWidgetHostImpl::SetView(RenderWidgetHostViewBase* view) {
289 if (view)
290 view_weak_ = view->GetWeakPtr();
291 else
292 view_weak_.reset();
293 view_ = view;
295 // If the renderer has not yet been initialized, then the surface ID
296 // namespace will be sent during initialization.
297 if (view_ && renderer_initialized_) {
298 Send(new ViewMsg_SetSurfaceIdNamespace(routing_id_,
299 view_->GetSurfaceIdNamespace()));
302 GpuSurfaceTracker::Get()->SetSurfaceHandle(
303 surface_id_, GetCompositingSurface());
305 synthetic_gesture_controller_.reset();
308 RenderProcessHost* RenderWidgetHostImpl::GetProcess() const {
309 return process_;
312 int RenderWidgetHostImpl::GetRoutingID() const {
313 return routing_id_;
316 RenderWidgetHostView* RenderWidgetHostImpl::GetView() const {
317 return view_;
320 RenderWidgetHostImpl* RenderWidgetHostImpl::AsRenderWidgetHostImpl() {
321 return this;
324 gfx::NativeViewId RenderWidgetHostImpl::GetNativeViewId() const {
325 if (view_)
326 return view_->GetNativeViewId();
327 return 0;
330 gfx::GLSurfaceHandle RenderWidgetHostImpl::GetCompositingSurface() {
331 if (view_)
332 return view_->GetCompositingSurface();
333 return gfx::GLSurfaceHandle();
336 void RenderWidgetHostImpl::ResetSizeAndRepaintPendingFlags() {
337 resize_ack_pending_ = false;
338 if (repaint_ack_pending_) {
339 TRACE_EVENT_ASYNC_END0(
340 "renderer_host", "RenderWidgetHostImpl::repaint_ack_pending_", this);
342 repaint_ack_pending_ = false;
343 if (old_resize_params_)
344 old_resize_params_->new_size = gfx::Size();
347 void RenderWidgetHostImpl::SendScreenRects() {
348 if (!renderer_initialized_ || waiting_for_screen_rects_ack_)
349 return;
351 if (is_hidden_) {
352 // On GTK, this comes in for backgrounded tabs. Ignore, to match what
353 // happens on Win & Mac, and when the view is shown it'll call this again.
354 return;
357 if (!view_)
358 return;
360 last_view_screen_rect_ = view_->GetViewBounds();
361 last_window_screen_rect_ = view_->GetBoundsInRootWindow();
362 Send(new ViewMsg_UpdateScreenRects(
363 GetRoutingID(), last_view_screen_rect_, last_window_screen_rect_));
364 if (delegate_)
365 delegate_->DidSendScreenRects(this);
366 waiting_for_screen_rects_ack_ = true;
369 void RenderWidgetHostImpl::SuppressNextCharEvents() {
370 suppress_next_char_events_ = true;
373 void RenderWidgetHostImpl::FlushInput() {
374 input_router_->RequestNotificationWhenFlushed();
375 if (synthetic_gesture_controller_)
376 synthetic_gesture_controller_->Flush(base::TimeTicks::Now());
379 void RenderWidgetHostImpl::SetNeedsFlush() {
380 if (view_)
381 view_->OnSetNeedsFlushInput();
384 void RenderWidgetHostImpl::Init() {
385 DCHECK(process_->HasConnection());
387 renderer_initialized_ = true;
389 GpuSurfaceTracker::Get()->SetSurfaceHandle(
390 surface_id_, GetCompositingSurface());
392 // Send the ack along with the information on placement.
393 Send(new ViewMsg_CreatingNew_ACK(routing_id_));
394 GetProcess()->ResumeRequestsForView(routing_id_);
396 // If the RWHV has not yet been set, the surface ID namespace will get
397 // passed down by the call to SetView().
398 if (view_) {
399 Send(new ViewMsg_SetSurfaceIdNamespace(routing_id_,
400 view_->GetSurfaceIdNamespace()));
403 WasResized();
406 void RenderWidgetHostImpl::InitForFrame() {
407 DCHECK(process_->HasConnection());
408 renderer_initialized_ = true;
411 void RenderWidgetHostImpl::Shutdown() {
412 RejectMouseLockOrUnlockIfNecessary();
414 if (process_->HasConnection()) {
415 // Tell the renderer object to close.
416 bool rv = Send(new ViewMsg_Close(routing_id_));
417 DCHECK(rv);
420 Destroy();
423 bool RenderWidgetHostImpl::IsLoading() const {
424 return is_loading_;
427 bool RenderWidgetHostImpl::IsRenderView() const {
428 return false;
431 bool RenderWidgetHostImpl::OnMessageReceived(const IPC::Message &msg) {
432 bool handled = true;
433 IPC_BEGIN_MESSAGE_MAP(RenderWidgetHostImpl, msg)
434 IPC_MESSAGE_HANDLER(FrameHostMsg_RenderProcessGone, OnRenderProcessGone)
435 IPC_MESSAGE_HANDLER(InputHostMsg_QueueSyntheticGesture,
436 OnQueueSyntheticGesture)
437 IPC_MESSAGE_HANDLER(InputHostMsg_ImeCancelComposition,
438 OnImeCancelComposition)
439 IPC_MESSAGE_HANDLER(ViewHostMsg_RenderViewReady, OnRenderViewReady)
440 IPC_MESSAGE_HANDLER(ViewHostMsg_Close, OnClose)
441 IPC_MESSAGE_HANDLER(ViewHostMsg_UpdateScreenRects_ACK,
442 OnUpdateScreenRectsAck)
443 IPC_MESSAGE_HANDLER(ViewHostMsg_RequestMove, OnRequestMove)
444 IPC_MESSAGE_HANDLER(ViewHostMsg_SetTooltipText, OnSetTooltipText)
445 IPC_MESSAGE_HANDLER_GENERIC(ViewHostMsg_SwapCompositorFrame,
446 OnSwapCompositorFrame(msg))
447 IPC_MESSAGE_HANDLER(ViewHostMsg_UpdateRect, OnUpdateRect)
448 IPC_MESSAGE_HANDLER(ViewHostMsg_Focus, OnFocus)
449 IPC_MESSAGE_HANDLER(ViewHostMsg_Blur, OnBlur)
450 IPC_MESSAGE_HANDLER(ViewHostMsg_SetCursor, OnSetCursor)
451 IPC_MESSAGE_HANDLER(ViewHostMsg_TextInputStateChanged,
452 OnTextInputStateChanged)
453 IPC_MESSAGE_HANDLER(ViewHostMsg_LockMouse, OnLockMouse)
454 IPC_MESSAGE_HANDLER(ViewHostMsg_UnlockMouse, OnUnlockMouse)
455 IPC_MESSAGE_HANDLER(ViewHostMsg_ShowDisambiguationPopup,
456 OnShowDisambiguationPopup)
457 IPC_MESSAGE_HANDLER(ViewHostMsg_SelectionChanged, OnSelectionChanged)
458 IPC_MESSAGE_HANDLER(ViewHostMsg_SelectionBoundsChanged,
459 OnSelectionBoundsChanged)
460 #if defined(OS_WIN)
461 IPC_MESSAGE_HANDLER(ViewHostMsg_WindowlessPluginDummyWindowCreated,
462 OnWindowlessPluginDummyWindowCreated)
463 IPC_MESSAGE_HANDLER(ViewHostMsg_WindowlessPluginDummyWindowDestroyed,
464 OnWindowlessPluginDummyWindowDestroyed)
465 #endif
466 IPC_MESSAGE_HANDLER(InputHostMsg_ImeCompositionRangeChanged,
467 OnImeCompositionRangeChanged)
468 IPC_MESSAGE_UNHANDLED(handled = false)
469 IPC_END_MESSAGE_MAP()
471 if (!handled && input_router_ && input_router_->OnMessageReceived(msg))
472 return true;
474 if (!handled && view_ && view_->OnMessageReceived(msg))
475 return true;
477 return handled;
480 bool RenderWidgetHostImpl::Send(IPC::Message* msg) {
481 if (IPC_MESSAGE_ID_CLASS(msg->type()) == InputMsgStart)
482 return input_router_->SendInput(make_scoped_ptr(msg));
484 return process_->Send(msg);
487 void RenderWidgetHostImpl::SetIsLoading(bool is_loading) {
488 is_loading_ = is_loading;
489 if (!view_)
490 return;
491 view_->SetIsLoading(is_loading);
494 void RenderWidgetHostImpl::WasHidden() {
495 if (is_hidden_)
496 return;
498 TRACE_EVENT0("renderer_host", "RenderWidgetHostImpl::WasHidden");
499 is_hidden_ = true;
501 // Don't bother reporting hung state when we aren't active.
502 StopHangMonitorTimeout();
504 // If we have a renderer, then inform it that we are being hidden so it can
505 // reduce its resource utilization.
506 Send(new ViewMsg_WasHidden(routing_id_));
508 // Tell the RenderProcessHost we were hidden.
509 process_->WidgetHidden();
511 bool is_visible = false;
512 NotificationService::current()->Notify(
513 NOTIFICATION_RENDER_WIDGET_VISIBILITY_CHANGED,
514 Source<RenderWidgetHost>(this),
515 Details<bool>(&is_visible));
518 void RenderWidgetHostImpl::WasShown(const ui::LatencyInfo& latency_info) {
519 if (!is_hidden_)
520 return;
522 TRACE_EVENT0("renderer_host", "RenderWidgetHostImpl::WasShown");
523 is_hidden_ = false;
525 SendScreenRects();
527 // When hidden, timeout monitoring for input events is disabled. Restore it
528 // now to ensure consistent hang detection.
529 if (in_flight_event_count_)
530 RestartHangMonitorTimeout();
532 // Always repaint on restore.
533 bool needs_repainting = true;
534 needs_repainting_on_restore_ = false;
535 Send(new ViewMsg_WasShown(routing_id_, needs_repainting, latency_info));
537 process_->WidgetRestored();
539 bool is_visible = true;
540 NotificationService::current()->Notify(
541 NOTIFICATION_RENDER_WIDGET_VISIBILITY_CHANGED,
542 Source<RenderWidgetHost>(this),
543 Details<bool>(&is_visible));
545 // It's possible for our size to be out of sync with the renderer. The
546 // following is one case that leads to this:
547 // 1. WasResized -> Send ViewMsg_Resize to render
548 // 2. WasResized -> do nothing as resize_ack_pending_ is true
549 // 3. WasHidden
550 // 4. OnUpdateRect from (1) processed. Does NOT invoke WasResized as view
551 // is hidden. Now renderer/browser out of sync with what they think size
552 // is.
553 // By invoking WasResized the renderer is updated as necessary. WasResized
554 // does nothing if the sizes are already in sync.
556 // TODO: ideally ViewMsg_WasShown would take a size. This way, the renderer
557 // could handle both the restore and resize at once. This isn't that big a
558 // deal as RenderWidget::WasShown delays updating, so that the resize from
559 // WasResized is usually processed before the renderer is painted.
560 WasResized();
563 bool RenderWidgetHostImpl::GetResizeParams(
564 ViewMsg_Resize_Params* resize_params) {
565 *resize_params = ViewMsg_Resize_Params();
567 GetWebScreenInfo(&resize_params->screen_info);
568 resize_params->resizer_rect = GetRootWindowResizerRect();
570 if (view_) {
571 resize_params->new_size = view_->GetRequestedRendererSize();
572 resize_params->physical_backing_size = view_->GetPhysicalBackingSize();
573 resize_params->top_controls_height = view_->GetTopControlsHeight();
574 resize_params->top_controls_shrink_blink_size =
575 view_->DoTopControlsShrinkBlinkSize();
576 resize_params->visible_viewport_size = view_->GetVisibleViewportSize();
577 resize_params->is_fullscreen_granted = IsFullscreenGranted();
578 resize_params->display_mode = GetDisplayMode();
581 const bool size_changed =
582 !old_resize_params_ ||
583 old_resize_params_->new_size != resize_params->new_size ||
584 (old_resize_params_->physical_backing_size.IsEmpty() &&
585 !resize_params->physical_backing_size.IsEmpty());
586 bool dirty = size_changed ||
587 old_resize_params_->screen_info != resize_params->screen_info ||
588 old_resize_params_->physical_backing_size !=
589 resize_params->physical_backing_size ||
590 old_resize_params_->is_fullscreen_granted !=
591 resize_params->is_fullscreen_granted ||
592 old_resize_params_->display_mode != resize_params->display_mode ||
593 old_resize_params_->top_controls_height !=
594 resize_params->top_controls_height ||
595 old_resize_params_->top_controls_shrink_blink_size !=
596 resize_params->top_controls_shrink_blink_size ||
597 old_resize_params_->visible_viewport_size !=
598 resize_params->visible_viewport_size;
600 // We don't expect to receive an ACK when the requested size or the physical
601 // backing size is empty, or when the main viewport size didn't change.
602 resize_params->needs_resize_ack =
603 g_check_for_pending_resize_ack && !resize_params->new_size.IsEmpty() &&
604 !resize_params->physical_backing_size.IsEmpty() && size_changed;
606 return dirty;
609 void RenderWidgetHostImpl::SetInitialRenderSizeParams(
610 const ViewMsg_Resize_Params& resize_params) {
611 resize_ack_pending_ = resize_params.needs_resize_ack;
613 old_resize_params_ =
614 make_scoped_ptr(new ViewMsg_Resize_Params(resize_params));
617 void RenderWidgetHostImpl::WasResized() {
618 // Skip if the |delegate_| has already been detached because
619 // it's web contents is being deleted.
620 if (resize_ack_pending_ || !process_->HasConnection() || !view_ ||
621 !renderer_initialized_ || auto_resize_enabled_ || !delegate_) {
622 if (resize_ack_pending_ && color_profile_out_of_date_)
623 DispatchColorProfile();
624 return;
627 scoped_ptr<ViewMsg_Resize_Params> params(new ViewMsg_Resize_Params);
628 if (color_profile_out_of_date_)
629 DispatchColorProfile();
630 if (!GetResizeParams(params.get()))
631 return;
633 bool width_changed =
634 !old_resize_params_ ||
635 old_resize_params_->new_size.width() != params->new_size.width();
636 if (Send(new ViewMsg_Resize(routing_id_, *params))) {
637 resize_ack_pending_ = params->needs_resize_ack;
638 old_resize_params_.swap(params);
641 if (delegate_)
642 delegate_->RenderWidgetWasResized(this, width_changed);
645 void RenderWidgetHostImpl::DispatchColorProfile() {
646 #if defined(OS_WIN) || defined(OS_MACOSX) || defined(OS_LINUX)
647 static bool image_profiles = base::CommandLine::ForCurrentProcess()->
648 HasSwitch(switches::kEnableImageColorProfiles);
649 if (!image_profiles)
650 return;
651 #if defined(OS_WIN)
652 // Windows will read disk to get the color profile data if needed, so
653 // dispatch the SendColorProfile() work off the UI thread.
654 BrowserThread::PostBlockingPoolTask(
655 FROM_HERE,
656 base::Bind(&RenderWidgetHostImpl::SendColorProfile,
657 weak_factory_.GetWeakPtr()));
658 #elif !defined(OS_CHROMEOS) && !defined(OS_IOS) && !defined(OS_ANDROID)
659 // Only support desktop Mac and Linux at this time.
660 SendColorProfile();
661 #endif
662 #endif
665 void RenderWidgetHostImpl::SendColorProfile() {
666 if (!view_ || !delegate_)
667 return;
668 DCHECK(!view_->GetRequestedRendererSize().IsEmpty());
669 #if defined(OS_WIN)
670 DCHECK(!BrowserThread::CurrentlyOn(BrowserThread::UI));
671 DCHECK(!BrowserThread::CurrentlyOn(BrowserThread::IO));
672 #endif
673 std::vector<char> color_profile;
674 if (!GetScreenColorProfile(&color_profile))
675 return;
676 if (!renderer_initialized_ || !process_->HasConnection())
677 return;
678 if (!Send(new ViewMsg_ColorProfile(routing_id_, color_profile)))
679 return;
680 color_profile_out_of_date_ = false;
683 void RenderWidgetHostImpl::ResizeRectChanged(const gfx::Rect& new_rect) {
684 Send(new ViewMsg_ChangeResizeRect(routing_id_, new_rect));
687 void RenderWidgetHostImpl::GotFocus() {
688 Focus();
689 if (delegate_)
690 delegate_->RenderWidgetGotFocus(this);
693 void RenderWidgetHostImpl::Focus() {
694 is_focused_ = true;
696 Send(new InputMsg_SetFocus(routing_id_, true));
699 void RenderWidgetHostImpl::Blur() {
700 is_focused_ = false;
702 // If there is a pending mouse lock request, we don't want to reject it at
703 // this point. The user can switch focus back to this view and approve the
704 // request later.
705 if (IsMouseLocked())
706 view_->UnlockMouse();
708 if (touch_emulator_)
709 touch_emulator_->CancelTouch();
711 Send(new InputMsg_SetFocus(routing_id_, false));
714 void RenderWidgetHostImpl::LostCapture() {
715 if (touch_emulator_)
716 touch_emulator_->CancelTouch();
718 Send(new InputMsg_MouseCaptureLost(routing_id_));
721 void RenderWidgetHostImpl::SetActive(bool active) {
722 Send(new ViewMsg_SetActive(routing_id_, active));
725 void RenderWidgetHostImpl::LostMouseLock() {
726 Send(new ViewMsg_MouseLockLost(routing_id_));
729 void RenderWidgetHostImpl::ViewDestroyed() {
730 RejectMouseLockOrUnlockIfNecessary();
732 // TODO(evanm): tracking this may no longer be necessary;
733 // eliminate this function if so.
734 SetView(NULL);
737 void RenderWidgetHostImpl::CopyFromBackingStore(
738 const gfx::Rect& src_subrect,
739 const gfx::Size& accelerated_dst_size,
740 ReadbackRequestCallback& callback,
741 const SkColorType preferred_color_type) {
742 if (view_) {
743 TRACE_EVENT0("browser",
744 "RenderWidgetHostImpl::CopyFromBackingStore::FromCompositingSurface");
745 gfx::Rect accelerated_copy_rect = src_subrect.IsEmpty() ?
746 gfx::Rect(view_->GetViewBounds().size()) : src_subrect;
747 view_->CopyFromCompositingSurface(accelerated_copy_rect,
748 accelerated_dst_size, callback,
749 preferred_color_type);
750 return;
753 callback.Run(SkBitmap(), content::READBACK_FAILED);
756 bool RenderWidgetHostImpl::CanCopyFromBackingStore() {
757 if (view_)
758 return view_->IsSurfaceAvailableForCopy();
759 return false;
762 #if defined(OS_ANDROID)
763 void RenderWidgetHostImpl::LockBackingStore() {
764 if (view_)
765 view_->LockCompositingSurface();
768 void RenderWidgetHostImpl::UnlockBackingStore() {
769 if (view_)
770 view_->UnlockCompositingSurface();
772 #endif
774 #if defined(OS_MACOSX)
775 void RenderWidgetHostImpl::PauseForPendingResizeOrRepaints() {
776 TRACE_EVENT0("browser",
777 "RenderWidgetHostImpl::PauseForPendingResizeOrRepaints");
779 if (!CanPauseForPendingResizeOrRepaints())
780 return;
782 WaitForSurface();
785 bool RenderWidgetHostImpl::CanPauseForPendingResizeOrRepaints() {
786 // Do not pause if the view is hidden.
787 if (is_hidden())
788 return false;
790 // Do not pause if there is not a paint or resize already coming.
791 if (!repaint_ack_pending_ && !resize_ack_pending_)
792 return false;
794 return true;
797 void RenderWidgetHostImpl::WaitForSurface() {
798 // How long to (synchronously) wait for the renderer to respond with a
799 // new frame when our current frame doesn't exist or is the wrong size.
800 // This timeout impacts the "choppiness" of our window resize.
801 const int kPaintMsgTimeoutMS = 50;
803 if (!view_)
804 return;
806 // The view_size will be current_size_ for auto-sized views and otherwise the
807 // size of the view_. (For auto-sized views, current_size_ is updated during
808 // UpdateRect messages.)
809 gfx::Size view_size = current_size_;
810 if (!auto_resize_enabled_) {
811 // Get the desired size from the current view bounds.
812 gfx::Rect view_rect = view_->GetViewBounds();
813 if (view_rect.IsEmpty())
814 return;
815 view_size = view_rect.size();
818 TRACE_EVENT2("renderer_host",
819 "RenderWidgetHostImpl::WaitForSurface",
820 "width",
821 base::IntToString(view_size.width()),
822 "height",
823 base::IntToString(view_size.height()));
825 // We should not be asked to paint while we are hidden. If we are hidden,
826 // then it means that our consumer failed to call WasShown.
827 DCHECK(!is_hidden_) << "WaitForSurface called while hidden!";
829 // We should never be called recursively; this can theoretically lead to
830 // infinite recursion and almost certainly leads to lower performance.
831 DCHECK(!in_get_backing_store_) << "WaitForSurface called recursively!";
832 base::AutoReset<bool> auto_reset_in_get_backing_store(
833 &in_get_backing_store_, true);
835 // We might have a surface that we can use already.
836 if (view_->HasAcceleratedSurface(view_size))
837 return;
839 // Request that the renderer produce a frame of the right size, if it
840 // hasn't been requested already.
841 if (!repaint_ack_pending_ && !resize_ack_pending_) {
842 repaint_start_time_ = TimeTicks::Now();
843 repaint_ack_pending_ = true;
844 TRACE_EVENT_ASYNC_BEGIN0(
845 "renderer_host", "RenderWidgetHostImpl::repaint_ack_pending_", this);
846 Send(new ViewMsg_Repaint(routing_id_, view_size));
849 // Pump a nested message loop until we time out or get a frame of the right
850 // size.
851 TimeTicks start_time = TimeTicks::Now();
852 TimeDelta time_left = TimeDelta::FromMilliseconds(kPaintMsgTimeoutMS);
853 TimeTicks timeout_time = start_time + time_left;
854 while (1) {
855 TRACE_EVENT0("renderer_host", "WaitForSurface::WaitForSingleTaskToRun");
856 if (RenderWidgetResizeHelper::Get()->WaitForSingleTaskToRun(time_left)) {
857 // For auto-resized views, current_size_ determines the view_size and it
858 // may have changed during the handling of an UpdateRect message.
859 if (auto_resize_enabled_)
860 view_size = current_size_;
861 if (view_->HasAcceleratedSurface(view_size))
862 break;
864 time_left = timeout_time - TimeTicks::Now();
865 if (time_left <= TimeDelta::FromSeconds(0)) {
866 TRACE_EVENT0("renderer_host", "WaitForSurface::Timeout");
867 break;
871 UMA_HISTOGRAM_CUSTOM_TIMES("OSX.RendererHost.SurfaceWaitTime",
872 TimeTicks::Now() - start_time,
873 TimeDelta::FromMilliseconds(1),
874 TimeDelta::FromMilliseconds(200), 50);
876 #endif
878 bool RenderWidgetHostImpl::ScheduleComposite() {
879 if (is_hidden_ || current_size_.IsEmpty() || repaint_ack_pending_ ||
880 resize_ack_pending_) {
881 return false;
884 // Send out a request to the renderer to paint the view if required.
885 repaint_start_time_ = TimeTicks::Now();
886 repaint_ack_pending_ = true;
887 TRACE_EVENT_ASYNC_BEGIN0(
888 "renderer_host", "RenderWidgetHostImpl::repaint_ack_pending_", this);
889 Send(new ViewMsg_Repaint(routing_id_, current_size_));
890 return true;
893 void RenderWidgetHostImpl::StartHangMonitorTimeout(base::TimeDelta delay) {
894 if (hang_monitor_timeout_)
895 hang_monitor_timeout_->Start(delay);
898 void RenderWidgetHostImpl::RestartHangMonitorTimeout() {
899 if (hang_monitor_timeout_)
900 hang_monitor_timeout_->Restart(hung_renderer_delay_);
903 void RenderWidgetHostImpl::StopHangMonitorTimeout() {
904 if (hang_monitor_timeout_)
905 hang_monitor_timeout_->Stop();
906 RendererIsResponsive();
909 void RenderWidgetHostImpl::ForwardMouseEvent(const WebMouseEvent& mouse_event) {
910 ForwardMouseEventWithLatencyInfo(mouse_event, ui::LatencyInfo());
913 void RenderWidgetHostImpl::ForwardMouseEventWithLatencyInfo(
914 const blink::WebMouseEvent& mouse_event,
915 const ui::LatencyInfo& ui_latency) {
916 TRACE_EVENT2("input", "RenderWidgetHostImpl::ForwardMouseEvent",
917 "x", mouse_event.x, "y", mouse_event.y);
919 for (size_t i = 0; i < mouse_event_callbacks_.size(); ++i) {
920 if (mouse_event_callbacks_[i].Run(mouse_event))
921 return;
924 if (IgnoreInputEvents())
925 return;
927 if (touch_emulator_ && touch_emulator_->HandleMouseEvent(mouse_event))
928 return;
930 MouseEventWithLatencyInfo mouse_with_latency(mouse_event, ui_latency);
931 latency_tracker_.OnInputEvent(mouse_event, &mouse_with_latency.latency);
932 input_router_->SendMouseEvent(mouse_with_latency);
934 // Pass mouse state to gpu service if the subscribe uniform
935 // extension is enabled.
936 if (process_->SubscribeUniformEnabled()) {
937 gpu::ValueState state;
938 state.int_value[0] = mouse_event.x;
939 state.int_value[1] = mouse_event.y;
940 // TODO(orglofch) Separate the mapping of pending value states to the
941 // Gpu Service to be per RWH not per process
942 process_->SendUpdateValueState(GL_MOUSE_POSITION_CHROMIUM, state);
946 void RenderWidgetHostImpl::ForwardWheelEvent(
947 const WebMouseWheelEvent& wheel_event) {
948 ForwardWheelEventWithLatencyInfo(wheel_event, ui::LatencyInfo());
951 void RenderWidgetHostImpl::ForwardWheelEventWithLatencyInfo(
952 const blink::WebMouseWheelEvent& wheel_event,
953 const ui::LatencyInfo& ui_latency) {
954 TRACE_EVENT2("input", "RenderWidgetHostImpl::ForwardWheelEvent",
955 "dx", wheel_event.deltaX, "dy", wheel_event.deltaY);
957 if (IgnoreInputEvents())
958 return;
960 if (touch_emulator_ && touch_emulator_->HandleMouseWheelEvent(wheel_event))
961 return;
963 MouseWheelEventWithLatencyInfo wheel_with_latency(wheel_event, ui_latency);
964 latency_tracker_.OnInputEvent(wheel_event, &wheel_with_latency.latency);
965 input_router_->SendWheelEvent(wheel_with_latency);
968 void RenderWidgetHostImpl::ForwardGestureEvent(
969 const blink::WebGestureEvent& gesture_event) {
970 ForwardGestureEventWithLatencyInfo(gesture_event, ui::LatencyInfo());
973 void RenderWidgetHostImpl::ForwardGestureEventWithLatencyInfo(
974 const blink::WebGestureEvent& gesture_event,
975 const ui::LatencyInfo& ui_latency) {
976 TRACE_EVENT0("input", "RenderWidgetHostImpl::ForwardGestureEvent");
977 // Early out if necessary, prior to performing latency logic.
978 if (IgnoreInputEvents())
979 return;
981 if (delegate_->PreHandleGestureEvent(gesture_event))
982 return;
984 GestureEventWithLatencyInfo gesture_with_latency(gesture_event, ui_latency);
985 latency_tracker_.OnInputEvent(gesture_event, &gesture_with_latency.latency);
986 input_router_->SendGestureEvent(gesture_with_latency);
989 void RenderWidgetHostImpl::ForwardEmulatedTouchEvent(
990 const blink::WebTouchEvent& touch_event) {
991 TRACE_EVENT0("input", "RenderWidgetHostImpl::ForwardEmulatedTouchEvent");
993 TouchEventWithLatencyInfo touch_with_latency(touch_event);
994 latency_tracker_.OnInputEvent(touch_event, &touch_with_latency.latency);
995 input_router_->SendTouchEvent(touch_with_latency);
998 void RenderWidgetHostImpl::ForwardTouchEventWithLatencyInfo(
999 const blink::WebTouchEvent& touch_event,
1000 const ui::LatencyInfo& ui_latency) {
1001 TRACE_EVENT0("input", "RenderWidgetHostImpl::ForwardTouchEvent");
1003 // Always forward TouchEvents for touch stream consistency. They will be
1004 // ignored if appropriate in FilterInputEvent().
1006 TouchEventWithLatencyInfo touch_with_latency(touch_event, ui_latency);
1007 if (touch_emulator_ &&
1008 touch_emulator_->HandleTouchEvent(touch_with_latency.event)) {
1009 if (view_) {
1010 view_->ProcessAckedTouchEvent(
1011 touch_with_latency, INPUT_EVENT_ACK_STATE_CONSUMED);
1013 return;
1016 latency_tracker_.OnInputEvent(touch_event, &touch_with_latency.latency);
1017 input_router_->SendTouchEvent(touch_with_latency);
1020 void RenderWidgetHostImpl::ForwardKeyboardEvent(
1021 const NativeWebKeyboardEvent& key_event) {
1022 TRACE_EVENT0("input", "RenderWidgetHostImpl::ForwardKeyboardEvent");
1023 if (IgnoreInputEvents())
1024 return;
1026 if (!process_->HasConnection())
1027 return;
1029 // First, let keypress listeners take a shot at handling the event. If a
1030 // listener handles the event, it should not be propagated to the renderer.
1031 if (KeyPressListenersHandleEvent(key_event)) {
1032 // Some keypresses that are accepted by the listener might have follow up
1033 // char events, which should be ignored.
1034 if (key_event.type == WebKeyboardEvent::RawKeyDown)
1035 suppress_next_char_events_ = true;
1036 return;
1039 if (key_event.type == WebKeyboardEvent::Char &&
1040 (key_event.windowsKeyCode == ui::VKEY_RETURN ||
1041 key_event.windowsKeyCode == ui::VKEY_SPACE)) {
1042 OnUserGesture();
1045 // Double check the type to make sure caller hasn't sent us nonsense that
1046 // will mess up our key queue.
1047 if (!WebInputEvent::isKeyboardEventType(key_event.type))
1048 return;
1050 if (suppress_next_char_events_) {
1051 // If preceding RawKeyDown event was handled by the browser, then we need
1052 // suppress all Char events generated by it. Please note that, one
1053 // RawKeyDown event may generate multiple Char events, so we can't reset
1054 // |suppress_next_char_events_| until we get a KeyUp or a RawKeyDown.
1055 if (key_event.type == WebKeyboardEvent::Char)
1056 return;
1057 // We get a KeyUp or a RawKeyDown event.
1058 suppress_next_char_events_ = false;
1061 bool is_shortcut = false;
1063 // Only pre-handle the key event if it's not handled by the input method.
1064 if (delegate_ && !key_event.skip_in_browser) {
1065 // We need to set |suppress_next_char_events_| to true if
1066 // PreHandleKeyboardEvent() returns true, but |this| may already be
1067 // destroyed at that time. So set |suppress_next_char_events_| true here,
1068 // then revert it afterwards when necessary.
1069 if (key_event.type == WebKeyboardEvent::RawKeyDown)
1070 suppress_next_char_events_ = true;
1072 // Tab switching/closing accelerators aren't sent to the renderer to avoid
1073 // a hung/malicious renderer from interfering.
1074 if (delegate_->PreHandleKeyboardEvent(key_event, &is_shortcut))
1075 return;
1077 if (key_event.type == WebKeyboardEvent::RawKeyDown)
1078 suppress_next_char_events_ = false;
1081 if (touch_emulator_ && touch_emulator_->HandleKeyboardEvent(key_event))
1082 return;
1084 NativeWebKeyboardEventWithLatencyInfo key_event_with_latency(key_event);
1085 latency_tracker_.OnInputEvent(key_event, &key_event_with_latency.latency);
1086 input_router_->SendKeyboardEvent(key_event_with_latency, is_shortcut);
1089 void RenderWidgetHostImpl::QueueSyntheticGesture(
1090 scoped_ptr<SyntheticGesture> synthetic_gesture,
1091 const base::Callback<void(SyntheticGesture::Result)>& on_complete) {
1092 if (!synthetic_gesture_controller_ && view_) {
1093 synthetic_gesture_controller_.reset(
1094 new SyntheticGestureController(
1095 view_->CreateSyntheticGestureTarget().Pass()));
1097 if (synthetic_gesture_controller_) {
1098 synthetic_gesture_controller_->QueueSyntheticGesture(
1099 synthetic_gesture.Pass(), on_complete);
1103 void RenderWidgetHostImpl::SetCursor(const WebCursor& cursor) {
1104 if (!view_)
1105 return;
1106 view_->UpdateCursor(cursor);
1109 void RenderWidgetHostImpl::ShowContextMenuAtPoint(const gfx::Point& point) {
1110 Send(new ViewMsg_ShowContextMenu(
1111 GetRoutingID(), ui::MENU_SOURCE_MOUSE, point));
1114 void RenderWidgetHostImpl::SendCursorVisibilityState(bool is_visible) {
1115 Send(new InputMsg_CursorVisibilityChange(GetRoutingID(), is_visible));
1118 int64 RenderWidgetHostImpl::GetLatencyComponentId() const {
1119 return latency_tracker_.latency_component_id();
1122 // static
1123 void RenderWidgetHostImpl::DisableResizeAckCheckForTesting() {
1124 g_check_for_pending_resize_ack = false;
1127 void RenderWidgetHostImpl::AddKeyPressEventCallback(
1128 const KeyPressEventCallback& callback) {
1129 key_press_event_callbacks_.push_back(callback);
1132 void RenderWidgetHostImpl::RemoveKeyPressEventCallback(
1133 const KeyPressEventCallback& callback) {
1134 for (size_t i = 0; i < key_press_event_callbacks_.size(); ++i) {
1135 if (key_press_event_callbacks_[i].Equals(callback)) {
1136 key_press_event_callbacks_.erase(
1137 key_press_event_callbacks_.begin() + i);
1138 return;
1143 void RenderWidgetHostImpl::AddMouseEventCallback(
1144 const MouseEventCallback& callback) {
1145 mouse_event_callbacks_.push_back(callback);
1148 void RenderWidgetHostImpl::RemoveMouseEventCallback(
1149 const MouseEventCallback& callback) {
1150 for (size_t i = 0; i < mouse_event_callbacks_.size(); ++i) {
1151 if (mouse_event_callbacks_[i].Equals(callback)) {
1152 mouse_event_callbacks_.erase(mouse_event_callbacks_.begin() + i);
1153 return;
1158 void RenderWidgetHostImpl::GetWebScreenInfo(blink::WebScreenInfo* result) {
1159 TRACE_EVENT0("renderer_host", "RenderWidgetHostImpl::GetWebScreenInfo");
1160 if (view_)
1161 view_->GetScreenInfo(result);
1162 else
1163 RenderWidgetHostViewBase::GetDefaultScreenInfo(result);
1164 // TODO(sievers): find a way to make this done another way so the method
1165 // can be const.
1166 latency_tracker_.set_device_scale_factor(result->deviceScaleFactor);
1169 bool RenderWidgetHostImpl::GetScreenColorProfile(
1170 std::vector<char>* color_profile) {
1171 DCHECK(color_profile->empty());
1172 if (view_)
1173 return view_->GetScreenColorProfile(color_profile);
1174 return false;
1177 void RenderWidgetHostImpl::NotifyScreenInfoChanged() {
1178 color_profile_out_of_date_ = true;
1180 if (delegate_)
1181 delegate_->ScreenInfoChanged();
1183 // The resize message (which may not happen immediately) will carry with it
1184 // the screen info as well as the new size (if the screen has changed scale
1185 // factor).
1186 WasResized();
1189 void RenderWidgetHostImpl::GetSnapshotFromBrowser(
1190 const base::Callback<void(const unsigned char*,size_t)> callback) {
1191 int id = next_browser_snapshot_id_++;
1192 pending_browser_snapshots_.insert(std::make_pair(id, callback));
1193 Send(new ViewMsg_ForceRedraw(GetRoutingID(), id));
1196 const NativeWebKeyboardEvent*
1197 RenderWidgetHostImpl::GetLastKeyboardEvent() const {
1198 return input_router_->GetLastKeyboardEvent();
1201 void RenderWidgetHostImpl::OnSelectionChanged(const base::string16& text,
1202 size_t offset,
1203 const gfx::Range& range) {
1204 if (view_)
1205 view_->SelectionChanged(text, offset, range);
1208 void RenderWidgetHostImpl::OnSelectionBoundsChanged(
1209 const ViewHostMsg_SelectionBounds_Params& params) {
1210 if (view_) {
1211 view_->SelectionBoundsChanged(params);
1215 void RenderWidgetHostImpl::UpdateVSyncParameters(base::TimeTicks timebase,
1216 base::TimeDelta interval) {
1217 Send(new ViewMsg_UpdateVSyncParameters(GetRoutingID(), timebase, interval));
1220 void RenderWidgetHostImpl::RendererExited(base::TerminationStatus status,
1221 int exit_code) {
1222 if (!renderer_initialized_)
1223 return;
1225 // Clearing this flag causes us to re-create the renderer when recovering
1226 // from a crashed renderer.
1227 renderer_initialized_ = false;
1229 waiting_for_screen_rects_ack_ = false;
1231 // Must reset these to ensure that keyboard events work with a new renderer.
1232 suppress_next_char_events_ = false;
1234 // Reset some fields in preparation for recovering from a crash.
1235 ResetSizeAndRepaintPendingFlags();
1236 current_size_.SetSize(0, 0);
1237 // After the renderer crashes, the view is destroyed and so the
1238 // RenderWidgetHost cannot track its visibility anymore. We assume such
1239 // RenderWidgetHost to be visible for the sake of internal accounting - be
1240 // careful about changing this - see http://crbug.com/401859.
1242 // We need to at least make sure that the RenderProcessHost is notified about
1243 // the |is_hidden_| change, so that the renderer will have correct visibility
1244 // set when respawned.
1245 if (is_hidden_) {
1246 process_->WidgetRestored();
1247 is_hidden_ = false;
1250 // Reset this to ensure the hung renderer mechanism is working properly.
1251 in_flight_event_count_ = 0;
1252 StopHangMonitorTimeout();
1254 if (view_) {
1255 GpuSurfaceTracker::Get()->SetSurfaceHandle(surface_id_,
1256 gfx::GLSurfaceHandle());
1257 view_->RenderProcessGone(status, exit_code);
1258 view_ = NULL; // The View should be deleted by RenderProcessGone.
1259 view_weak_.reset();
1262 // Reconstruct the input router to ensure that it has fresh state for a new
1263 // renderer. Otherwise it may be stuck waiting for the old renderer to ack an
1264 // event. (In particular, the above call to view_->RenderProcessGone will
1265 // destroy the aura window, which may dispatch a synthetic mouse move.)
1266 input_router_.reset(new InputRouterImpl(
1267 process_, this, this, routing_id_, GetInputRouterConfigForPlatform()));
1269 synthetic_gesture_controller_.reset();
1272 void RenderWidgetHostImpl::UpdateTextDirection(WebTextDirection direction) {
1273 text_direction_updated_ = true;
1274 text_direction_ = direction;
1277 void RenderWidgetHostImpl::CancelUpdateTextDirection() {
1278 if (text_direction_updated_)
1279 text_direction_canceled_ = true;
1282 void RenderWidgetHostImpl::NotifyTextDirection() {
1283 if (text_direction_updated_) {
1284 if (!text_direction_canceled_)
1285 Send(new ViewMsg_SetTextDirection(GetRoutingID(), text_direction_));
1286 text_direction_updated_ = false;
1287 text_direction_canceled_ = false;
1291 void RenderWidgetHostImpl::ImeSetComposition(
1292 const base::string16& text,
1293 const std::vector<blink::WebCompositionUnderline>& underlines,
1294 int selection_start,
1295 int selection_end) {
1296 Send(new InputMsg_ImeSetComposition(
1297 GetRoutingID(), text, underlines, selection_start, selection_end));
1300 void RenderWidgetHostImpl::ImeConfirmComposition(
1301 const base::string16& text,
1302 const gfx::Range& replacement_range,
1303 bool keep_selection) {
1304 Send(new InputMsg_ImeConfirmComposition(
1305 GetRoutingID(), text, replacement_range, keep_selection));
1308 void RenderWidgetHostImpl::ImeCancelComposition() {
1309 Send(new InputMsg_ImeSetComposition(GetRoutingID(), base::string16(),
1310 std::vector<blink::WebCompositionUnderline>(), 0, 0));
1313 gfx::Rect RenderWidgetHostImpl::GetRootWindowResizerRect() const {
1314 return gfx::Rect();
1317 void RenderWidgetHostImpl::RequestToLockMouse(bool user_gesture,
1318 bool last_unlocked_by_target) {
1319 // Directly reject to lock the mouse. Subclass can override this method to
1320 // decide whether to allow mouse lock or not.
1321 GotResponseToLockMouseRequest(false);
1324 void RenderWidgetHostImpl::RejectMouseLockOrUnlockIfNecessary() {
1325 DCHECK(!pending_mouse_lock_request_ || !IsMouseLocked());
1326 if (pending_mouse_lock_request_) {
1327 pending_mouse_lock_request_ = false;
1328 Send(new ViewMsg_LockMouse_ACK(routing_id_, false));
1329 } else if (IsMouseLocked()) {
1330 view_->UnlockMouse();
1334 bool RenderWidgetHostImpl::IsMouseLocked() const {
1335 return view_ ? view_->IsMouseLocked() : false;
1338 bool RenderWidgetHostImpl::IsFullscreenGranted() const {
1339 return false;
1342 blink::WebDisplayMode RenderWidgetHostImpl::GetDisplayMode() const {
1343 return blink::WebDisplayModeBrowser;
1346 void RenderWidgetHostImpl::SetAutoResize(bool enable,
1347 const gfx::Size& min_size,
1348 const gfx::Size& max_size) {
1349 auto_resize_enabled_ = enable;
1350 min_size_for_auto_resize_ = min_size;
1351 max_size_for_auto_resize_ = max_size;
1354 void RenderWidgetHostImpl::Destroy() {
1355 NotificationService::current()->Notify(
1356 NOTIFICATION_RENDER_WIDGET_HOST_DESTROYED,
1357 Source<RenderWidgetHost>(this),
1358 NotificationService::NoDetails());
1360 // Tell the view to die.
1361 // Note that in the process of the view shutting down, it can call a ton
1362 // of other messages on us. So if you do any other deinitialization here,
1363 // do it after this call to view_->Destroy().
1364 if (view_) {
1365 view_->Destroy();
1366 view_ = nullptr;
1369 delete this;
1372 void RenderWidgetHostImpl::RendererIsUnresponsive() {
1373 NotificationService::current()->Notify(
1374 NOTIFICATION_RENDER_WIDGET_HOST_HANG,
1375 Source<RenderWidgetHost>(this),
1376 NotificationService::NoDetails());
1377 is_unresponsive_ = true;
1378 NotifyRendererUnresponsive();
1381 void RenderWidgetHostImpl::RendererIsResponsive() {
1382 if (is_unresponsive_) {
1383 is_unresponsive_ = false;
1384 NotifyRendererResponsive();
1388 void RenderWidgetHostImpl::OnRenderViewReady() {
1389 SendScreenRects();
1390 WasResized();
1393 void RenderWidgetHostImpl::OnRenderProcessGone(int status, int exit_code) {
1394 // RenderFrameHost owns a RenderWidgetHost when it needs one, in which case
1395 // it handles destruction.
1396 if (!owned_by_render_frame_host_) {
1397 // TODO(evanm): This synchronously ends up calling "delete this".
1398 // Is that really what we want in response to this message? I'm matching
1399 // previous behavior of the code here.
1400 Destroy();
1401 } else {
1402 RendererExited(static_cast<base::TerminationStatus>(status), exit_code);
1406 void RenderWidgetHostImpl::OnClose() {
1407 Shutdown();
1410 void RenderWidgetHostImpl::OnSetTooltipText(
1411 const base::string16& tooltip_text,
1412 WebTextDirection text_direction_hint) {
1413 // First, add directionality marks around tooltip text if necessary.
1414 // A naive solution would be to simply always wrap the text. However, on
1415 // windows, Unicode directional embedding characters can't be displayed on
1416 // systems that lack RTL fonts and are instead displayed as empty squares.
1418 // To get around this we only wrap the string when we deem it necessary i.e.
1419 // when the locale direction is different than the tooltip direction hint.
1421 // Currently, we use element's directionality as the tooltip direction hint.
1422 // An alternate solution would be to set the overall directionality based on
1423 // trying to detect the directionality from the tooltip text rather than the
1424 // element direction. One could argue that would be a preferable solution
1425 // but we use the current approach to match Fx & IE's behavior.
1426 base::string16 wrapped_tooltip_text = tooltip_text;
1427 if (!tooltip_text.empty()) {
1428 if (text_direction_hint == blink::WebTextDirectionLeftToRight) {
1429 // Force the tooltip to have LTR directionality.
1430 wrapped_tooltip_text =
1431 base::i18n::GetDisplayStringInLTRDirectionality(wrapped_tooltip_text);
1432 } else if (text_direction_hint == blink::WebTextDirectionRightToLeft &&
1433 !base::i18n::IsRTL()) {
1434 // Force the tooltip to have RTL directionality.
1435 base::i18n::WrapStringWithRTLFormatting(&wrapped_tooltip_text);
1438 if (GetView())
1439 view_->SetTooltipText(wrapped_tooltip_text);
1442 void RenderWidgetHostImpl::OnUpdateScreenRectsAck() {
1443 waiting_for_screen_rects_ack_ = false;
1444 if (!view_)
1445 return;
1447 if (view_->GetViewBounds() == last_view_screen_rect_ &&
1448 view_->GetBoundsInRootWindow() == last_window_screen_rect_) {
1449 return;
1452 SendScreenRects();
1455 void RenderWidgetHostImpl::OnRequestMove(const gfx::Rect& pos) {
1456 if (view_) {
1457 view_->SetBounds(pos);
1458 Send(new ViewMsg_Move_ACK(routing_id_));
1462 bool RenderWidgetHostImpl::OnSwapCompositorFrame(
1463 const IPC::Message& message) {
1464 // This trace event is used in
1465 // chrome/browser/extensions/api/cast_streaming/performance_test.cc
1466 TRACE_EVENT0("test_fps,benchmark", "OnSwapCompositorFrame");
1467 ViewHostMsg_SwapCompositorFrame::Param param;
1468 if (!ViewHostMsg_SwapCompositorFrame::Read(&message, &param))
1469 return false;
1470 scoped_ptr<cc::CompositorFrame> frame(new cc::CompositorFrame);
1471 uint32 output_surface_id = base::get<0>(param);
1472 base::get<1>(param).AssignTo(frame.get());
1473 std::vector<IPC::Message> messages_to_deliver_with_frame;
1474 messages_to_deliver_with_frame.swap(base::get<2>(param));
1476 if (!ui::LatencyInfo::Verify(frame->metadata.latency_info,
1477 "RenderWidgetHostImpl::OnSwapCompositorFrame"))
1478 return false;
1480 latency_tracker_.OnSwapCompositorFrame(&frame->metadata.latency_info);
1482 bool is_mobile_optimized = IsMobileOptimizedFrame(frame->metadata);
1483 input_router_->NotifySiteIsMobileOptimized(is_mobile_optimized);
1484 if (touch_emulator_)
1485 touch_emulator_->SetDoubleTapSupportForPageEnabled(!is_mobile_optimized);
1487 if (view_) {
1488 view_->OnSwapCompositorFrame(output_surface_id, frame.Pass());
1489 view_->DidReceiveRendererFrame();
1490 } else {
1491 cc::CompositorFrameAck ack;
1492 if (frame->gl_frame_data) {
1493 ack.gl_frame_data = frame->gl_frame_data.Pass();
1494 ack.gl_frame_data->sync_point = 0;
1495 } else if (frame->delegated_frame_data) {
1496 cc::TransferableResource::ReturnResources(
1497 frame->delegated_frame_data->resource_list,
1498 &ack.resources);
1500 SendSwapCompositorFrameAck(routing_id_, output_surface_id,
1501 process_->GetID(), ack);
1504 RenderProcessHost* rph = GetProcess();
1505 for (std::vector<IPC::Message>::const_iterator i =
1506 messages_to_deliver_with_frame.begin();
1507 i != messages_to_deliver_with_frame.end();
1508 ++i) {
1509 rph->OnMessageReceived(*i);
1510 if (i->dispatch_error())
1511 rph->OnBadMessageReceived(*i);
1513 messages_to_deliver_with_frame.clear();
1515 return true;
1518 void RenderWidgetHostImpl::OnUpdateRect(
1519 const ViewHostMsg_UpdateRect_Params& params) {
1520 TRACE_EVENT0("renderer_host", "RenderWidgetHostImpl::OnUpdateRect");
1521 TimeTicks paint_start = TimeTicks::Now();
1523 // Update our knowledge of the RenderWidget's size.
1524 current_size_ = params.view_size;
1526 bool is_resize_ack =
1527 ViewHostMsg_UpdateRect_Flags::is_resize_ack(params.flags);
1529 // resize_ack_pending_ needs to be cleared before we call DidPaintRect, since
1530 // that will end up reaching GetBackingStore.
1531 if (is_resize_ack) {
1532 DCHECK(!g_check_for_pending_resize_ack || resize_ack_pending_);
1533 resize_ack_pending_ = false;
1536 bool is_repaint_ack =
1537 ViewHostMsg_UpdateRect_Flags::is_repaint_ack(params.flags);
1538 if (is_repaint_ack) {
1539 DCHECK(repaint_ack_pending_);
1540 TRACE_EVENT_ASYNC_END0(
1541 "renderer_host", "RenderWidgetHostImpl::repaint_ack_pending_", this);
1542 repaint_ack_pending_ = false;
1543 TimeDelta delta = TimeTicks::Now() - repaint_start_time_;
1544 UMA_HISTOGRAM_TIMES("MPArch.RWH_RepaintDelta", delta);
1547 DCHECK(!params.view_size.IsEmpty());
1549 DidUpdateBackingStore(params, paint_start);
1551 if (auto_resize_enabled_) {
1552 bool post_callback = new_auto_size_.IsEmpty();
1553 new_auto_size_ = params.view_size;
1554 if (post_callback) {
1555 base::ThreadTaskRunnerHandle::Get()->PostTask(
1556 FROM_HERE, base::Bind(&RenderWidgetHostImpl::DelayedAutoResized,
1557 weak_factory_.GetWeakPtr()));
1561 // Log the time delta for processing a paint message. On platforms that don't
1562 // support asynchronous painting, this is equivalent to
1563 // MPArch.RWH_TotalPaintTime.
1564 TimeDelta delta = TimeTicks::Now() - paint_start;
1565 UMA_HISTOGRAM_TIMES("MPArch.RWH_OnMsgUpdateRect", delta);
1568 void RenderWidgetHostImpl::DidUpdateBackingStore(
1569 const ViewHostMsg_UpdateRect_Params& params,
1570 const TimeTicks& paint_start) {
1571 TRACE_EVENT0("renderer_host", "RenderWidgetHostImpl::DidUpdateBackingStore");
1572 TimeTicks update_start = TimeTicks::Now();
1574 // Move the plugins if the view hasn't already been destroyed. Plugin moves
1575 // will not be re-issued, so must move them now, regardless of whether we
1576 // paint or not. MovePluginWindows attempts to move the plugin windows and
1577 // in the process could dispatch other window messages which could cause the
1578 // view to be destroyed.
1579 if (view_)
1580 view_->MovePluginWindows(params.plugin_window_moves);
1582 NotificationService::current()->Notify(
1583 NOTIFICATION_RENDER_WIDGET_HOST_DID_UPDATE_BACKING_STORE,
1584 Source<RenderWidgetHost>(this),
1585 NotificationService::NoDetails());
1587 // We don't need to update the view if the view is hidden. We must do this
1588 // early return after the ACK is sent, however, or the renderer will not send
1589 // us more data.
1590 if (is_hidden_)
1591 return;
1593 // If we got a resize ack, then perhaps we have another resize to send?
1594 bool is_resize_ack =
1595 ViewHostMsg_UpdateRect_Flags::is_resize_ack(params.flags);
1596 if (is_resize_ack)
1597 WasResized();
1599 // Log the time delta for processing a paint message.
1600 TimeTicks now = TimeTicks::Now();
1601 TimeDelta delta = now - update_start;
1602 UMA_HISTOGRAM_TIMES("MPArch.RWH_DidUpdateBackingStore", delta);
1605 void RenderWidgetHostImpl::OnQueueSyntheticGesture(
1606 const SyntheticGesturePacket& gesture_packet) {
1607 // Only allow untrustworthy gestures if explicitly enabled.
1608 if (!base::CommandLine::ForCurrentProcess()->HasSwitch(
1609 cc::switches::kEnableGpuBenchmarking)) {
1610 bad_message::ReceivedBadMessage(GetProcess(),
1611 bad_message::RWH_SYNTHETIC_GESTURE);
1612 return;
1615 QueueSyntheticGesture(
1616 SyntheticGesture::Create(*gesture_packet.gesture_params()),
1617 base::Bind(&RenderWidgetHostImpl::OnSyntheticGestureCompleted,
1618 weak_factory_.GetWeakPtr()));
1621 void RenderWidgetHostImpl::OnFocus() {
1622 // Only RenderViewHost can deal with that message.
1623 bad_message::ReceivedBadMessage(GetProcess(), bad_message::RWH_FOCUS);
1626 void RenderWidgetHostImpl::OnBlur() {
1627 // Only RenderViewHost can deal with that message.
1628 bad_message::ReceivedBadMessage(GetProcess(), bad_message::RWH_BLUR);
1631 void RenderWidgetHostImpl::OnSetCursor(const WebCursor& cursor) {
1632 SetCursor(cursor);
1635 void RenderWidgetHostImpl::SetTouchEventEmulationEnabled(
1636 bool enabled, ui::GestureProviderConfigType config_type) {
1637 if (enabled) {
1638 if (!touch_emulator_) {
1639 touch_emulator_.reset(new TouchEmulator(
1640 this, view_ ? content::GetScaleFactorForView(view_) : 1.0f));
1642 touch_emulator_->Enable(config_type);
1643 } else {
1644 if (touch_emulator_)
1645 touch_emulator_->Disable();
1649 void RenderWidgetHostImpl::OnTextInputStateChanged(
1650 const ViewHostMsg_TextInputState_Params& params) {
1651 if (view_)
1652 view_->TextInputStateChanged(params);
1655 void RenderWidgetHostImpl::OnImeCompositionRangeChanged(
1656 const gfx::Range& range,
1657 const std::vector<gfx::Rect>& character_bounds) {
1658 if (view_)
1659 view_->ImeCompositionRangeChanged(range, character_bounds);
1662 void RenderWidgetHostImpl::OnImeCancelComposition() {
1663 if (view_)
1664 view_->ImeCancelComposition();
1667 void RenderWidgetHostImpl::OnLockMouse(bool user_gesture,
1668 bool last_unlocked_by_target,
1669 bool privileged) {
1671 if (pending_mouse_lock_request_) {
1672 Send(new ViewMsg_LockMouse_ACK(routing_id_, false));
1673 return;
1674 } else if (IsMouseLocked()) {
1675 Send(new ViewMsg_LockMouse_ACK(routing_id_, true));
1676 return;
1679 pending_mouse_lock_request_ = true;
1680 if (privileged && allow_privileged_mouse_lock_) {
1681 // Directly approve to lock the mouse.
1682 GotResponseToLockMouseRequest(true);
1683 } else {
1684 RequestToLockMouse(user_gesture, last_unlocked_by_target);
1688 void RenderWidgetHostImpl::OnUnlockMouse() {
1689 RejectMouseLockOrUnlockIfNecessary();
1692 void RenderWidgetHostImpl::OnShowDisambiguationPopup(
1693 const gfx::Rect& rect_pixels,
1694 const gfx::Size& size,
1695 const cc::SharedBitmapId& id) {
1696 DCHECK(!rect_pixels.IsEmpty());
1697 DCHECK(!size.IsEmpty());
1699 scoped_ptr<cc::SharedBitmap> bitmap =
1700 HostSharedBitmapManager::current()->GetSharedBitmapFromId(size, id);
1701 if (!bitmap) {
1702 bad_message::ReceivedBadMessage(GetProcess(),
1703 bad_message::RWH_SHARED_BITMAP);
1704 return;
1707 DCHECK(bitmap->pixels());
1709 SkImageInfo info = SkImageInfo::MakeN32Premul(size.width(), size.height());
1710 SkBitmap zoomed_bitmap;
1711 zoomed_bitmap.installPixels(info, bitmap->pixels(), info.minRowBytes());
1713 // Note that |rect| is in coordinates of pixels relative to the window origin.
1714 // Aura-based systems will want to convert this to DIPs.
1715 if (view_)
1716 view_->ShowDisambiguationPopup(rect_pixels, zoomed_bitmap);
1718 // It is assumed that the disambiguation popup will make a copy of the
1719 // provided zoomed image, so we delete this one.
1720 zoomed_bitmap.setPixels(0);
1721 Send(new ViewMsg_ReleaseDisambiguationPopupBitmap(GetRoutingID(), id));
1724 #if defined(OS_WIN)
1725 void RenderWidgetHostImpl::OnWindowlessPluginDummyWindowCreated(
1726 gfx::NativeViewId dummy_activation_window) {
1727 HWND hwnd = reinterpret_cast<HWND>(dummy_activation_window);
1729 // This may happen as a result of a race condition when the plugin is going
1730 // away.
1731 wchar_t window_title[MAX_PATH + 1] = {0};
1732 if (!IsWindow(hwnd) ||
1733 !GetWindowText(hwnd, window_title, arraysize(window_title)) ||
1734 lstrcmpiW(window_title, kDummyActivationWindowName) != 0) {
1735 return;
1738 #if defined(USE_AURA)
1739 SetParent(hwnd,
1740 reinterpret_cast<HWND>(view_->GetParentForWindowlessPlugin()));
1741 #else
1742 SetParent(hwnd, reinterpret_cast<HWND>(GetNativeViewId()));
1743 #endif
1744 dummy_windows_for_activation_.push_back(hwnd);
1747 void RenderWidgetHostImpl::OnWindowlessPluginDummyWindowDestroyed(
1748 gfx::NativeViewId dummy_activation_window) {
1749 HWND hwnd = reinterpret_cast<HWND>(dummy_activation_window);
1750 std::list<HWND>::iterator i = dummy_windows_for_activation_.begin();
1751 for (; i != dummy_windows_for_activation_.end(); ++i) {
1752 if ((*i) == hwnd) {
1753 dummy_windows_for_activation_.erase(i);
1754 return;
1757 NOTREACHED() << "Unknown dummy window";
1759 #endif
1761 void RenderWidgetHostImpl::SetIgnoreInputEvents(bool ignore_input_events) {
1762 ignore_input_events_ = ignore_input_events;
1765 bool RenderWidgetHostImpl::KeyPressListenersHandleEvent(
1766 const NativeWebKeyboardEvent& event) {
1767 if (event.skip_in_browser || event.type != WebKeyboardEvent::RawKeyDown)
1768 return false;
1770 for (size_t i = 0; i < key_press_event_callbacks_.size(); i++) {
1771 size_t original_size = key_press_event_callbacks_.size();
1772 if (key_press_event_callbacks_[i].Run(event))
1773 return true;
1775 // Check whether the callback that just ran removed itself, in which case
1776 // the iterator needs to be decremented to properly account for the removal.
1777 size_t current_size = key_press_event_callbacks_.size();
1778 if (current_size != original_size) {
1779 DCHECK_EQ(original_size - 1, current_size);
1780 --i;
1784 return false;
1787 InputEventAckState RenderWidgetHostImpl::FilterInputEvent(
1788 const blink::WebInputEvent& event, const ui::LatencyInfo& latency_info) {
1789 // Don't ignore touch cancel events, since they may be sent while input
1790 // events are being ignored in order to keep the renderer from getting
1791 // confused about how many touches are active.
1792 if (IgnoreInputEvents() && event.type != WebInputEvent::TouchCancel)
1793 return INPUT_EVENT_ACK_STATE_NO_CONSUMER_EXISTS;
1795 if (!process_->HasConnection())
1796 return INPUT_EVENT_ACK_STATE_UNKNOWN;
1798 if (event.type == WebInputEvent::MouseDown ||
1799 event.type == WebInputEvent::GestureTapDown) {
1800 OnUserGesture();
1803 return view_ ? view_->FilterInputEvent(event)
1804 : INPUT_EVENT_ACK_STATE_NOT_CONSUMED;
1807 void RenderWidgetHostImpl::IncrementInFlightEventCount() {
1808 increment_in_flight_event_count();
1809 if (!is_hidden_)
1810 StartHangMonitorTimeout(hung_renderer_delay_);
1813 void RenderWidgetHostImpl::DecrementInFlightEventCount() {
1814 if (decrement_in_flight_event_count() <= 0) {
1815 // Cancel pending hung renderer checks since the renderer is responsive.
1816 StopHangMonitorTimeout();
1817 } else {
1818 // The renderer is responsive, but there are in-flight events to wait for.
1819 if (!is_hidden_)
1820 RestartHangMonitorTimeout();
1824 void RenderWidgetHostImpl::OnHasTouchEventHandlers(bool has_handlers) {
1825 has_touch_handler_ = has_handlers;
1828 void RenderWidgetHostImpl::DidFlush() {
1829 if (synthetic_gesture_controller_)
1830 synthetic_gesture_controller_->OnDidFlushInput();
1833 void RenderWidgetHostImpl::DidOverscroll(const DidOverscrollParams& params) {
1834 if (view_)
1835 view_->DidOverscroll(params);
1838 void RenderWidgetHostImpl::DidStopFlinging() {
1839 if (view_)
1840 view_->DidStopFlinging();
1843 void RenderWidgetHostImpl::OnKeyboardEventAck(
1844 const NativeWebKeyboardEventWithLatencyInfo& event,
1845 InputEventAckState ack_result) {
1846 latency_tracker_.OnInputEventAck(event.event, &event.latency);
1848 #if defined(OS_MACOSX)
1849 if (!is_hidden() && view_ && view_->PostProcessEventForPluginIme(event.event))
1850 return;
1851 #endif
1853 // We only send unprocessed key event upwards if we are not hidden,
1854 // because the user has moved away from us and no longer expect any effect
1855 // of this key event.
1856 const bool processed = (INPUT_EVENT_ACK_STATE_CONSUMED == ack_result);
1857 if (delegate_ && !processed && !is_hidden() && !event.event.skip_in_browser) {
1858 delegate_->HandleKeyboardEvent(event.event);
1860 // WARNING: This RenderWidgetHostImpl can be deallocated at this point
1861 // (i.e. in the case of Ctrl+W, where the call to
1862 // HandleKeyboardEvent destroys this RenderWidgetHostImpl).
1866 void RenderWidgetHostImpl::OnMouseEventAck(
1867 const MouseEventWithLatencyInfo& mouse_event,
1868 InputEventAckState ack_result) {
1869 latency_tracker_.OnInputEventAck(mouse_event.event, &mouse_event.latency);
1872 void RenderWidgetHostImpl::OnWheelEventAck(
1873 const MouseWheelEventWithLatencyInfo& wheel_event,
1874 InputEventAckState ack_result) {
1875 latency_tracker_.OnInputEventAck(wheel_event.event, &wheel_event.latency);
1877 if (!is_hidden() && view_) {
1878 if (ack_result != INPUT_EVENT_ACK_STATE_CONSUMED &&
1879 delegate_->HandleWheelEvent(wheel_event.event)) {
1880 ack_result = INPUT_EVENT_ACK_STATE_CONSUMED;
1882 view_->WheelEventAck(wheel_event.event, ack_result);
1886 void RenderWidgetHostImpl::OnGestureEventAck(
1887 const GestureEventWithLatencyInfo& event,
1888 InputEventAckState ack_result) {
1889 latency_tracker_.OnInputEventAck(event.event, &event.latency);
1891 if (view_)
1892 view_->GestureEventAck(event.event, ack_result);
1895 void RenderWidgetHostImpl::OnTouchEventAck(
1896 const TouchEventWithLatencyInfo& event,
1897 InputEventAckState ack_result) {
1898 latency_tracker_.OnInputEventAck(event.event, &event.latency);
1900 if (touch_emulator_ &&
1901 touch_emulator_->HandleTouchEventAck(event.event, ack_result)) {
1902 return;
1905 if (view_)
1906 view_->ProcessAckedTouchEvent(event, ack_result);
1909 void RenderWidgetHostImpl::OnUnexpectedEventAck(UnexpectedEventAckType type) {
1910 if (type == BAD_ACK_MESSAGE) {
1911 bad_message::ReceivedBadMessage(process_, bad_message::RWH_BAD_ACK_MESSAGE);
1912 } else if (type == UNEXPECTED_EVENT_TYPE) {
1913 suppress_next_char_events_ = false;
1917 void RenderWidgetHostImpl::OnSyntheticGestureCompleted(
1918 SyntheticGesture::Result result) {
1919 Send(new InputMsg_SyntheticGestureCompleted(GetRoutingID()));
1922 bool RenderWidgetHostImpl::IgnoreInputEvents() const {
1923 return ignore_input_events_ || process_->IgnoreInputEvents();
1926 void RenderWidgetHostImpl::StartUserGesture() {
1927 OnUserGesture();
1930 void RenderWidgetHostImpl::SetBackgroundOpaque(bool opaque) {
1931 Send(new ViewMsg_SetBackgroundOpaque(GetRoutingID(), opaque));
1934 void RenderWidgetHostImpl::SetEditCommandsForNextKeyEvent(
1935 const std::vector<EditCommand>& commands) {
1936 Send(new InputMsg_SetEditCommandsForNextKeyEvent(GetRoutingID(), commands));
1939 void RenderWidgetHostImpl::ExecuteEditCommand(const std::string& command,
1940 const std::string& value) {
1941 Send(new InputMsg_ExecuteEditCommand(GetRoutingID(), command, value));
1944 void RenderWidgetHostImpl::ScrollFocusedEditableNodeIntoRect(
1945 const gfx::Rect& rect) {
1946 Send(new InputMsg_ScrollFocusedEditableNodeIntoRect(GetRoutingID(), rect));
1949 void RenderWidgetHostImpl::MoveCaret(const gfx::Point& point) {
1950 Send(new InputMsg_MoveCaret(GetRoutingID(), point));
1953 bool RenderWidgetHostImpl::GotResponseToLockMouseRequest(bool allowed) {
1954 if (!allowed) {
1955 RejectMouseLockOrUnlockIfNecessary();
1956 return false;
1957 } else {
1958 if (!pending_mouse_lock_request_) {
1959 // This is possible, e.g., the plugin sends us an unlock request before
1960 // the user allows to lock to mouse.
1961 return false;
1964 pending_mouse_lock_request_ = false;
1965 if (!view_ || !view_->HasFocus()|| !view_->LockMouse()) {
1966 Send(new ViewMsg_LockMouse_ACK(routing_id_, false));
1967 return false;
1968 } else {
1969 Send(new ViewMsg_LockMouse_ACK(routing_id_, true));
1970 return true;
1975 // static
1976 void RenderWidgetHostImpl::SendSwapCompositorFrameAck(
1977 int32 route_id,
1978 uint32 output_surface_id,
1979 int renderer_host_id,
1980 const cc::CompositorFrameAck& ack) {
1981 RenderProcessHost* host = RenderProcessHost::FromID(renderer_host_id);
1982 if (!host)
1983 return;
1984 host->Send(new ViewMsg_SwapCompositorFrameAck(
1985 route_id, output_surface_id, ack));
1988 // static
1989 void RenderWidgetHostImpl::SendReclaimCompositorResources(
1990 int32 route_id,
1991 uint32 output_surface_id,
1992 int renderer_host_id,
1993 const cc::CompositorFrameAck& ack) {
1994 RenderProcessHost* host = RenderProcessHost::FromID(renderer_host_id);
1995 if (!host)
1996 return;
1997 host->Send(
1998 new ViewMsg_ReclaimCompositorResources(route_id, output_surface_id, ack));
2001 void RenderWidgetHostImpl::DelayedAutoResized() {
2002 gfx::Size new_size = new_auto_size_;
2003 // Clear the new_auto_size_ since the empty value is used as a flag to
2004 // indicate that no callback is in progress (i.e. without this line
2005 // DelayedAutoResized will not get called again).
2006 new_auto_size_.SetSize(0, 0);
2007 if (!auto_resize_enabled_)
2008 return;
2010 OnRenderAutoResized(new_size);
2013 void RenderWidgetHostImpl::DetachDelegate() {
2014 delegate_ = NULL;
2017 void RenderWidgetHostImpl::FrameSwapped(const ui::LatencyInfo& latency_info) {
2018 ui::LatencyInfo::LatencyComponent window_snapshot_component;
2019 if (latency_info.FindLatency(ui::WINDOW_SNAPSHOT_FRAME_NUMBER_COMPONENT,
2020 GetLatencyComponentId(),
2021 &window_snapshot_component)) {
2022 int sequence_number = static_cast<int>(
2023 window_snapshot_component.sequence_number);
2024 #if defined(OS_MACOSX)
2025 // On Mac, when using CoreAnmation, there is a delay between when content
2026 // is drawn to the screen, and when the snapshot will actually pick up
2027 // that content. Insert a manual delay of 1/6th of a second (to simulate
2028 // 10 frames at 60 fps) before actually taking the snapshot.
2029 base::MessageLoop::current()->PostDelayedTask(
2030 FROM_HERE,
2031 base::Bind(&RenderWidgetHostImpl::WindowSnapshotReachedScreen,
2032 weak_factory_.GetWeakPtr(),
2033 sequence_number),
2034 base::TimeDelta::FromSecondsD(1. / 6));
2035 #else
2036 WindowSnapshotReachedScreen(sequence_number);
2037 #endif
2040 latency_tracker_.OnFrameSwapped(latency_info);
2043 void RenderWidgetHostImpl::DidReceiveRendererFrame() {
2044 view_->DidReceiveRendererFrame();
2047 void RenderWidgetHostImpl::WindowSnapshotReachedScreen(int snapshot_id) {
2048 DCHECK(base::MessageLoopForUI::IsCurrent());
2050 gfx::Rect view_bounds = GetView()->GetViewBounds();
2051 gfx::Rect snapshot_bounds(view_bounds.size());
2053 std::vector<unsigned char> png;
2054 if (ui::GrabViewSnapshot(
2055 GetView()->GetNativeView(), &png, snapshot_bounds)) {
2056 OnSnapshotDataReceived(snapshot_id, &png.front(), png.size());
2057 return;
2060 ui::GrabViewSnapshotAsync(
2061 GetView()->GetNativeView(),
2062 snapshot_bounds,
2063 base::ThreadTaskRunnerHandle::Get(),
2064 base::Bind(&RenderWidgetHostImpl::OnSnapshotDataReceivedAsync,
2065 weak_factory_.GetWeakPtr(),
2066 snapshot_id));
2069 void RenderWidgetHostImpl::OnSnapshotDataReceived(int snapshot_id,
2070 const unsigned char* data,
2071 size_t size) {
2072 // Any pending snapshots with a lower ID than the one received are considered
2073 // to be implicitly complete, and returned the same snapshot data.
2074 PendingSnapshotMap::iterator it = pending_browser_snapshots_.begin();
2075 while(it != pending_browser_snapshots_.end()) {
2076 if (it->first <= snapshot_id) {
2077 it->second.Run(data, size);
2078 pending_browser_snapshots_.erase(it++);
2079 } else {
2080 ++it;
2085 void RenderWidgetHostImpl::OnSnapshotDataReceivedAsync(
2086 int snapshot_id,
2087 scoped_refptr<base::RefCountedBytes> png_data) {
2088 if (png_data.get())
2089 OnSnapshotDataReceived(snapshot_id, png_data->front(), png_data->size());
2090 else
2091 OnSnapshotDataReceived(snapshot_id, NULL, 0);
2094 // static
2095 void RenderWidgetHostImpl::CompositorFrameDrawn(
2096 const std::vector<ui::LatencyInfo>& latency_info) {
2097 for (size_t i = 0; i < latency_info.size(); i++) {
2098 std::set<RenderWidgetHostImpl*> rwhi_set;
2099 for (const auto& lc : latency_info[i].latency_components()) {
2100 if (lc.first.first == ui::INPUT_EVENT_LATENCY_BEGIN_RWH_COMPONENT ||
2101 lc.first.first == ui::WINDOW_SNAPSHOT_FRAME_NUMBER_COMPONENT ||
2102 lc.first.first == ui::TAB_SHOW_COMPONENT) {
2103 // Matches with GetLatencyComponentId
2104 int routing_id = lc.first.second & 0xffffffff;
2105 int process_id = (lc.first.second >> 32) & 0xffffffff;
2106 RenderWidgetHost* rwh =
2107 RenderWidgetHost::FromID(process_id, routing_id);
2108 if (!rwh) {
2109 continue;
2111 RenderWidgetHostImpl* rwhi = RenderWidgetHostImpl::From(rwh);
2112 if (rwhi_set.insert(rwhi).second)
2113 rwhi->FrameSwapped(latency_info[i]);
2119 BrowserAccessibilityManager*
2120 RenderWidgetHostImpl::GetRootBrowserAccessibilityManager() {
2121 return delegate_ ? delegate_->GetRootBrowserAccessibilityManager() : NULL;
2124 BrowserAccessibilityManager*
2125 RenderWidgetHostImpl::GetOrCreateRootBrowserAccessibilityManager() {
2126 return delegate_ ?
2127 delegate_->GetOrCreateRootBrowserAccessibilityManager() : NULL;
2130 #if defined(OS_WIN)
2131 gfx::NativeViewAccessible
2132 RenderWidgetHostImpl::GetParentNativeViewAccessible() {
2133 return delegate_ ? delegate_->GetParentNativeViewAccessible() : NULL;
2135 #endif
2137 } // namespace content