Clean up check for dependency_info.
[chromium-blink-merge.git] / content / browser / renderer_host / render_widget_host_impl.cc
bloba4b3eda71ad9ff4919d3ab0323a72b21cc5cc29e
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/common/content_constants_internal.h"
51 #include "content/common/cursors/webcursor.h"
52 #include "content/common/frame_messages.h"
53 #include "content/common/gpu/gpu_messages.h"
54 #include "content/common/host_shared_bitmap_manager.h"
55 #include "content/common/input_messages.h"
56 #include "content/common/view_messages.h"
57 #include "content/public/browser/native_web_keyboard_event.h"
58 #include "content/public/browser/notification_service.h"
59 #include "content/public/browser/notification_types.h"
60 #include "content/public/browser/render_widget_host_iterator.h"
61 #include "content/public/common/content_constants.h"
62 #include "content/public/common/content_switches.h"
63 #include "content/public/common/result_codes.h"
64 #include "content/public/common/web_preferences.h"
65 #include "gpu/GLES2/gl2extchromium.h"
66 #include "gpu/command_buffer/service/gpu_switches.h"
67 #include "skia/ext/image_operations.h"
68 #include "skia/ext/platform_canvas.h"
69 #include "third_party/WebKit/public/web/WebCompositionUnderline.h"
70 #include "ui/events/event.h"
71 #include "ui/events/keycodes/keyboard_codes.h"
72 #include "ui/gfx/geometry/size_conversions.h"
73 #include "ui/gfx/geometry/vector2d_conversions.h"
74 #include "ui/gfx/skbitmap_operations.h"
75 #include "ui/snapshot/snapshot.h"
77 #if defined(OS_WIN)
78 #include "content/common/plugin_constants_win.h"
79 #endif
81 #if defined(OS_MACOSX)
82 #include "content/browser/renderer_host/render_widget_resize_helper_mac.h"
83 #endif
85 using base::Time;
86 using base::TimeDelta;
87 using base::TimeTicks;
88 using blink::WebGestureEvent;
89 using blink::WebInputEvent;
90 using blink::WebKeyboardEvent;
91 using blink::WebMouseEvent;
92 using blink::WebMouseWheelEvent;
93 using blink::WebTextDirection;
95 namespace content {
96 namespace {
98 bool g_check_for_pending_resize_ack = true;
100 // <process id, routing id>
101 using RenderWidgetHostID = std::pair<int32_t, int32_t>;
102 using RoutingIDWidgetMap =
103 base::hash_map<RenderWidgetHostID, RenderWidgetHostImpl*>;
104 base::LazyInstance<RoutingIDWidgetMap> g_routing_id_widget_map =
105 LAZY_INSTANCE_INITIALIZER;
107 // Implements the RenderWidgetHostIterator interface. It keeps a list of
108 // RenderWidgetHosts, and makes sure it returns a live RenderWidgetHost at each
109 // iteration (or NULL if there isn't any left).
110 class RenderWidgetHostIteratorImpl : public RenderWidgetHostIterator {
111 public:
112 RenderWidgetHostIteratorImpl()
113 : current_index_(0) {
116 ~RenderWidgetHostIteratorImpl() override {}
118 void Add(RenderWidgetHost* host) {
119 hosts_.push_back(RenderWidgetHostID(host->GetProcess()->GetID(),
120 host->GetRoutingID()));
123 // RenderWidgetHostIterator:
124 RenderWidgetHost* GetNextHost() override {
125 RenderWidgetHost* host = NULL;
126 while (current_index_ < hosts_.size() && !host) {
127 RenderWidgetHostID id = hosts_[current_index_];
128 host = RenderWidgetHost::FromID(id.first, id.second);
129 ++current_index_;
131 return host;
134 private:
135 std::vector<RenderWidgetHostID> hosts_;
136 size_t current_index_;
138 DISALLOW_COPY_AND_ASSIGN(RenderWidgetHostIteratorImpl);
141 } // namespace
143 ///////////////////////////////////////////////////////////////////////////////
144 // RenderWidgetHostImpl
146 RenderWidgetHostImpl::RenderWidgetHostImpl(RenderWidgetHostDelegate* delegate,
147 RenderProcessHost* process,
148 int32_t routing_id,
149 int32_t surface_id,
150 bool hidden)
151 : view_(NULL),
152 hung_renderer_delay_(
153 base::TimeDelta::FromMilliseconds(kHungRendererDelayMs)),
154 new_content_rendering_delay_(
155 base::TimeDelta::FromMilliseconds(kNewContentRenderingDelayMs)),
156 renderer_initialized_(false),
157 delegate_(delegate),
158 process_(process),
159 routing_id_(routing_id),
160 surface_id_(surface_id),
161 is_loading_(false),
162 is_hidden_(hidden),
163 repaint_ack_pending_(false),
164 resize_ack_pending_(false),
165 color_profile_out_of_date_(false),
166 auto_resize_enabled_(false),
167 waiting_for_screen_rects_ack_(false),
168 needs_repainting_on_restore_(false),
169 is_unresponsive_(false),
170 in_flight_event_count_(0),
171 in_get_backing_store_(false),
172 ignore_input_events_(false),
173 text_direction_updated_(false),
174 text_direction_(blink::WebTextDirectionLeftToRight),
175 text_direction_canceled_(false),
176 suppress_next_char_events_(false),
177 pending_mouse_lock_request_(false),
178 allow_privileged_mouse_lock_(false),
179 has_touch_handler_(false),
180 next_browser_snapshot_id_(1),
181 owned_by_render_frame_host_(false),
182 is_focused_(false),
183 weak_factory_(this) {
184 CHECK(delegate_);
185 CHECK_NE(MSG_ROUTING_NONE, routing_id_);
186 DCHECK_EQ(surface_id_, GpuSurfaceTracker::Get()->LookupSurfaceForRenderer(
187 process_->GetID(), routing_id_));
189 std::pair<RoutingIDWidgetMap::iterator, bool> result =
190 g_routing_id_widget_map.Get().insert(std::make_pair(
191 RenderWidgetHostID(process->GetID(), routing_id_), this));
192 CHECK(result.second) << "Inserting a duplicate item!";
193 process_->AddRoute(routing_id_, this);
195 // If we're initially visible, tell the process host that we're alive.
196 // Otherwise we'll notify the process host when we are first shown.
197 if (!hidden)
198 process_->WidgetRestored();
200 latency_tracker_.Initialize(routing_id_, GetProcess()->GetID());
202 input_router_.reset(new InputRouterImpl(
203 process_, this, this, routing_id_, GetInputRouterConfigForPlatform()));
205 touch_emulator_.reset();
207 RenderViewHostImpl* rvh = static_cast<RenderViewHostImpl*>(
208 IsRenderView() ? RenderViewHost::From(this) : NULL);
209 if (BrowserPluginGuest::IsGuest(rvh) ||
210 !base::CommandLine::ForCurrentProcess()->HasSwitch(
211 switches::kDisableHangMonitor)) {
212 hang_monitor_timeout_.reset(new TimeoutMonitor(
213 base::Bind(&RenderWidgetHostImpl::RendererIsUnresponsive,
214 weak_factory_.GetWeakPtr())));
217 new_content_rendering_timeout_.reset(new TimeoutMonitor(
218 base::Bind(&RenderWidgetHostImpl::ClearDisplayedGraphics,
219 weak_factory_.GetWeakPtr())));
222 RenderWidgetHostImpl::~RenderWidgetHostImpl() {
223 if (view_weak_)
224 view_weak_->RenderWidgetHostGone();
225 SetView(NULL);
227 GpuSurfaceTracker::Get()->RemoveSurface(surface_id_);
228 surface_id_ = 0;
230 process_->RemoveRoute(routing_id_);
231 g_routing_id_widget_map.Get().erase(
232 RenderWidgetHostID(process_->GetID(), routing_id_));
234 if (delegate_)
235 delegate_->RenderWidgetDeleted(this);
238 // static
239 RenderWidgetHost* RenderWidgetHost::FromID(
240 int32_t process_id,
241 int32_t routing_id) {
242 return RenderWidgetHostImpl::FromID(process_id, routing_id);
245 // static
246 RenderWidgetHostImpl* RenderWidgetHostImpl::FromID(
247 int32_t process_id,
248 int32_t routing_id) {
249 DCHECK_CURRENTLY_ON(BrowserThread::UI);
250 RoutingIDWidgetMap* widgets = g_routing_id_widget_map.Pointer();
251 RoutingIDWidgetMap::iterator it = widgets->find(
252 RenderWidgetHostID(process_id, routing_id));
253 return it == widgets->end() ? NULL : it->second;
256 // static
257 scoped_ptr<RenderWidgetHostIterator> RenderWidgetHost::GetRenderWidgetHosts() {
258 RenderWidgetHostIteratorImpl* hosts = new RenderWidgetHostIteratorImpl();
259 RoutingIDWidgetMap* widgets = g_routing_id_widget_map.Pointer();
260 for (RoutingIDWidgetMap::const_iterator it = widgets->begin();
261 it != widgets->end();
262 ++it) {
263 RenderWidgetHost* widget = it->second;
265 if (!widget->IsRenderView()) {
266 hosts->Add(widget);
267 continue;
270 // Add only active RenderViewHosts.
271 RenderViewHost* rvh = RenderViewHost::From(widget);
272 if (static_cast<RenderViewHostImpl*>(rvh)->is_active())
273 hosts->Add(widget);
276 return scoped_ptr<RenderWidgetHostIterator>(hosts);
279 // static
280 scoped_ptr<RenderWidgetHostIterator>
281 RenderWidgetHostImpl::GetAllRenderWidgetHosts() {
282 RenderWidgetHostIteratorImpl* hosts = new RenderWidgetHostIteratorImpl();
283 RoutingIDWidgetMap* widgets = g_routing_id_widget_map.Pointer();
284 for (RoutingIDWidgetMap::const_iterator it = widgets->begin();
285 it != widgets->end();
286 ++it) {
287 hosts->Add(it->second);
290 return scoped_ptr<RenderWidgetHostIterator>(hosts);
293 // static
294 RenderWidgetHostImpl* RenderWidgetHostImpl::From(RenderWidgetHost* rwh) {
295 return rwh->AsRenderWidgetHostImpl();
298 void RenderWidgetHostImpl::SetView(RenderWidgetHostViewBase* view) {
299 if (view)
300 view_weak_ = view->GetWeakPtr();
301 else
302 view_weak_.reset();
303 view_ = view;
305 // If the renderer has not yet been initialized, then the surface ID
306 // namespace will be sent during initialization.
307 if (view_ && renderer_initialized_) {
308 Send(new ViewMsg_SetSurfaceIdNamespace(routing_id_,
309 view_->GetSurfaceIdNamespace()));
312 GpuSurfaceTracker::Get()->SetSurfaceHandle(
313 surface_id_, GetCompositingSurface());
315 synthetic_gesture_controller_.reset();
318 RenderProcessHost* RenderWidgetHostImpl::GetProcess() const {
319 return process_;
322 int RenderWidgetHostImpl::GetRoutingID() const {
323 return routing_id_;
326 RenderWidgetHostView* RenderWidgetHostImpl::GetView() const {
327 return view_;
330 RenderWidgetHostImpl* RenderWidgetHostImpl::AsRenderWidgetHostImpl() {
331 return this;
334 gfx::NativeViewId RenderWidgetHostImpl::GetNativeViewId() const {
335 if (view_)
336 return view_->GetNativeViewId();
337 return 0;
340 gfx::GLSurfaceHandle RenderWidgetHostImpl::GetCompositingSurface() {
341 if (view_)
342 return view_->GetCompositingSurface();
343 return gfx::GLSurfaceHandle();
346 void RenderWidgetHostImpl::ResetSizeAndRepaintPendingFlags() {
347 resize_ack_pending_ = false;
348 if (repaint_ack_pending_) {
349 TRACE_EVENT_ASYNC_END0(
350 "renderer_host", "RenderWidgetHostImpl::repaint_ack_pending_", this);
352 repaint_ack_pending_ = false;
353 if (old_resize_params_)
354 old_resize_params_->new_size = gfx::Size();
357 void RenderWidgetHostImpl::SendScreenRects() {
358 if (!renderer_initialized_ || waiting_for_screen_rects_ack_)
359 return;
361 if (is_hidden_) {
362 // On GTK, this comes in for backgrounded tabs. Ignore, to match what
363 // happens on Win & Mac, and when the view is shown it'll call this again.
364 return;
367 if (!view_)
368 return;
370 last_view_screen_rect_ = view_->GetViewBounds();
371 last_window_screen_rect_ = view_->GetBoundsInRootWindow();
372 Send(new ViewMsg_UpdateScreenRects(
373 GetRoutingID(), last_view_screen_rect_, last_window_screen_rect_));
374 if (delegate_)
375 delegate_->DidSendScreenRects(this);
376 waiting_for_screen_rects_ack_ = true;
379 void RenderWidgetHostImpl::SuppressNextCharEvents() {
380 suppress_next_char_events_ = true;
383 void RenderWidgetHostImpl::FlushInput() {
384 input_router_->RequestNotificationWhenFlushed();
385 if (synthetic_gesture_controller_)
386 synthetic_gesture_controller_->Flush(base::TimeTicks::Now());
389 void RenderWidgetHostImpl::SetNeedsFlush() {
390 if (view_)
391 view_->OnSetNeedsFlushInput();
394 void RenderWidgetHostImpl::Init() {
395 DCHECK(process_->HasConnection());
397 renderer_initialized_ = true;
399 GpuSurfaceTracker::Get()->SetSurfaceHandle(
400 surface_id_, GetCompositingSurface());
402 // Send the ack along with the information on placement.
403 Send(new ViewMsg_CreatingNew_ACK(routing_id_));
404 GetProcess()->ResumeRequestsForView(routing_id_);
406 // If the RWHV has not yet been set, the surface ID namespace will get
407 // passed down by the call to SetView().
408 if (view_) {
409 Send(new ViewMsg_SetSurfaceIdNamespace(routing_id_,
410 view_->GetSurfaceIdNamespace()));
413 WasResized();
416 void RenderWidgetHostImpl::InitForFrame() {
417 DCHECK(process_->HasConnection());
418 renderer_initialized_ = true;
421 void RenderWidgetHostImpl::Shutdown() {
422 RejectMouseLockOrUnlockIfNecessary();
424 if (process_->HasConnection()) {
425 // Tell the renderer object to close.
426 bool rv = Send(new ViewMsg_Close(routing_id_));
427 DCHECK(rv);
430 Destroy();
433 bool RenderWidgetHostImpl::IsLoading() const {
434 return is_loading_;
437 bool RenderWidgetHostImpl::IsRenderView() const {
438 return false;
441 bool RenderWidgetHostImpl::OnMessageReceived(const IPC::Message &msg) {
442 bool handled = true;
443 IPC_BEGIN_MESSAGE_MAP(RenderWidgetHostImpl, msg)
444 IPC_MESSAGE_HANDLER(FrameHostMsg_RenderProcessGone, OnRenderProcessGone)
445 IPC_MESSAGE_HANDLER(InputHostMsg_QueueSyntheticGesture,
446 OnQueueSyntheticGesture)
447 IPC_MESSAGE_HANDLER(InputHostMsg_ImeCancelComposition,
448 OnImeCancelComposition)
449 IPC_MESSAGE_HANDLER(ViewHostMsg_RenderViewReady, OnRenderViewReady)
450 IPC_MESSAGE_HANDLER(ViewHostMsg_Close, OnClose)
451 IPC_MESSAGE_HANDLER(ViewHostMsg_UpdateScreenRects_ACK,
452 OnUpdateScreenRectsAck)
453 IPC_MESSAGE_HANDLER(ViewHostMsg_RequestMove, OnRequestMove)
454 IPC_MESSAGE_HANDLER(ViewHostMsg_SetTooltipText, OnSetTooltipText)
455 IPC_MESSAGE_HANDLER_GENERIC(ViewHostMsg_SwapCompositorFrame,
456 OnSwapCompositorFrame(msg))
457 IPC_MESSAGE_HANDLER(ViewHostMsg_UpdateRect, OnUpdateRect)
458 IPC_MESSAGE_HANDLER(ViewHostMsg_Focus, OnFocus)
459 IPC_MESSAGE_HANDLER(ViewHostMsg_Blur, OnBlur)
460 IPC_MESSAGE_HANDLER(ViewHostMsg_SetCursor, OnSetCursor)
461 IPC_MESSAGE_HANDLER(ViewHostMsg_TextInputStateChanged,
462 OnTextInputStateChanged)
463 IPC_MESSAGE_HANDLER(ViewHostMsg_LockMouse, OnLockMouse)
464 IPC_MESSAGE_HANDLER(ViewHostMsg_UnlockMouse, OnUnlockMouse)
465 IPC_MESSAGE_HANDLER(ViewHostMsg_ShowDisambiguationPopup,
466 OnShowDisambiguationPopup)
467 IPC_MESSAGE_HANDLER(ViewHostMsg_SelectionChanged, OnSelectionChanged)
468 IPC_MESSAGE_HANDLER(ViewHostMsg_SelectionBoundsChanged,
469 OnSelectionBoundsChanged)
470 #if defined(OS_WIN)
471 IPC_MESSAGE_HANDLER(ViewHostMsg_WindowlessPluginDummyWindowCreated,
472 OnWindowlessPluginDummyWindowCreated)
473 IPC_MESSAGE_HANDLER(ViewHostMsg_WindowlessPluginDummyWindowDestroyed,
474 OnWindowlessPluginDummyWindowDestroyed)
475 #endif
476 IPC_MESSAGE_HANDLER(InputHostMsg_ImeCompositionRangeChanged,
477 OnImeCompositionRangeChanged)
478 IPC_MESSAGE_UNHANDLED(handled = false)
479 IPC_END_MESSAGE_MAP()
481 if (!handled && input_router_ && input_router_->OnMessageReceived(msg))
482 return true;
484 if (!handled && view_ && view_->OnMessageReceived(msg))
485 return true;
487 return handled;
490 bool RenderWidgetHostImpl::Send(IPC::Message* msg) {
491 if (IPC_MESSAGE_ID_CLASS(msg->type()) == InputMsgStart)
492 return input_router_->SendInput(make_scoped_ptr(msg));
494 return process_->Send(msg);
497 void RenderWidgetHostImpl::SetIsLoading(bool is_loading) {
498 is_loading_ = is_loading;
499 if (!view_)
500 return;
501 view_->SetIsLoading(is_loading);
504 void RenderWidgetHostImpl::WasHidden() {
505 if (is_hidden_)
506 return;
508 TRACE_EVENT0("renderer_host", "RenderWidgetHostImpl::WasHidden");
509 is_hidden_ = true;
511 // Don't bother reporting hung state when we aren't active.
512 StopHangMonitorTimeout();
514 // If we have a renderer, then inform it that we are being hidden so it can
515 // reduce its resource utilization.
516 Send(new ViewMsg_WasHidden(routing_id_));
518 // Tell the RenderProcessHost we were hidden.
519 process_->WidgetHidden();
521 bool is_visible = false;
522 NotificationService::current()->Notify(
523 NOTIFICATION_RENDER_WIDGET_VISIBILITY_CHANGED,
524 Source<RenderWidgetHost>(this),
525 Details<bool>(&is_visible));
528 void RenderWidgetHostImpl::WasShown(const ui::LatencyInfo& latency_info) {
529 if (!is_hidden_)
530 return;
532 TRACE_EVENT0("renderer_host", "RenderWidgetHostImpl::WasShown");
533 is_hidden_ = false;
535 SendScreenRects();
537 // When hidden, timeout monitoring for input events is disabled. Restore it
538 // now to ensure consistent hang detection.
539 if (in_flight_event_count_)
540 RestartHangMonitorTimeout();
542 // Always repaint on restore.
543 bool needs_repainting = true;
544 needs_repainting_on_restore_ = false;
545 Send(new ViewMsg_WasShown(routing_id_, needs_repainting, latency_info));
547 process_->WidgetRestored();
549 bool is_visible = true;
550 NotificationService::current()->Notify(
551 NOTIFICATION_RENDER_WIDGET_VISIBILITY_CHANGED,
552 Source<RenderWidgetHost>(this),
553 Details<bool>(&is_visible));
555 // It's possible for our size to be out of sync with the renderer. The
556 // following is one case that leads to this:
557 // 1. WasResized -> Send ViewMsg_Resize to render
558 // 2. WasResized -> do nothing as resize_ack_pending_ is true
559 // 3. WasHidden
560 // 4. OnUpdateRect from (1) processed. Does NOT invoke WasResized as view
561 // is hidden. Now renderer/browser out of sync with what they think size
562 // is.
563 // By invoking WasResized the renderer is updated as necessary. WasResized
564 // does nothing if the sizes are already in sync.
566 // TODO: ideally ViewMsg_WasShown would take a size. This way, the renderer
567 // could handle both the restore and resize at once. This isn't that big a
568 // deal as RenderWidget::WasShown delays updating, so that the resize from
569 // WasResized is usually processed before the renderer is painted.
570 WasResized();
573 bool RenderWidgetHostImpl::GetResizeParams(
574 ViewMsg_Resize_Params* resize_params) {
575 *resize_params = ViewMsg_Resize_Params();
577 GetWebScreenInfo(&resize_params->screen_info);
578 resize_params->resizer_rect = GetRootWindowResizerRect();
580 if (view_) {
581 resize_params->new_size = view_->GetRequestedRendererSize();
582 resize_params->physical_backing_size = view_->GetPhysicalBackingSize();
583 resize_params->top_controls_height = view_->GetTopControlsHeight();
584 resize_params->top_controls_shrink_blink_size =
585 view_->DoTopControlsShrinkBlinkSize();
586 resize_params->visible_viewport_size = view_->GetVisibleViewportSize();
587 resize_params->is_fullscreen_granted = IsFullscreenGranted();
588 resize_params->display_mode = GetDisplayMode();
591 const bool size_changed =
592 !old_resize_params_ ||
593 old_resize_params_->new_size != resize_params->new_size ||
594 (old_resize_params_->physical_backing_size.IsEmpty() &&
595 !resize_params->physical_backing_size.IsEmpty());
596 bool dirty = size_changed ||
597 old_resize_params_->screen_info != resize_params->screen_info ||
598 old_resize_params_->physical_backing_size !=
599 resize_params->physical_backing_size ||
600 old_resize_params_->is_fullscreen_granted !=
601 resize_params->is_fullscreen_granted ||
602 old_resize_params_->display_mode != resize_params->display_mode ||
603 old_resize_params_->top_controls_height !=
604 resize_params->top_controls_height ||
605 old_resize_params_->top_controls_shrink_blink_size !=
606 resize_params->top_controls_shrink_blink_size ||
607 old_resize_params_->visible_viewport_size !=
608 resize_params->visible_viewport_size;
610 // We don't expect to receive an ACK when the requested size or the physical
611 // backing size is empty, or when the main viewport size didn't change.
612 resize_params->needs_resize_ack =
613 g_check_for_pending_resize_ack && !resize_params->new_size.IsEmpty() &&
614 !resize_params->physical_backing_size.IsEmpty() && size_changed;
616 return dirty;
619 void RenderWidgetHostImpl::SetInitialRenderSizeParams(
620 const ViewMsg_Resize_Params& resize_params) {
621 resize_ack_pending_ = resize_params.needs_resize_ack;
623 old_resize_params_ =
624 make_scoped_ptr(new ViewMsg_Resize_Params(resize_params));
627 void RenderWidgetHostImpl::WasResized() {
628 // Skip if the |delegate_| has already been detached because
629 // it's web contents is being deleted.
630 if (resize_ack_pending_ || !process_->HasConnection() || !view_ ||
631 !renderer_initialized_ || auto_resize_enabled_ || !delegate_) {
632 if (resize_ack_pending_ && color_profile_out_of_date_)
633 DispatchColorProfile();
634 return;
637 scoped_ptr<ViewMsg_Resize_Params> params(new ViewMsg_Resize_Params);
638 if (color_profile_out_of_date_)
639 DispatchColorProfile();
640 if (!GetResizeParams(params.get()))
641 return;
643 bool width_changed =
644 !old_resize_params_ ||
645 old_resize_params_->new_size.width() != params->new_size.width();
646 if (Send(new ViewMsg_Resize(routing_id_, *params))) {
647 resize_ack_pending_ = params->needs_resize_ack;
648 old_resize_params_.swap(params);
651 if (delegate_)
652 delegate_->RenderWidgetWasResized(this, width_changed);
655 void RenderWidgetHostImpl::DispatchColorProfile() {
656 #if defined(OS_WIN) || defined(OS_MACOSX) || defined(OS_LINUX)
657 static bool image_profiles = base::CommandLine::ForCurrentProcess()->
658 HasSwitch(switches::kEnableImageColorProfiles);
659 if (!image_profiles)
660 return;
661 #if defined(OS_WIN)
662 // Windows will read disk to get the color profile data if needed, so
663 // dispatch the SendColorProfile() work off the UI thread.
664 BrowserThread::PostBlockingPoolTask(
665 FROM_HERE,
666 base::Bind(&RenderWidgetHostImpl::SendColorProfile,
667 weak_factory_.GetWeakPtr()));
668 #elif !defined(OS_CHROMEOS) && !defined(OS_IOS) && !defined(OS_ANDROID)
669 // Only support desktop Mac and Linux at this time.
670 SendColorProfile();
671 #endif
672 #endif
675 void RenderWidgetHostImpl::SendColorProfile() {
676 if (!view_ || !delegate_)
677 return;
678 DCHECK(!view_->GetRequestedRendererSize().IsEmpty());
679 #if defined(OS_WIN)
680 DCHECK(!BrowserThread::CurrentlyOn(BrowserThread::UI));
681 DCHECK(!BrowserThread::CurrentlyOn(BrowserThread::IO));
682 #endif
683 std::vector<char> color_profile;
684 if (!GetScreenColorProfile(&color_profile))
685 return;
686 if (!renderer_initialized_ || !process_->HasConnection())
687 return;
688 if (!Send(new ViewMsg_ColorProfile(routing_id_, color_profile)))
689 return;
690 color_profile_out_of_date_ = false;
693 void RenderWidgetHostImpl::ResizeRectChanged(const gfx::Rect& new_rect) {
694 Send(new ViewMsg_ChangeResizeRect(routing_id_, new_rect));
697 void RenderWidgetHostImpl::GotFocus() {
698 Focus();
699 if (delegate_)
700 delegate_->RenderWidgetGotFocus(this);
703 void RenderWidgetHostImpl::Focus() {
704 is_focused_ = true;
706 Send(new InputMsg_SetFocus(routing_id_, true));
709 void RenderWidgetHostImpl::Blur() {
710 is_focused_ = false;
712 // If there is a pending mouse lock request, we don't want to reject it at
713 // this point. The user can switch focus back to this view and approve the
714 // request later.
715 if (IsMouseLocked())
716 view_->UnlockMouse();
718 if (touch_emulator_)
719 touch_emulator_->CancelTouch();
721 Send(new InputMsg_SetFocus(routing_id_, false));
724 void RenderWidgetHostImpl::LostCapture() {
725 if (touch_emulator_)
726 touch_emulator_->CancelTouch();
728 Send(new InputMsg_MouseCaptureLost(routing_id_));
731 void RenderWidgetHostImpl::SetActive(bool active) {
732 Send(new ViewMsg_SetActive(routing_id_, active));
735 void RenderWidgetHostImpl::LostMouseLock() {
736 Send(new ViewMsg_MouseLockLost(routing_id_));
739 void RenderWidgetHostImpl::ViewDestroyed() {
740 RejectMouseLockOrUnlockIfNecessary();
742 // TODO(evanm): tracking this may no longer be necessary;
743 // eliminate this function if so.
744 SetView(NULL);
747 void RenderWidgetHostImpl::CopyFromBackingStore(
748 const gfx::Rect& src_subrect,
749 const gfx::Size& accelerated_dst_size,
750 ReadbackRequestCallback& callback,
751 const SkColorType preferred_color_type) {
752 if (view_) {
753 TRACE_EVENT0("browser",
754 "RenderWidgetHostImpl::CopyFromBackingStore::FromCompositingSurface");
755 gfx::Rect accelerated_copy_rect = src_subrect.IsEmpty() ?
756 gfx::Rect(view_->GetViewBounds().size()) : src_subrect;
757 view_->CopyFromCompositingSurface(accelerated_copy_rect,
758 accelerated_dst_size, callback,
759 preferred_color_type);
760 return;
763 callback.Run(SkBitmap(), content::READBACK_FAILED);
766 bool RenderWidgetHostImpl::CanCopyFromBackingStore() {
767 if (view_)
768 return view_->IsSurfaceAvailableForCopy();
769 return false;
772 #if defined(OS_ANDROID)
773 void RenderWidgetHostImpl::LockBackingStore() {
774 if (view_)
775 view_->LockCompositingSurface();
778 void RenderWidgetHostImpl::UnlockBackingStore() {
779 if (view_)
780 view_->UnlockCompositingSurface();
782 #endif
784 #if defined(OS_MACOSX)
785 void RenderWidgetHostImpl::PauseForPendingResizeOrRepaints() {
786 TRACE_EVENT0("browser",
787 "RenderWidgetHostImpl::PauseForPendingResizeOrRepaints");
789 if (!CanPauseForPendingResizeOrRepaints())
790 return;
792 WaitForSurface();
795 bool RenderWidgetHostImpl::CanPauseForPendingResizeOrRepaints() {
796 // Do not pause if the view is hidden.
797 if (is_hidden())
798 return false;
800 // Do not pause if there is not a paint or resize already coming.
801 if (!repaint_ack_pending_ && !resize_ack_pending_)
802 return false;
804 return true;
807 void RenderWidgetHostImpl::WaitForSurface() {
808 // How long to (synchronously) wait for the renderer to respond with a
809 // new frame when our current frame doesn't exist or is the wrong size.
810 // This timeout impacts the "choppiness" of our window resize.
811 const int kPaintMsgTimeoutMS = 50;
813 if (!view_)
814 return;
816 // The view_size will be current_size_ for auto-sized views and otherwise the
817 // size of the view_. (For auto-sized views, current_size_ is updated during
818 // UpdateRect messages.)
819 gfx::Size view_size = current_size_;
820 if (!auto_resize_enabled_) {
821 // Get the desired size from the current view bounds.
822 gfx::Rect view_rect = view_->GetViewBounds();
823 if (view_rect.IsEmpty())
824 return;
825 view_size = view_rect.size();
828 TRACE_EVENT2("renderer_host",
829 "RenderWidgetHostImpl::WaitForSurface",
830 "width",
831 base::IntToString(view_size.width()),
832 "height",
833 base::IntToString(view_size.height()));
835 // We should not be asked to paint while we are hidden. If we are hidden,
836 // then it means that our consumer failed to call WasShown.
837 DCHECK(!is_hidden_) << "WaitForSurface called while hidden!";
839 // We should never be called recursively; this can theoretically lead to
840 // infinite recursion and almost certainly leads to lower performance.
841 DCHECK(!in_get_backing_store_) << "WaitForSurface called recursively!";
842 base::AutoReset<bool> auto_reset_in_get_backing_store(
843 &in_get_backing_store_, true);
845 // We might have a surface that we can use already.
846 if (view_->HasAcceleratedSurface(view_size))
847 return;
849 // Request that the renderer produce a frame of the right size, if it
850 // hasn't been requested already.
851 if (!repaint_ack_pending_ && !resize_ack_pending_) {
852 repaint_start_time_ = TimeTicks::Now();
853 repaint_ack_pending_ = true;
854 TRACE_EVENT_ASYNC_BEGIN0(
855 "renderer_host", "RenderWidgetHostImpl::repaint_ack_pending_", this);
856 Send(new ViewMsg_Repaint(routing_id_, view_size));
859 // Pump a nested message loop until we time out or get a frame of the right
860 // size.
861 TimeTicks start_time = TimeTicks::Now();
862 TimeDelta time_left = TimeDelta::FromMilliseconds(kPaintMsgTimeoutMS);
863 TimeTicks timeout_time = start_time + time_left;
864 while (1) {
865 TRACE_EVENT0("renderer_host", "WaitForSurface::WaitForSingleTaskToRun");
866 if (RenderWidgetResizeHelper::Get()->WaitForSingleTaskToRun(time_left)) {
867 // For auto-resized views, current_size_ determines the view_size and it
868 // may have changed during the handling of an UpdateRect message.
869 if (auto_resize_enabled_)
870 view_size = current_size_;
871 if (view_->HasAcceleratedSurface(view_size))
872 break;
874 time_left = timeout_time - TimeTicks::Now();
875 if (time_left <= TimeDelta::FromSeconds(0)) {
876 TRACE_EVENT0("renderer_host", "WaitForSurface::Timeout");
877 break;
881 UMA_HISTOGRAM_CUSTOM_TIMES("OSX.RendererHost.SurfaceWaitTime",
882 TimeTicks::Now() - start_time,
883 TimeDelta::FromMilliseconds(1),
884 TimeDelta::FromMilliseconds(200), 50);
886 #endif
888 bool RenderWidgetHostImpl::ScheduleComposite() {
889 if (is_hidden_ || current_size_.IsEmpty() || repaint_ack_pending_ ||
890 resize_ack_pending_) {
891 return false;
894 // Send out a request to the renderer to paint the view if required.
895 repaint_start_time_ = TimeTicks::Now();
896 repaint_ack_pending_ = true;
897 TRACE_EVENT_ASYNC_BEGIN0(
898 "renderer_host", "RenderWidgetHostImpl::repaint_ack_pending_", this);
899 Send(new ViewMsg_Repaint(routing_id_, current_size_));
900 return true;
903 void RenderWidgetHostImpl::StartHangMonitorTimeout(base::TimeDelta delay) {
904 if (hang_monitor_timeout_)
905 hang_monitor_timeout_->Start(delay);
908 void RenderWidgetHostImpl::RestartHangMonitorTimeout() {
909 if (hang_monitor_timeout_)
910 hang_monitor_timeout_->Restart(hung_renderer_delay_);
913 void RenderWidgetHostImpl::StopHangMonitorTimeout() {
914 if (hang_monitor_timeout_)
915 hang_monitor_timeout_->Stop();
916 RendererIsResponsive();
919 void RenderWidgetHostImpl::StartNewContentRenderingTimeout() {
920 if (new_content_rendering_timeout_)
921 new_content_rendering_timeout_->Start(new_content_rendering_delay_);
924 void RenderWidgetHostImpl::StopNewContentRenderingTimeout() {
925 if (new_content_rendering_timeout_)
926 new_content_rendering_timeout_->Stop();
929 void RenderWidgetHostImpl::ForwardMouseEvent(const WebMouseEvent& mouse_event) {
930 ForwardMouseEventWithLatencyInfo(mouse_event, ui::LatencyInfo());
933 void RenderWidgetHostImpl::ForwardMouseEventWithLatencyInfo(
934 const blink::WebMouseEvent& mouse_event,
935 const ui::LatencyInfo& ui_latency) {
936 TRACE_EVENT2("input", "RenderWidgetHostImpl::ForwardMouseEvent",
937 "x", mouse_event.x, "y", mouse_event.y);
939 for (size_t i = 0; i < mouse_event_callbacks_.size(); ++i) {
940 if (mouse_event_callbacks_[i].Run(mouse_event))
941 return;
944 if (IgnoreInputEvents())
945 return;
947 if (touch_emulator_ && touch_emulator_->HandleMouseEvent(mouse_event))
948 return;
950 MouseEventWithLatencyInfo mouse_with_latency(mouse_event, ui_latency);
951 latency_tracker_.OnInputEvent(mouse_event, &mouse_with_latency.latency);
952 input_router_->SendMouseEvent(mouse_with_latency);
954 // Pass mouse state to gpu service if the subscribe uniform
955 // extension is enabled.
956 if (process_->SubscribeUniformEnabled()) {
957 gpu::ValueState state;
958 state.int_value[0] = mouse_event.x;
959 state.int_value[1] = mouse_event.y;
960 // TODO(orglofch) Separate the mapping of pending value states to the
961 // Gpu Service to be per RWH not per process
962 process_->SendUpdateValueState(GL_MOUSE_POSITION_CHROMIUM, state);
966 void RenderWidgetHostImpl::ForwardWheelEvent(
967 const WebMouseWheelEvent& wheel_event) {
968 ForwardWheelEventWithLatencyInfo(wheel_event, ui::LatencyInfo());
971 void RenderWidgetHostImpl::ForwardWheelEventWithLatencyInfo(
972 const blink::WebMouseWheelEvent& wheel_event,
973 const ui::LatencyInfo& ui_latency) {
974 TRACE_EVENT2("input", "RenderWidgetHostImpl::ForwardWheelEvent",
975 "dx", wheel_event.deltaX, "dy", wheel_event.deltaY);
977 if (IgnoreInputEvents())
978 return;
980 if (touch_emulator_ && touch_emulator_->HandleMouseWheelEvent(wheel_event))
981 return;
983 MouseWheelEventWithLatencyInfo wheel_with_latency(wheel_event, ui_latency);
984 latency_tracker_.OnInputEvent(wheel_event, &wheel_with_latency.latency);
985 input_router_->SendWheelEvent(wheel_with_latency);
988 void RenderWidgetHostImpl::ForwardGestureEvent(
989 const blink::WebGestureEvent& gesture_event) {
990 ForwardGestureEventWithLatencyInfo(gesture_event, ui::LatencyInfo());
993 void RenderWidgetHostImpl::ForwardGestureEventWithLatencyInfo(
994 const blink::WebGestureEvent& gesture_event,
995 const ui::LatencyInfo& ui_latency) {
996 TRACE_EVENT0("input", "RenderWidgetHostImpl::ForwardGestureEvent");
997 // Early out if necessary, prior to performing latency logic.
998 if (IgnoreInputEvents())
999 return;
1001 if (delegate_->PreHandleGestureEvent(gesture_event))
1002 return;
1004 GestureEventWithLatencyInfo gesture_with_latency(gesture_event, ui_latency);
1005 latency_tracker_.OnInputEvent(gesture_event, &gesture_with_latency.latency);
1006 input_router_->SendGestureEvent(gesture_with_latency);
1009 void RenderWidgetHostImpl::ForwardEmulatedTouchEvent(
1010 const blink::WebTouchEvent& touch_event) {
1011 TRACE_EVENT0("input", "RenderWidgetHostImpl::ForwardEmulatedTouchEvent");
1013 TouchEventWithLatencyInfo touch_with_latency(touch_event);
1014 latency_tracker_.OnInputEvent(touch_event, &touch_with_latency.latency);
1015 input_router_->SendTouchEvent(touch_with_latency);
1018 void RenderWidgetHostImpl::ForwardTouchEventWithLatencyInfo(
1019 const blink::WebTouchEvent& touch_event,
1020 const ui::LatencyInfo& ui_latency) {
1021 TRACE_EVENT0("input", "RenderWidgetHostImpl::ForwardTouchEvent");
1023 // Always forward TouchEvents for touch stream consistency. They will be
1024 // ignored if appropriate in FilterInputEvent().
1026 TouchEventWithLatencyInfo touch_with_latency(touch_event, ui_latency);
1027 if (touch_emulator_ &&
1028 touch_emulator_->HandleTouchEvent(touch_with_latency.event)) {
1029 if (view_) {
1030 view_->ProcessAckedTouchEvent(
1031 touch_with_latency, INPUT_EVENT_ACK_STATE_CONSUMED);
1033 return;
1036 latency_tracker_.OnInputEvent(touch_event, &touch_with_latency.latency);
1037 input_router_->SendTouchEvent(touch_with_latency);
1040 void RenderWidgetHostImpl::ForwardKeyboardEvent(
1041 const NativeWebKeyboardEvent& key_event) {
1042 TRACE_EVENT0("input", "RenderWidgetHostImpl::ForwardKeyboardEvent");
1043 if (IgnoreInputEvents())
1044 return;
1046 if (!process_->HasConnection())
1047 return;
1049 // First, let keypress listeners take a shot at handling the event. If a
1050 // listener handles the event, it should not be propagated to the renderer.
1051 if (KeyPressListenersHandleEvent(key_event)) {
1052 // Some keypresses that are accepted by the listener might have follow up
1053 // char events, which should be ignored.
1054 if (key_event.type == WebKeyboardEvent::RawKeyDown)
1055 suppress_next_char_events_ = true;
1056 return;
1059 if (key_event.type == WebKeyboardEvent::Char &&
1060 (key_event.windowsKeyCode == ui::VKEY_RETURN ||
1061 key_event.windowsKeyCode == ui::VKEY_SPACE)) {
1062 OnUserGesture();
1065 // Double check the type to make sure caller hasn't sent us nonsense that
1066 // will mess up our key queue.
1067 if (!WebInputEvent::isKeyboardEventType(key_event.type))
1068 return;
1070 if (suppress_next_char_events_) {
1071 // If preceding RawKeyDown event was handled by the browser, then we need
1072 // suppress all Char events generated by it. Please note that, one
1073 // RawKeyDown event may generate multiple Char events, so we can't reset
1074 // |suppress_next_char_events_| until we get a KeyUp or a RawKeyDown.
1075 if (key_event.type == WebKeyboardEvent::Char)
1076 return;
1077 // We get a KeyUp or a RawKeyDown event.
1078 suppress_next_char_events_ = false;
1081 bool is_shortcut = false;
1083 // Only pre-handle the key event if it's not handled by the input method.
1084 if (delegate_ && !key_event.skip_in_browser) {
1085 // We need to set |suppress_next_char_events_| to true if
1086 // PreHandleKeyboardEvent() returns true, but |this| may already be
1087 // destroyed at that time. So set |suppress_next_char_events_| true here,
1088 // then revert it afterwards when necessary.
1089 if (key_event.type == WebKeyboardEvent::RawKeyDown)
1090 suppress_next_char_events_ = true;
1092 // Tab switching/closing accelerators aren't sent to the renderer to avoid
1093 // a hung/malicious renderer from interfering.
1094 if (delegate_->PreHandleKeyboardEvent(key_event, &is_shortcut))
1095 return;
1097 if (key_event.type == WebKeyboardEvent::RawKeyDown)
1098 suppress_next_char_events_ = false;
1101 if (touch_emulator_ && touch_emulator_->HandleKeyboardEvent(key_event))
1102 return;
1104 NativeWebKeyboardEventWithLatencyInfo key_event_with_latency(key_event);
1105 latency_tracker_.OnInputEvent(key_event, &key_event_with_latency.latency);
1106 input_router_->SendKeyboardEvent(key_event_with_latency, is_shortcut);
1109 void RenderWidgetHostImpl::QueueSyntheticGesture(
1110 scoped_ptr<SyntheticGesture> synthetic_gesture,
1111 const base::Callback<void(SyntheticGesture::Result)>& on_complete) {
1112 if (!synthetic_gesture_controller_ && view_) {
1113 synthetic_gesture_controller_.reset(
1114 new SyntheticGestureController(
1115 view_->CreateSyntheticGestureTarget().Pass()));
1117 if (synthetic_gesture_controller_) {
1118 synthetic_gesture_controller_->QueueSyntheticGesture(
1119 synthetic_gesture.Pass(), on_complete);
1123 void RenderWidgetHostImpl::SetCursor(const WebCursor& cursor) {
1124 if (!view_)
1125 return;
1126 view_->UpdateCursor(cursor);
1129 void RenderWidgetHostImpl::ShowContextMenuAtPoint(const gfx::Point& point) {
1130 Send(new ViewMsg_ShowContextMenu(
1131 GetRoutingID(), ui::MENU_SOURCE_MOUSE, point));
1134 void RenderWidgetHostImpl::SendCursorVisibilityState(bool is_visible) {
1135 Send(new InputMsg_CursorVisibilityChange(GetRoutingID(), is_visible));
1138 int64_t RenderWidgetHostImpl::GetLatencyComponentId() const {
1139 return latency_tracker_.latency_component_id();
1142 // static
1143 void RenderWidgetHostImpl::DisableResizeAckCheckForTesting() {
1144 g_check_for_pending_resize_ack = false;
1147 void RenderWidgetHostImpl::AddKeyPressEventCallback(
1148 const KeyPressEventCallback& callback) {
1149 key_press_event_callbacks_.push_back(callback);
1152 void RenderWidgetHostImpl::RemoveKeyPressEventCallback(
1153 const KeyPressEventCallback& callback) {
1154 for (size_t i = 0; i < key_press_event_callbacks_.size(); ++i) {
1155 if (key_press_event_callbacks_[i].Equals(callback)) {
1156 key_press_event_callbacks_.erase(
1157 key_press_event_callbacks_.begin() + i);
1158 return;
1163 void RenderWidgetHostImpl::AddMouseEventCallback(
1164 const MouseEventCallback& callback) {
1165 mouse_event_callbacks_.push_back(callback);
1168 void RenderWidgetHostImpl::RemoveMouseEventCallback(
1169 const MouseEventCallback& callback) {
1170 for (size_t i = 0; i < mouse_event_callbacks_.size(); ++i) {
1171 if (mouse_event_callbacks_[i].Equals(callback)) {
1172 mouse_event_callbacks_.erase(mouse_event_callbacks_.begin() + i);
1173 return;
1178 void RenderWidgetHostImpl::GetWebScreenInfo(blink::WebScreenInfo* result) {
1179 TRACE_EVENT0("renderer_host", "RenderWidgetHostImpl::GetWebScreenInfo");
1180 if (view_)
1181 view_->GetScreenInfo(result);
1182 else
1183 RenderWidgetHostViewBase::GetDefaultScreenInfo(result);
1184 // TODO(sievers): find a way to make this done another way so the method
1185 // can be const.
1186 latency_tracker_.set_device_scale_factor(result->deviceScaleFactor);
1189 bool RenderWidgetHostImpl::GetScreenColorProfile(
1190 std::vector<char>* color_profile) {
1191 DCHECK(color_profile->empty());
1192 if (view_)
1193 return view_->GetScreenColorProfile(color_profile);
1194 return false;
1197 void RenderWidgetHostImpl::NotifyScreenInfoChanged() {
1198 color_profile_out_of_date_ = true;
1200 if (delegate_)
1201 delegate_->ScreenInfoChanged();
1203 // The resize message (which may not happen immediately) will carry with it
1204 // the screen info as well as the new size (if the screen has changed scale
1205 // factor).
1206 WasResized();
1209 void RenderWidgetHostImpl::GetSnapshotFromBrowser(
1210 const GetSnapshotFromBrowserCallback& callback) {
1211 int id = next_browser_snapshot_id_++;
1212 pending_browser_snapshots_.insert(std::make_pair(id, callback));
1213 Send(new ViewMsg_ForceRedraw(GetRoutingID(), id));
1216 const NativeWebKeyboardEvent*
1217 RenderWidgetHostImpl::GetLastKeyboardEvent() const {
1218 return input_router_->GetLastKeyboardEvent();
1221 void RenderWidgetHostImpl::OnSelectionChanged(const base::string16& text,
1222 size_t offset,
1223 const gfx::Range& range) {
1224 if (view_)
1225 view_->SelectionChanged(text, offset, range);
1228 void RenderWidgetHostImpl::OnSelectionBoundsChanged(
1229 const ViewHostMsg_SelectionBounds_Params& params) {
1230 if (view_) {
1231 view_->SelectionBoundsChanged(params);
1235 void RenderWidgetHostImpl::UpdateVSyncParameters(base::TimeTicks timebase,
1236 base::TimeDelta interval) {
1237 Send(new ViewMsg_UpdateVSyncParameters(GetRoutingID(), timebase, interval));
1240 void RenderWidgetHostImpl::RendererExited(base::TerminationStatus status,
1241 int exit_code) {
1242 if (!renderer_initialized_)
1243 return;
1245 // Clearing this flag causes us to re-create the renderer when recovering
1246 // from a crashed renderer.
1247 renderer_initialized_ = false;
1249 waiting_for_screen_rects_ack_ = false;
1251 // Must reset these to ensure that keyboard events work with a new renderer.
1252 suppress_next_char_events_ = false;
1254 // Reset some fields in preparation for recovering from a crash.
1255 ResetSizeAndRepaintPendingFlags();
1256 current_size_.SetSize(0, 0);
1257 // After the renderer crashes, the view is destroyed and so the
1258 // RenderWidgetHost cannot track its visibility anymore. We assume such
1259 // RenderWidgetHost to be invisible for the sake of internal accounting - be
1260 // careful about changing this - see http://crbug.com/401859 and
1261 // http://crbug.com/522795.
1263 // We need to at least make sure that the RenderProcessHost is notified about
1264 // the |is_hidden_| change, so that the renderer will have correct visibility
1265 // set when respawned.
1266 if (!is_hidden_) {
1267 process_->WidgetHidden();
1268 is_hidden_ = true;
1271 // Reset this to ensure the hung renderer mechanism is working properly.
1272 in_flight_event_count_ = 0;
1273 StopHangMonitorTimeout();
1275 if (view_) {
1276 GpuSurfaceTracker::Get()->SetSurfaceHandle(surface_id_,
1277 gfx::GLSurfaceHandle());
1278 view_->RenderProcessGone(status, exit_code);
1279 view_ = nullptr; // The View should be deleted by RenderProcessGone.
1280 view_weak_.reset();
1283 // Reconstruct the input router to ensure that it has fresh state for a new
1284 // renderer. Otherwise it may be stuck waiting for the old renderer to ack an
1285 // event. (In particular, the above call to view_->RenderProcessGone will
1286 // destroy the aura window, which may dispatch a synthetic mouse move.)
1287 input_router_.reset(new InputRouterImpl(
1288 process_, this, this, routing_id_, GetInputRouterConfigForPlatform()));
1290 synthetic_gesture_controller_.reset();
1293 void RenderWidgetHostImpl::UpdateTextDirection(WebTextDirection direction) {
1294 text_direction_updated_ = true;
1295 text_direction_ = direction;
1298 void RenderWidgetHostImpl::CancelUpdateTextDirection() {
1299 if (text_direction_updated_)
1300 text_direction_canceled_ = true;
1303 void RenderWidgetHostImpl::NotifyTextDirection() {
1304 if (text_direction_updated_) {
1305 if (!text_direction_canceled_)
1306 Send(new ViewMsg_SetTextDirection(GetRoutingID(), text_direction_));
1307 text_direction_updated_ = false;
1308 text_direction_canceled_ = false;
1312 void RenderWidgetHostImpl::ImeSetComposition(
1313 const base::string16& text,
1314 const std::vector<blink::WebCompositionUnderline>& underlines,
1315 int selection_start,
1316 int selection_end) {
1317 Send(new InputMsg_ImeSetComposition(
1318 GetRoutingID(), text, underlines, selection_start, selection_end));
1321 void RenderWidgetHostImpl::ImeConfirmComposition(
1322 const base::string16& text,
1323 const gfx::Range& replacement_range,
1324 bool keep_selection) {
1325 Send(new InputMsg_ImeConfirmComposition(
1326 GetRoutingID(), text, replacement_range, keep_selection));
1329 void RenderWidgetHostImpl::ImeCancelComposition() {
1330 Send(new InputMsg_ImeSetComposition(GetRoutingID(), base::string16(),
1331 std::vector<blink::WebCompositionUnderline>(), 0, 0));
1334 gfx::Rect RenderWidgetHostImpl::GetRootWindowResizerRect() const {
1335 return gfx::Rect();
1338 void RenderWidgetHostImpl::RequestToLockMouse(bool user_gesture,
1339 bool last_unlocked_by_target) {
1340 // Directly reject to lock the mouse. Subclass can override this method to
1341 // decide whether to allow mouse lock or not.
1342 GotResponseToLockMouseRequest(false);
1345 void RenderWidgetHostImpl::RejectMouseLockOrUnlockIfNecessary() {
1346 DCHECK(!pending_mouse_lock_request_ || !IsMouseLocked());
1347 if (pending_mouse_lock_request_) {
1348 pending_mouse_lock_request_ = false;
1349 Send(new ViewMsg_LockMouse_ACK(routing_id_, false));
1350 } else if (IsMouseLocked()) {
1351 view_->UnlockMouse();
1355 bool RenderWidgetHostImpl::IsMouseLocked() const {
1356 return view_ ? view_->IsMouseLocked() : false;
1359 bool RenderWidgetHostImpl::IsFullscreenGranted() const {
1360 return false;
1363 blink::WebDisplayMode RenderWidgetHostImpl::GetDisplayMode() const {
1364 return blink::WebDisplayModeBrowser;
1367 void RenderWidgetHostImpl::SetAutoResize(bool enable,
1368 const gfx::Size& min_size,
1369 const gfx::Size& max_size) {
1370 auto_resize_enabled_ = enable;
1371 min_size_for_auto_resize_ = min_size;
1372 max_size_for_auto_resize_ = max_size;
1375 void RenderWidgetHostImpl::Destroy() {
1376 NotificationService::current()->Notify(
1377 NOTIFICATION_RENDER_WIDGET_HOST_DESTROYED,
1378 Source<RenderWidgetHost>(this),
1379 NotificationService::NoDetails());
1381 // Tell the view to die.
1382 // Note that in the process of the view shutting down, it can call a ton
1383 // of other messages on us. So if you do any other deinitialization here,
1384 // do it after this call to view_->Destroy().
1385 if (view_) {
1386 view_->Destroy();
1387 view_ = nullptr;
1390 delete this;
1393 void RenderWidgetHostImpl::RendererIsUnresponsive() {
1394 NotificationService::current()->Notify(
1395 NOTIFICATION_RENDER_WIDGET_HOST_HANG,
1396 Source<RenderWidgetHost>(this),
1397 NotificationService::NoDetails());
1398 is_unresponsive_ = true;
1399 NotifyRendererUnresponsive();
1402 void RenderWidgetHostImpl::RendererIsResponsive() {
1403 if (is_unresponsive_) {
1404 is_unresponsive_ = false;
1405 NotifyRendererResponsive();
1409 void RenderWidgetHostImpl::ClearDisplayedGraphics() {
1410 NotifyNewContentRenderingTimeoutForTesting();
1411 if (view_)
1412 view_->ClearCompositorFrame();
1415 void RenderWidgetHostImpl::OnRenderViewReady() {
1416 SendScreenRects();
1417 WasResized();
1420 void RenderWidgetHostImpl::OnRenderProcessGone(int status, int exit_code) {
1421 // RenderFrameHost owns a RenderWidgetHost when it needs one, in which case
1422 // it handles destruction.
1423 if (!owned_by_render_frame_host_) {
1424 // TODO(evanm): This synchronously ends up calling "delete this".
1425 // Is that really what we want in response to this message? I'm matching
1426 // previous behavior of the code here.
1427 Destroy();
1428 } else {
1429 RendererExited(static_cast<base::TerminationStatus>(status), exit_code);
1433 void RenderWidgetHostImpl::OnClose() {
1434 Shutdown();
1437 void RenderWidgetHostImpl::OnSetTooltipText(
1438 const base::string16& tooltip_text,
1439 WebTextDirection text_direction_hint) {
1440 // First, add directionality marks around tooltip text if necessary.
1441 // A naive solution would be to simply always wrap the text. However, on
1442 // windows, Unicode directional embedding characters can't be displayed on
1443 // systems that lack RTL fonts and are instead displayed as empty squares.
1445 // To get around this we only wrap the string when we deem it necessary i.e.
1446 // when the locale direction is different than the tooltip direction hint.
1448 // Currently, we use element's directionality as the tooltip direction hint.
1449 // An alternate solution would be to set the overall directionality based on
1450 // trying to detect the directionality from the tooltip text rather than the
1451 // element direction. One could argue that would be a preferable solution
1452 // but we use the current approach to match Fx & IE's behavior.
1453 base::string16 wrapped_tooltip_text = tooltip_text;
1454 if (!tooltip_text.empty()) {
1455 if (text_direction_hint == blink::WebTextDirectionLeftToRight) {
1456 // Force the tooltip to have LTR directionality.
1457 wrapped_tooltip_text =
1458 base::i18n::GetDisplayStringInLTRDirectionality(wrapped_tooltip_text);
1459 } else if (text_direction_hint == blink::WebTextDirectionRightToLeft &&
1460 !base::i18n::IsRTL()) {
1461 // Force the tooltip to have RTL directionality.
1462 base::i18n::WrapStringWithRTLFormatting(&wrapped_tooltip_text);
1465 if (GetView())
1466 view_->SetTooltipText(wrapped_tooltip_text);
1469 void RenderWidgetHostImpl::OnUpdateScreenRectsAck() {
1470 waiting_for_screen_rects_ack_ = false;
1471 if (!view_)
1472 return;
1474 if (view_->GetViewBounds() == last_view_screen_rect_ &&
1475 view_->GetBoundsInRootWindow() == last_window_screen_rect_) {
1476 return;
1479 SendScreenRects();
1482 void RenderWidgetHostImpl::OnRequestMove(const gfx::Rect& pos) {
1483 if (view_) {
1484 view_->SetBounds(pos);
1485 Send(new ViewMsg_Move_ACK(routing_id_));
1489 bool RenderWidgetHostImpl::OnSwapCompositorFrame(
1490 const IPC::Message& message) {
1491 // This trace event is used in
1492 // chrome/browser/extensions/api/cast_streaming/performance_test.cc
1493 TRACE_EVENT0("test_fps,benchmark", "OnSwapCompositorFrame");
1495 StopNewContentRenderingTimeout();
1497 ViewHostMsg_SwapCompositorFrame::Param param;
1498 if (!ViewHostMsg_SwapCompositorFrame::Read(&message, &param))
1499 return false;
1500 scoped_ptr<cc::CompositorFrame> frame(new cc::CompositorFrame);
1501 uint32_t output_surface_id = base::get<0>(param);
1502 base::get<1>(param).AssignTo(frame.get());
1503 std::vector<IPC::Message> messages_to_deliver_with_frame;
1504 messages_to_deliver_with_frame.swap(base::get<2>(param));
1506 if (!ui::LatencyInfo::Verify(frame->metadata.latency_info,
1507 "RenderWidgetHostImpl::OnSwapCompositorFrame")) {
1508 std::vector<ui::LatencyInfo>().swap(frame->metadata.latency_info);
1511 latency_tracker_.OnSwapCompositorFrame(&frame->metadata.latency_info);
1513 bool is_mobile_optimized = IsMobileOptimizedFrame(frame->metadata);
1514 input_router_->NotifySiteIsMobileOptimized(is_mobile_optimized);
1515 if (touch_emulator_)
1516 touch_emulator_->SetDoubleTapSupportForPageEnabled(!is_mobile_optimized);
1518 if (view_) {
1519 view_->OnSwapCompositorFrame(output_surface_id, frame.Pass());
1520 view_->DidReceiveRendererFrame();
1521 } else {
1522 cc::CompositorFrameAck ack;
1523 if (frame->gl_frame_data) {
1524 ack.gl_frame_data = frame->gl_frame_data.Pass();
1525 ack.gl_frame_data->sync_point = 0;
1526 } else if (frame->delegated_frame_data) {
1527 cc::TransferableResource::ReturnResources(
1528 frame->delegated_frame_data->resource_list,
1529 &ack.resources);
1531 SendSwapCompositorFrameAck(routing_id_, output_surface_id,
1532 process_->GetID(), ack);
1535 RenderProcessHost* rph = GetProcess();
1536 for (std::vector<IPC::Message>::const_iterator i =
1537 messages_to_deliver_with_frame.begin();
1538 i != messages_to_deliver_with_frame.end();
1539 ++i) {
1540 rph->OnMessageReceived(*i);
1541 if (i->dispatch_error())
1542 rph->OnBadMessageReceived(*i);
1544 messages_to_deliver_with_frame.clear();
1546 return true;
1549 void RenderWidgetHostImpl::OnUpdateRect(
1550 const ViewHostMsg_UpdateRect_Params& params) {
1551 TRACE_EVENT0("renderer_host", "RenderWidgetHostImpl::OnUpdateRect");
1552 TimeTicks paint_start = TimeTicks::Now();
1554 // Update our knowledge of the RenderWidget's size.
1555 current_size_ = params.view_size;
1557 bool is_resize_ack =
1558 ViewHostMsg_UpdateRect_Flags::is_resize_ack(params.flags);
1560 // resize_ack_pending_ needs to be cleared before we call DidPaintRect, since
1561 // that will end up reaching GetBackingStore.
1562 if (is_resize_ack) {
1563 DCHECK(!g_check_for_pending_resize_ack || resize_ack_pending_);
1564 resize_ack_pending_ = false;
1567 bool is_repaint_ack =
1568 ViewHostMsg_UpdateRect_Flags::is_repaint_ack(params.flags);
1569 if (is_repaint_ack) {
1570 DCHECK(repaint_ack_pending_);
1571 TRACE_EVENT_ASYNC_END0(
1572 "renderer_host", "RenderWidgetHostImpl::repaint_ack_pending_", this);
1573 repaint_ack_pending_ = false;
1574 TimeDelta delta = TimeTicks::Now() - repaint_start_time_;
1575 UMA_HISTOGRAM_TIMES("MPArch.RWH_RepaintDelta", delta);
1578 DCHECK(!params.view_size.IsEmpty());
1580 DidUpdateBackingStore(params, paint_start);
1582 if (auto_resize_enabled_) {
1583 bool post_callback = new_auto_size_.IsEmpty();
1584 new_auto_size_ = params.view_size;
1585 if (post_callback) {
1586 base::ThreadTaskRunnerHandle::Get()->PostTask(
1587 FROM_HERE, base::Bind(&RenderWidgetHostImpl::DelayedAutoResized,
1588 weak_factory_.GetWeakPtr()));
1592 // Log the time delta for processing a paint message. On platforms that don't
1593 // support asynchronous painting, this is equivalent to
1594 // MPArch.RWH_TotalPaintTime.
1595 TimeDelta delta = TimeTicks::Now() - paint_start;
1596 UMA_HISTOGRAM_TIMES("MPArch.RWH_OnMsgUpdateRect", delta);
1599 void RenderWidgetHostImpl::DidUpdateBackingStore(
1600 const ViewHostMsg_UpdateRect_Params& params,
1601 const TimeTicks& paint_start) {
1602 TRACE_EVENT0("renderer_host", "RenderWidgetHostImpl::DidUpdateBackingStore");
1603 TimeTicks update_start = TimeTicks::Now();
1605 // Move the plugins if the view hasn't already been destroyed. Plugin moves
1606 // will not be re-issued, so must move them now, regardless of whether we
1607 // paint or not. MovePluginWindows attempts to move the plugin windows and
1608 // in the process could dispatch other window messages which could cause the
1609 // view to be destroyed.
1610 if (view_)
1611 view_->MovePluginWindows(params.plugin_window_moves);
1613 NotificationService::current()->Notify(
1614 NOTIFICATION_RENDER_WIDGET_HOST_DID_UPDATE_BACKING_STORE,
1615 Source<RenderWidgetHost>(this),
1616 NotificationService::NoDetails());
1618 // We don't need to update the view if the view is hidden. We must do this
1619 // early return after the ACK is sent, however, or the renderer will not send
1620 // us more data.
1621 if (is_hidden_)
1622 return;
1624 // If we got a resize ack, then perhaps we have another resize to send?
1625 bool is_resize_ack =
1626 ViewHostMsg_UpdateRect_Flags::is_resize_ack(params.flags);
1627 if (is_resize_ack)
1628 WasResized();
1630 // Log the time delta for processing a paint message.
1631 TimeTicks now = TimeTicks::Now();
1632 TimeDelta delta = now - update_start;
1633 UMA_HISTOGRAM_TIMES("MPArch.RWH_DidUpdateBackingStore", delta);
1636 void RenderWidgetHostImpl::OnQueueSyntheticGesture(
1637 const SyntheticGesturePacket& gesture_packet) {
1638 // Only allow untrustworthy gestures if explicitly enabled.
1639 if (!base::CommandLine::ForCurrentProcess()->HasSwitch(
1640 cc::switches::kEnableGpuBenchmarking)) {
1641 bad_message::ReceivedBadMessage(GetProcess(),
1642 bad_message::RWH_SYNTHETIC_GESTURE);
1643 return;
1646 QueueSyntheticGesture(
1647 SyntheticGesture::Create(*gesture_packet.gesture_params()),
1648 base::Bind(&RenderWidgetHostImpl::OnSyntheticGestureCompleted,
1649 weak_factory_.GetWeakPtr()));
1652 void RenderWidgetHostImpl::OnFocus() {
1653 // Only RenderViewHost can deal with that message.
1654 bad_message::ReceivedBadMessage(GetProcess(), bad_message::RWH_FOCUS);
1657 void RenderWidgetHostImpl::OnBlur() {
1658 // Only RenderViewHost can deal with that message.
1659 bad_message::ReceivedBadMessage(GetProcess(), bad_message::RWH_BLUR);
1662 void RenderWidgetHostImpl::OnSetCursor(const WebCursor& cursor) {
1663 SetCursor(cursor);
1666 void RenderWidgetHostImpl::SetTouchEventEmulationEnabled(
1667 bool enabled, ui::GestureProviderConfigType config_type) {
1668 if (enabled) {
1669 if (!touch_emulator_) {
1670 touch_emulator_.reset(new TouchEmulator(
1671 this, view_ ? content::GetScaleFactorForView(view_) : 1.0f));
1673 touch_emulator_->Enable(config_type);
1674 } else {
1675 if (touch_emulator_)
1676 touch_emulator_->Disable();
1680 void RenderWidgetHostImpl::OnTextInputStateChanged(
1681 const ViewHostMsg_TextInputState_Params& params) {
1682 if (view_)
1683 view_->TextInputStateChanged(params);
1686 void RenderWidgetHostImpl::OnImeCompositionRangeChanged(
1687 const gfx::Range& range,
1688 const std::vector<gfx::Rect>& character_bounds) {
1689 if (view_)
1690 view_->ImeCompositionRangeChanged(range, character_bounds);
1693 void RenderWidgetHostImpl::OnImeCancelComposition() {
1694 if (view_)
1695 view_->ImeCancelComposition();
1698 void RenderWidgetHostImpl::OnLockMouse(bool user_gesture,
1699 bool last_unlocked_by_target,
1700 bool privileged) {
1701 if (pending_mouse_lock_request_) {
1702 Send(new ViewMsg_LockMouse_ACK(routing_id_, false));
1703 return;
1705 if (IsMouseLocked()) {
1706 Send(new ViewMsg_LockMouse_ACK(routing_id_, true));
1707 return;
1710 pending_mouse_lock_request_ = true;
1711 if (privileged && allow_privileged_mouse_lock_) {
1712 // Directly approve to lock the mouse.
1713 GotResponseToLockMouseRequest(true);
1714 } else {
1715 RequestToLockMouse(user_gesture, last_unlocked_by_target);
1719 void RenderWidgetHostImpl::OnUnlockMouse() {
1720 RejectMouseLockOrUnlockIfNecessary();
1723 void RenderWidgetHostImpl::OnShowDisambiguationPopup(
1724 const gfx::Rect& rect_pixels,
1725 const gfx::Size& size,
1726 const cc::SharedBitmapId& id) {
1727 DCHECK(!rect_pixels.IsEmpty());
1728 DCHECK(!size.IsEmpty());
1730 scoped_ptr<cc::SharedBitmap> bitmap =
1731 HostSharedBitmapManager::current()->GetSharedBitmapFromId(size, id);
1732 if (!bitmap) {
1733 bad_message::ReceivedBadMessage(GetProcess(),
1734 bad_message::RWH_SHARED_BITMAP);
1735 return;
1738 DCHECK(bitmap->pixels());
1740 SkImageInfo info = SkImageInfo::MakeN32Premul(size.width(), size.height());
1741 SkBitmap zoomed_bitmap;
1742 zoomed_bitmap.installPixels(info, bitmap->pixels(), info.minRowBytes());
1744 // Note that |rect| is in coordinates of pixels relative to the window origin.
1745 // Aura-based systems will want to convert this to DIPs.
1746 if (view_)
1747 view_->ShowDisambiguationPopup(rect_pixels, zoomed_bitmap);
1749 // It is assumed that the disambiguation popup will make a copy of the
1750 // provided zoomed image, so we delete this one.
1751 zoomed_bitmap.setPixels(0);
1752 Send(new ViewMsg_ReleaseDisambiguationPopupBitmap(GetRoutingID(), id));
1755 #if defined(OS_WIN)
1756 void RenderWidgetHostImpl::OnWindowlessPluginDummyWindowCreated(
1757 gfx::NativeViewId dummy_activation_window) {
1758 HWND hwnd = reinterpret_cast<HWND>(dummy_activation_window);
1760 // This may happen as a result of a race condition when the plugin is going
1761 // away.
1762 wchar_t window_title[MAX_PATH + 1] = {0};
1763 if (!IsWindow(hwnd) ||
1764 !GetWindowText(hwnd, window_title, arraysize(window_title)) ||
1765 lstrcmpiW(window_title, kDummyActivationWindowName) != 0) {
1766 return;
1769 #if defined(USE_AURA)
1770 SetParent(hwnd,
1771 reinterpret_cast<HWND>(view_->GetParentForWindowlessPlugin()));
1772 #else
1773 SetParent(hwnd, reinterpret_cast<HWND>(GetNativeViewId()));
1774 #endif
1775 dummy_windows_for_activation_.push_back(hwnd);
1778 void RenderWidgetHostImpl::OnWindowlessPluginDummyWindowDestroyed(
1779 gfx::NativeViewId dummy_activation_window) {
1780 HWND hwnd = reinterpret_cast<HWND>(dummy_activation_window);
1781 std::list<HWND>::iterator i = dummy_windows_for_activation_.begin();
1782 for (; i != dummy_windows_for_activation_.end(); ++i) {
1783 if ((*i) == hwnd) {
1784 dummy_windows_for_activation_.erase(i);
1785 return;
1788 NOTREACHED() << "Unknown dummy window";
1790 #endif
1792 void RenderWidgetHostImpl::SetIgnoreInputEvents(bool ignore_input_events) {
1793 ignore_input_events_ = ignore_input_events;
1796 bool RenderWidgetHostImpl::KeyPressListenersHandleEvent(
1797 const NativeWebKeyboardEvent& event) {
1798 if (event.skip_in_browser || event.type != WebKeyboardEvent::RawKeyDown)
1799 return false;
1801 for (size_t i = 0; i < key_press_event_callbacks_.size(); i++) {
1802 size_t original_size = key_press_event_callbacks_.size();
1803 if (key_press_event_callbacks_[i].Run(event))
1804 return true;
1806 // Check whether the callback that just ran removed itself, in which case
1807 // the iterator needs to be decremented to properly account for the removal.
1808 size_t current_size = key_press_event_callbacks_.size();
1809 if (current_size != original_size) {
1810 DCHECK_EQ(original_size - 1, current_size);
1811 --i;
1815 return false;
1818 InputEventAckState RenderWidgetHostImpl::FilterInputEvent(
1819 const blink::WebInputEvent& event, const ui::LatencyInfo& latency_info) {
1820 // Don't ignore touch cancel events, since they may be sent while input
1821 // events are being ignored in order to keep the renderer from getting
1822 // confused about how many touches are active.
1823 if (IgnoreInputEvents() && event.type != WebInputEvent::TouchCancel)
1824 return INPUT_EVENT_ACK_STATE_NO_CONSUMER_EXISTS;
1826 if (!process_->HasConnection())
1827 return INPUT_EVENT_ACK_STATE_UNKNOWN;
1829 if (event.type == WebInputEvent::MouseDown ||
1830 event.type == WebInputEvent::GestureTapDown) {
1831 OnUserGesture();
1834 return view_ ? view_->FilterInputEvent(event)
1835 : INPUT_EVENT_ACK_STATE_NOT_CONSUMED;
1838 void RenderWidgetHostImpl::IncrementInFlightEventCount() {
1839 increment_in_flight_event_count();
1840 if (!is_hidden_)
1841 StartHangMonitorTimeout(hung_renderer_delay_);
1844 void RenderWidgetHostImpl::DecrementInFlightEventCount() {
1845 if (decrement_in_flight_event_count() <= 0) {
1846 // Cancel pending hung renderer checks since the renderer is responsive.
1847 StopHangMonitorTimeout();
1848 } else {
1849 // The renderer is responsive, but there are in-flight events to wait for.
1850 if (!is_hidden_)
1851 RestartHangMonitorTimeout();
1855 void RenderWidgetHostImpl::OnHasTouchEventHandlers(bool has_handlers) {
1856 has_touch_handler_ = has_handlers;
1859 void RenderWidgetHostImpl::DidFlush() {
1860 if (synthetic_gesture_controller_)
1861 synthetic_gesture_controller_->OnDidFlushInput();
1864 void RenderWidgetHostImpl::DidOverscroll(const DidOverscrollParams& params) {
1865 if (view_)
1866 view_->DidOverscroll(params);
1869 void RenderWidgetHostImpl::DidStopFlinging() {
1870 if (view_)
1871 view_->DidStopFlinging();
1874 void RenderWidgetHostImpl::OnKeyboardEventAck(
1875 const NativeWebKeyboardEventWithLatencyInfo& event,
1876 InputEventAckState ack_result) {
1877 latency_tracker_.OnInputEventAck(event.event, &event.latency);
1879 #if defined(OS_MACOSX)
1880 if (!is_hidden() && view_ && view_->PostProcessEventForPluginIme(event.event))
1881 return;
1882 #endif
1884 // We only send unprocessed key event upwards if we are not hidden,
1885 // because the user has moved away from us and no longer expect any effect
1886 // of this key event.
1887 const bool processed = (INPUT_EVENT_ACK_STATE_CONSUMED == ack_result);
1888 if (delegate_ && !processed && !is_hidden() && !event.event.skip_in_browser) {
1889 delegate_->HandleKeyboardEvent(event.event);
1891 // WARNING: This RenderWidgetHostImpl can be deallocated at this point
1892 // (i.e. in the case of Ctrl+W, where the call to
1893 // HandleKeyboardEvent destroys this RenderWidgetHostImpl).
1897 void RenderWidgetHostImpl::OnMouseEventAck(
1898 const MouseEventWithLatencyInfo& mouse_event,
1899 InputEventAckState ack_result) {
1900 latency_tracker_.OnInputEventAck(mouse_event.event, &mouse_event.latency);
1903 void RenderWidgetHostImpl::OnWheelEventAck(
1904 const MouseWheelEventWithLatencyInfo& wheel_event,
1905 InputEventAckState ack_result) {
1906 latency_tracker_.OnInputEventAck(wheel_event.event, &wheel_event.latency);
1908 if (!is_hidden() && view_) {
1909 if (ack_result != INPUT_EVENT_ACK_STATE_CONSUMED &&
1910 delegate_->HandleWheelEvent(wheel_event.event)) {
1911 ack_result = INPUT_EVENT_ACK_STATE_CONSUMED;
1913 view_->WheelEventAck(wheel_event.event, ack_result);
1917 void RenderWidgetHostImpl::OnGestureEventAck(
1918 const GestureEventWithLatencyInfo& event,
1919 InputEventAckState ack_result) {
1920 latency_tracker_.OnInputEventAck(event.event, &event.latency);
1922 if (view_)
1923 view_->GestureEventAck(event.event, ack_result);
1926 void RenderWidgetHostImpl::OnTouchEventAck(
1927 const TouchEventWithLatencyInfo& event,
1928 InputEventAckState ack_result) {
1929 latency_tracker_.OnInputEventAck(event.event, &event.latency);
1931 if (touch_emulator_ &&
1932 touch_emulator_->HandleTouchEventAck(event.event, ack_result)) {
1933 return;
1936 if (view_)
1937 view_->ProcessAckedTouchEvent(event, ack_result);
1940 void RenderWidgetHostImpl::OnUnexpectedEventAck(UnexpectedEventAckType type) {
1941 if (type == BAD_ACK_MESSAGE) {
1942 bad_message::ReceivedBadMessage(process_, bad_message::RWH_BAD_ACK_MESSAGE);
1943 } else if (type == UNEXPECTED_EVENT_TYPE) {
1944 suppress_next_char_events_ = false;
1948 void RenderWidgetHostImpl::OnSyntheticGestureCompleted(
1949 SyntheticGesture::Result result) {
1950 Send(new InputMsg_SyntheticGestureCompleted(GetRoutingID()));
1953 bool RenderWidgetHostImpl::IgnoreInputEvents() const {
1954 return ignore_input_events_ || process_->IgnoreInputEvents();
1957 void RenderWidgetHostImpl::StartUserGesture() {
1958 OnUserGesture();
1961 void RenderWidgetHostImpl::SetBackgroundOpaque(bool opaque) {
1962 Send(new ViewMsg_SetBackgroundOpaque(GetRoutingID(), opaque));
1965 void RenderWidgetHostImpl::SetEditCommandsForNextKeyEvent(
1966 const std::vector<EditCommand>& commands) {
1967 Send(new InputMsg_SetEditCommandsForNextKeyEvent(GetRoutingID(), commands));
1970 void RenderWidgetHostImpl::ExecuteEditCommand(const std::string& command,
1971 const std::string& value) {
1972 Send(new InputMsg_ExecuteEditCommand(GetRoutingID(), command, value));
1975 void RenderWidgetHostImpl::ScrollFocusedEditableNodeIntoRect(
1976 const gfx::Rect& rect) {
1977 Send(new InputMsg_ScrollFocusedEditableNodeIntoRect(GetRoutingID(), rect));
1980 void RenderWidgetHostImpl::MoveCaret(const gfx::Point& point) {
1981 Send(new InputMsg_MoveCaret(GetRoutingID(), point));
1984 bool RenderWidgetHostImpl::GotResponseToLockMouseRequest(bool allowed) {
1985 if (!allowed) {
1986 RejectMouseLockOrUnlockIfNecessary();
1987 return false;
1990 if (!pending_mouse_lock_request_) {
1991 // This is possible, e.g., the plugin sends us an unlock request before
1992 // the user allows to lock to mouse.
1993 return false;
1996 pending_mouse_lock_request_ = false;
1997 if (!view_ || !view_->HasFocus()|| !view_->LockMouse()) {
1998 Send(new ViewMsg_LockMouse_ACK(routing_id_, false));
1999 return false;
2002 Send(new ViewMsg_LockMouse_ACK(routing_id_, true));
2003 return true;
2006 // static
2007 void RenderWidgetHostImpl::SendSwapCompositorFrameAck(
2008 int32_t route_id,
2009 uint32_t output_surface_id,
2010 int renderer_host_id,
2011 const cc::CompositorFrameAck& ack) {
2012 RenderProcessHost* host = RenderProcessHost::FromID(renderer_host_id);
2013 if (!host)
2014 return;
2015 host->Send(new ViewMsg_SwapCompositorFrameAck(
2016 route_id, output_surface_id, ack));
2019 // static
2020 void RenderWidgetHostImpl::SendReclaimCompositorResources(
2021 int32_t route_id,
2022 uint32_t output_surface_id,
2023 int renderer_host_id,
2024 const cc::CompositorFrameAck& ack) {
2025 RenderProcessHost* host = RenderProcessHost::FromID(renderer_host_id);
2026 if (!host)
2027 return;
2028 host->Send(
2029 new ViewMsg_ReclaimCompositorResources(route_id, output_surface_id, ack));
2032 void RenderWidgetHostImpl::DelayedAutoResized() {
2033 gfx::Size new_size = new_auto_size_;
2034 // Clear the new_auto_size_ since the empty value is used as a flag to
2035 // indicate that no callback is in progress (i.e. without this line
2036 // DelayedAutoResized will not get called again).
2037 new_auto_size_.SetSize(0, 0);
2038 if (!auto_resize_enabled_)
2039 return;
2041 OnRenderAutoResized(new_size);
2044 void RenderWidgetHostImpl::DetachDelegate() {
2045 delegate_ = NULL;
2048 void RenderWidgetHostImpl::FrameSwapped(const ui::LatencyInfo& latency_info) {
2049 ui::LatencyInfo::LatencyComponent window_snapshot_component;
2050 if (latency_info.FindLatency(ui::WINDOW_SNAPSHOT_FRAME_NUMBER_COMPONENT,
2051 GetLatencyComponentId(),
2052 &window_snapshot_component)) {
2053 int sequence_number = static_cast<int>(
2054 window_snapshot_component.sequence_number);
2055 #if defined(OS_MACOSX)
2056 // On Mac, when using CoreAnmation, there is a delay between when content
2057 // is drawn to the screen, and when the snapshot will actually pick up
2058 // that content. Insert a manual delay of 1/6th of a second (to simulate
2059 // 10 frames at 60 fps) before actually taking the snapshot.
2060 base::MessageLoop::current()->PostDelayedTask(
2061 FROM_HERE,
2062 base::Bind(&RenderWidgetHostImpl::WindowSnapshotReachedScreen,
2063 weak_factory_.GetWeakPtr(),
2064 sequence_number),
2065 base::TimeDelta::FromSecondsD(1. / 6));
2066 #else
2067 WindowSnapshotReachedScreen(sequence_number);
2068 #endif
2071 latency_tracker_.OnFrameSwapped(latency_info);
2074 void RenderWidgetHostImpl::DidReceiveRendererFrame() {
2075 view_->DidReceiveRendererFrame();
2078 void RenderWidgetHostImpl::WindowSnapshotReachedScreen(int snapshot_id) {
2079 DCHECK(base::MessageLoopForUI::IsCurrent());
2081 gfx::Rect view_bounds = GetView()->GetViewBounds();
2082 gfx::Rect snapshot_bounds(view_bounds.size());
2084 std::vector<unsigned char> png;
2085 if (ui::GrabViewSnapshot(
2086 GetView()->GetNativeView(), &png, snapshot_bounds)) {
2087 OnSnapshotDataReceived(snapshot_id, &png.front(), png.size());
2088 return;
2091 ui::GrabViewSnapshotAsync(
2092 GetView()->GetNativeView(),
2093 snapshot_bounds,
2094 base::ThreadTaskRunnerHandle::Get(),
2095 base::Bind(&RenderWidgetHostImpl::OnSnapshotDataReceivedAsync,
2096 weak_factory_.GetWeakPtr(),
2097 snapshot_id));
2100 void RenderWidgetHostImpl::OnSnapshotDataReceived(int snapshot_id,
2101 const unsigned char* data,
2102 size_t size) {
2103 // Any pending snapshots with a lower ID than the one received are considered
2104 // to be implicitly complete, and returned the same snapshot data.
2105 PendingSnapshotMap::iterator it = pending_browser_snapshots_.begin();
2106 while (it != pending_browser_snapshots_.end()) {
2107 if (it->first <= snapshot_id) {
2108 it->second.Run(data, size);
2109 pending_browser_snapshots_.erase(it++);
2110 } else {
2111 ++it;
2116 void RenderWidgetHostImpl::OnSnapshotDataReceivedAsync(
2117 int snapshot_id,
2118 scoped_refptr<base::RefCountedBytes> png_data) {
2119 if (png_data.get())
2120 OnSnapshotDataReceived(snapshot_id, png_data->front(), png_data->size());
2121 else
2122 OnSnapshotDataReceived(snapshot_id, NULL, 0);
2125 // static
2126 void RenderWidgetHostImpl::CompositorFrameDrawn(
2127 const std::vector<ui::LatencyInfo>& latency_info) {
2128 for (size_t i = 0; i < latency_info.size(); i++) {
2129 std::set<RenderWidgetHostImpl*> rwhi_set;
2130 for (const auto& lc : latency_info[i].latency_components()) {
2131 if (lc.first.first == ui::INPUT_EVENT_LATENCY_BEGIN_RWH_COMPONENT ||
2132 lc.first.first == ui::WINDOW_SNAPSHOT_FRAME_NUMBER_COMPONENT ||
2133 lc.first.first == ui::TAB_SHOW_COMPONENT) {
2134 // Matches with GetLatencyComponentId
2135 int routing_id = lc.first.second & 0xffffffff;
2136 int process_id = (lc.first.second >> 32) & 0xffffffff;
2137 RenderWidgetHost* rwh =
2138 RenderWidgetHost::FromID(process_id, routing_id);
2139 if (!rwh) {
2140 continue;
2142 RenderWidgetHostImpl* rwhi = RenderWidgetHostImpl::From(rwh);
2143 if (rwhi_set.insert(rwhi).second)
2144 rwhi->FrameSwapped(latency_info[i]);
2150 BrowserAccessibilityManager*
2151 RenderWidgetHostImpl::GetRootBrowserAccessibilityManager() {
2152 return delegate_ ? delegate_->GetRootBrowserAccessibilityManager() : NULL;
2155 BrowserAccessibilityManager*
2156 RenderWidgetHostImpl::GetOrCreateRootBrowserAccessibilityManager() {
2157 return delegate_ ?
2158 delegate_->GetOrCreateRootBrowserAccessibilityManager() : NULL;
2161 #if defined(OS_WIN)
2162 gfx::NativeViewAccessible
2163 RenderWidgetHostImpl::GetParentNativeViewAccessible() {
2164 return delegate_ ? delegate_->GetParentNativeViewAccessible() : NULL;
2166 #endif
2168 } // namespace content