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"
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/debug/trace_event.h"
16 #include "base/i18n/rtl.h"
17 #include "base/lazy_instance.h"
18 #include "base/message_loop/message_loop.h"
19 #include "base/metrics/field_trial.h"
20 #include "base/metrics/histogram.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 "cc/base/switches.h"
25 #include "cc/output/compositor_frame.h"
26 #include "cc/output/compositor_frame_ack.h"
27 #include "content/browser/accessibility/accessibility_mode_helper.h"
28 #include "content/browser/accessibility/browser_accessibility_state_impl.h"
29 #include "content/browser/browser_plugin/browser_plugin_guest.h"
30 #include "content/browser/gpu/compositor_util.h"
31 #include "content/browser/gpu/gpu_process_host.h"
32 #include "content/browser/gpu/gpu_process_host_ui_shim.h"
33 #include "content/browser/gpu/gpu_surface_tracker.h"
34 #include "content/browser/renderer_host/dip_util.h"
35 #include "content/browser/renderer_host/input/input_router_config_helper.h"
36 #include "content/browser/renderer_host/input/input_router_impl.h"
37 #include "content/browser/renderer_host/input/synthetic_gesture.h"
38 #include "content/browser/renderer_host/input/synthetic_gesture_controller.h"
39 #include "content/browser/renderer_host/input/synthetic_gesture_target.h"
40 #include "content/browser/renderer_host/input/timeout_monitor.h"
41 #include "content/browser/renderer_host/input/touch_emulator.h"
42 #include "content/browser/renderer_host/render_process_host_impl.h"
43 #include "content/browser/renderer_host/render_view_host_impl.h"
44 #include "content/browser/renderer_host/render_widget_helper.h"
45 #include "content/browser/renderer_host/render_widget_host_delegate.h"
46 #include "content/browser/renderer_host/render_widget_host_view_base.h"
47 #include "content/common/accessibility_messages.h"
48 #include "content/common/content_constants_internal.h"
49 #include "content/common/cursors/webcursor.h"
50 #include "content/common/gpu/gpu_messages.h"
51 #include "content/common/host_shared_bitmap_manager.h"
52 #include "content/common/input_messages.h"
53 #include "content/common/view_messages.h"
54 #include "content/public/browser/native_web_keyboard_event.h"
55 #include "content/public/browser/notification_service.h"
56 #include "content/public/browser/notification_types.h"
57 #include "content/public/browser/render_widget_host_iterator.h"
58 #include "content/public/browser/user_metrics.h"
59 #include "content/public/common/content_constants.h"
60 #include "content/public/common/content_switches.h"
61 #include "content/public/common/result_codes.h"
62 #include "skia/ext/image_operations.h"
63 #include "skia/ext/platform_canvas.h"
64 #include "third_party/WebKit/public/web/WebCompositionUnderline.h"
65 #include "ui/events/event.h"
66 #include "ui/events/keycodes/keyboard_codes.h"
67 #include "ui/gfx/size_conversions.h"
68 #include "ui/gfx/skbitmap_operations.h"
69 #include "ui/gfx/vector2d_conversions.h"
70 #include "ui/snapshot/snapshot.h"
71 #include "webkit/common/webpreferences.h"
74 #include "content/common/plugin_constants_win.h"
78 using base::TimeDelta;
79 using base::TimeTicks;
80 using blink::WebGestureEvent;
81 using blink::WebInputEvent;
82 using blink::WebKeyboardEvent;
83 using blink::WebMouseEvent;
84 using blink::WebMouseWheelEvent;
85 using blink::WebTextDirection;
90 bool g_check_for_pending_resize_ack = true;
92 // How long to (synchronously) wait for the renderer to respond with a
93 // PaintRect message, when our backing-store is invalid, before giving up and
94 // returning a null or incorrectly sized backing-store from GetBackingStore.
95 // This timeout impacts the "choppiness" of our window resize perf.
96 const int kPaintMsgTimeoutMS = 50;
98 typedef std::pair<int32, int32> RenderWidgetHostID;
99 typedef base::hash_map<RenderWidgetHostID, RenderWidgetHostImpl*>
101 base::LazyInstance<RoutingIDWidgetMap> g_routing_id_widget_map =
102 LAZY_INSTANCE_INITIALIZER;
104 int GetInputRouterViewFlagsFromCompositorFrameMetadata(
105 const cc::CompositorFrameMetadata metadata) {
106 int view_flags = InputRouter::VIEW_FLAGS_NONE;
108 if (metadata.min_page_scale_factor == metadata.max_page_scale_factor)
109 view_flags |= InputRouter::FIXED_PAGE_SCALE;
111 const float window_width_dip =
112 std::ceil(metadata.page_scale_factor * metadata.viewport_size.width());
113 const float content_width_css = metadata.root_layer_size.width();
114 if (content_width_css <= window_width_dip)
115 view_flags |= InputRouter::MOBILE_VIEWPORT;
120 // Implements the RenderWidgetHostIterator interface. It keeps a list of
121 // RenderWidgetHosts, and makes sure it returns a live RenderWidgetHost at each
122 // iteration (or NULL if there isn't any left).
123 class RenderWidgetHostIteratorImpl : public RenderWidgetHostIterator {
125 RenderWidgetHostIteratorImpl()
126 : current_index_(0) {
129 virtual ~RenderWidgetHostIteratorImpl() {
132 void Add(RenderWidgetHost* host) {
133 hosts_.push_back(RenderWidgetHostID(host->GetProcess()->GetID(),
134 host->GetRoutingID()));
137 // RenderWidgetHostIterator:
138 virtual RenderWidgetHost* GetNextHost() OVERRIDE {
139 RenderWidgetHost* host = NULL;
140 while (current_index_ < hosts_.size() && !host) {
141 RenderWidgetHostID id = hosts_[current_index_];
142 host = RenderWidgetHost::FromID(id.first, id.second);
149 std::vector<RenderWidgetHostID> hosts_;
150 size_t current_index_;
152 DISALLOW_COPY_AND_ASSIGN(RenderWidgetHostIteratorImpl);
157 ///////////////////////////////////////////////////////////////////////////////
158 // RenderWidgetHostImpl
160 RenderWidgetHostImpl::RenderWidgetHostImpl(RenderWidgetHostDelegate* delegate,
161 RenderProcessHost* process,
165 renderer_initialized_(false),
166 hung_renderer_delay_ms_(kHungRendererDelayMs),
169 routing_id_(routing_id),
173 is_fullscreen_(false),
174 repaint_ack_pending_(false),
175 resize_ack_pending_(false),
176 screen_info_out_of_date_(false),
177 overdraw_bottom_height_(0.f),
178 should_auto_resize_(false),
179 waiting_for_screen_rects_ack_(false),
180 accessibility_mode_(AccessibilityModeOff),
181 needs_repainting_on_restore_(false),
182 is_unresponsive_(false),
183 in_flight_event_count_(0),
184 in_get_backing_store_(false),
185 ignore_input_events_(false),
186 input_method_active_(false),
187 text_direction_updated_(false),
188 text_direction_(blink::WebTextDirectionLeftToRight),
189 text_direction_canceled_(false),
190 suppress_next_char_events_(false),
191 pending_mouse_lock_request_(false),
192 allow_privileged_mouse_lock_(false),
193 has_touch_handler_(false),
195 last_input_number_(static_cast<int64>(GetProcess()->GetID()) << 32) {
197 if (routing_id_ == MSG_ROUTING_NONE) {
198 routing_id_ = process_->GetNextRoutingID();
199 surface_id_ = GpuSurfaceTracker::Get()->AddSurfaceForRenderer(
203 // TODO(piman): This is a O(N) lookup, where we could forward the
204 // information from the RenderWidgetHelper. The problem is that doing so
205 // currently leaks outside of content all the way to chrome classes, and
206 // would be a layering violation. Since we don't expect more than a few
207 // hundreds of RWH, this seems acceptable. Revisit if performance become a
208 // problem, for example by tracking in the RenderWidgetHelper the routing id
209 // (and surface id) that have been created, but whose RWH haven't yet.
210 surface_id_ = GpuSurfaceTracker::Get()->LookupSurfaceForRenderer(
216 std::pair<RoutingIDWidgetMap::iterator, bool> result =
217 g_routing_id_widget_map.Get().insert(std::make_pair(
218 RenderWidgetHostID(process->GetID(), routing_id_), this));
219 CHECK(result.second) << "Inserting a duplicate item!";
220 process_->AddRoute(routing_id_, this);
222 // If we're initially visible, tell the process host that we're alive.
223 // Otherwise we'll notify the process host when we are first shown.
225 process_->WidgetRestored();
227 accessibility_mode_ =
228 BrowserAccessibilityStateImpl::GetInstance()->accessibility_mode();
230 input_router_.reset(new InputRouterImpl(
231 process_, this, this, routing_id_, GetInputRouterConfigForPlatform()));
233 touch_emulator_.reset();
235 RenderViewHostImpl* rvh = static_cast<RenderViewHostImpl*>(
236 IsRenderView() ? RenderViewHost::From(this) : NULL);
237 if (BrowserPluginGuest::IsGuest(rvh) ||
238 !CommandLine::ForCurrentProcess()->HasSwitch(
239 switches::kDisableHangMonitor)) {
240 hang_monitor_timeout_.reset(new TimeoutMonitor(
241 base::Bind(&RenderWidgetHostImpl::RendererIsUnresponsive,
242 weak_factory_.GetWeakPtr())));
246 RenderWidgetHostImpl::~RenderWidgetHostImpl() {
249 GpuSurfaceTracker::Get()->RemoveSurface(surface_id_);
252 process_->RemoveRoute(routing_id_);
253 g_routing_id_widget_map.Get().erase(
254 RenderWidgetHostID(process_->GetID(), routing_id_));
257 delegate_->RenderWidgetDeleted(this);
261 RenderWidgetHost* RenderWidgetHost::FromID(
264 return RenderWidgetHostImpl::FromID(process_id, routing_id);
268 RenderWidgetHostImpl* RenderWidgetHostImpl::FromID(
271 DCHECK_CURRENTLY_ON(BrowserThread::UI);
272 RoutingIDWidgetMap* widgets = g_routing_id_widget_map.Pointer();
273 RoutingIDWidgetMap::iterator it = widgets->find(
274 RenderWidgetHostID(process_id, routing_id));
275 return it == widgets->end() ? NULL : it->second;
279 scoped_ptr<RenderWidgetHostIterator> RenderWidgetHost::GetRenderWidgetHosts() {
280 RenderWidgetHostIteratorImpl* hosts = new RenderWidgetHostIteratorImpl();
281 RoutingIDWidgetMap* widgets = g_routing_id_widget_map.Pointer();
282 for (RoutingIDWidgetMap::const_iterator it = widgets->begin();
283 it != widgets->end();
285 RenderWidgetHost* widget = it->second;
287 if (!widget->IsRenderView()) {
292 // Add only active RenderViewHosts.
293 RenderViewHost* rvh = RenderViewHost::From(widget);
294 if (RenderViewHostImpl::IsRVHStateActive(
295 static_cast<RenderViewHostImpl*>(rvh)->rvh_state()))
299 return scoped_ptr<RenderWidgetHostIterator>(hosts);
303 scoped_ptr<RenderWidgetHostIterator>
304 RenderWidgetHostImpl::GetAllRenderWidgetHosts() {
305 RenderWidgetHostIteratorImpl* hosts = new RenderWidgetHostIteratorImpl();
306 RoutingIDWidgetMap* widgets = g_routing_id_widget_map.Pointer();
307 for (RoutingIDWidgetMap::const_iterator it = widgets->begin();
308 it != widgets->end();
310 hosts->Add(it->second);
313 return scoped_ptr<RenderWidgetHostIterator>(hosts);
317 RenderWidgetHostImpl* RenderWidgetHostImpl::From(RenderWidgetHost* rwh) {
318 return rwh->AsRenderWidgetHostImpl();
321 void RenderWidgetHostImpl::SetView(RenderWidgetHostViewBase* view) {
324 GpuSurfaceTracker::Get()->SetSurfaceHandle(
325 surface_id_, GetCompositingSurface());
327 synthetic_gesture_controller_.reset();
330 RenderProcessHost* RenderWidgetHostImpl::GetProcess() const {
334 int RenderWidgetHostImpl::GetRoutingID() const {
338 RenderWidgetHostView* RenderWidgetHostImpl::GetView() const {
342 RenderWidgetHostImpl* RenderWidgetHostImpl::AsRenderWidgetHostImpl() {
346 gfx::NativeViewId RenderWidgetHostImpl::GetNativeViewId() const {
348 return view_->GetNativeViewId();
352 gfx::GLSurfaceHandle RenderWidgetHostImpl::GetCompositingSurface() {
354 return view_->GetCompositingSurface();
355 return gfx::GLSurfaceHandle();
358 void RenderWidgetHostImpl::ResetSizeAndRepaintPendingFlags() {
359 resize_ack_pending_ = false;
360 if (repaint_ack_pending_) {
361 TRACE_EVENT_ASYNC_END0(
362 "renderer_host", "RenderWidgetHostImpl::repaint_ack_pending_", this);
364 repaint_ack_pending_ = false;
365 last_requested_size_.SetSize(0, 0);
368 void RenderWidgetHostImpl::SendScreenRects() {
369 if (!renderer_initialized_ || waiting_for_screen_rects_ack_)
373 // On GTK, this comes in for backgrounded tabs. Ignore, to match what
374 // happens on Win & Mac, and when the view is shown it'll call this again.
381 last_view_screen_rect_ = view_->GetViewBounds();
382 last_window_screen_rect_ = view_->GetBoundsInRootWindow();
383 Send(new ViewMsg_UpdateScreenRects(
384 GetRoutingID(), last_view_screen_rect_, last_window_screen_rect_));
386 delegate_->DidSendScreenRects(this);
387 waiting_for_screen_rects_ack_ = true;
390 void RenderWidgetHostImpl::SuppressNextCharEvents() {
391 suppress_next_char_events_ = true;
394 void RenderWidgetHostImpl::FlushInput() {
395 input_router_->Flush();
396 if (synthetic_gesture_controller_)
397 synthetic_gesture_controller_->Flush(base::TimeTicks::Now());
400 void RenderWidgetHostImpl::SetNeedsFlush() {
402 view_->OnSetNeedsFlushInput();
405 void RenderWidgetHostImpl::Init() {
406 DCHECK(process_->HasConnection());
408 renderer_initialized_ = true;
410 GpuSurfaceTracker::Get()->SetSurfaceHandle(
411 surface_id_, GetCompositingSurface());
413 // Send the ack along with the information on placement.
414 Send(new ViewMsg_CreatingNew_ACK(routing_id_));
415 GetProcess()->ResumeRequestsForView(routing_id_);
420 void RenderWidgetHostImpl::Shutdown() {
421 RejectMouseLockOrUnlockIfNecessary();
423 if (process_->HasConnection()) {
424 // Tell the renderer object to close.
425 bool rv = Send(new ViewMsg_Close(routing_id_));
432 bool RenderWidgetHostImpl::IsLoading() const {
436 bool RenderWidgetHostImpl::IsRenderView() const {
440 bool RenderWidgetHostImpl::OnMessageReceived(const IPC::Message &msg) {
442 IPC_BEGIN_MESSAGE_MAP(RenderWidgetHostImpl, msg)
443 IPC_MESSAGE_HANDLER(InputHostMsg_QueueSyntheticGesture,
444 OnQueueSyntheticGesture)
445 IPC_MESSAGE_HANDLER(ViewHostMsg_RenderViewReady, OnRenderViewReady)
446 IPC_MESSAGE_HANDLER(ViewHostMsg_RenderProcessGone, OnRenderProcessGone)
447 IPC_MESSAGE_HANDLER(ViewHostMsg_Close, OnClose)
448 IPC_MESSAGE_HANDLER(ViewHostMsg_UpdateScreenRects_ACK,
449 OnUpdateScreenRectsAck)
450 IPC_MESSAGE_HANDLER(ViewHostMsg_RequestMove, OnRequestMove)
451 IPC_MESSAGE_HANDLER(ViewHostMsg_SetTooltipText, OnSetTooltipText)
452 IPC_MESSAGE_HANDLER_GENERIC(ViewHostMsg_SwapCompositorFrame,
453 OnSwapCompositorFrame(msg))
454 IPC_MESSAGE_HANDLER(ViewHostMsg_DidStopFlinging, OnFlingingStopped)
455 IPC_MESSAGE_HANDLER(ViewHostMsg_UpdateRect, OnUpdateRect)
456 IPC_MESSAGE_HANDLER(ViewHostMsg_Focus, OnFocus)
457 IPC_MESSAGE_HANDLER(ViewHostMsg_Blur, OnBlur)
458 IPC_MESSAGE_HANDLER(ViewHostMsg_SetCursor, OnSetCursor)
459 IPC_MESSAGE_HANDLER(ViewHostMsg_SetTouchEventEmulationEnabled,
460 OnSetTouchEventEmulationEnabled)
461 IPC_MESSAGE_HANDLER(ViewHostMsg_TextInputStateChanged,
462 OnTextInputStateChanged)
463 IPC_MESSAGE_HANDLER(ViewHostMsg_ImeCancelComposition,
464 OnImeCancelComposition)
465 IPC_MESSAGE_HANDLER(ViewHostMsg_LockMouse, OnLockMouse)
466 IPC_MESSAGE_HANDLER(ViewHostMsg_UnlockMouse, OnUnlockMouse)
467 IPC_MESSAGE_HANDLER(ViewHostMsg_ShowDisambiguationPopup,
468 OnShowDisambiguationPopup)
469 IPC_MESSAGE_HANDLER(ViewHostMsg_SelectionChanged, OnSelectionChanged)
470 IPC_MESSAGE_HANDLER(ViewHostMsg_SelectionBoundsChanged,
471 OnSelectionBoundsChanged)
473 IPC_MESSAGE_HANDLER(ViewHostMsg_WindowlessPluginDummyWindowCreated,
474 OnWindowlessPluginDummyWindowCreated)
475 IPC_MESSAGE_HANDLER(ViewHostMsg_WindowlessPluginDummyWindowDestroyed,
476 OnWindowlessPluginDummyWindowDestroyed)
478 #if defined(OS_MACOSX)
479 IPC_MESSAGE_HANDLER(ViewHostMsg_CompositorSurfaceBuffersSwapped,
480 OnCompositorSurfaceBuffersSwapped)
482 #if defined(OS_MACOSX) || defined(USE_AURA)
483 IPC_MESSAGE_HANDLER(ViewHostMsg_ImeCompositionRangeChanged,
484 OnImeCompositionRangeChanged)
486 IPC_MESSAGE_UNHANDLED(handled = false)
487 IPC_END_MESSAGE_MAP()
489 if (!handled && input_router_ && input_router_->OnMessageReceived(msg))
492 if (!handled && view_ && view_->OnMessageReceived(msg))
498 bool RenderWidgetHostImpl::Send(IPC::Message* msg) {
499 if (IPC_MESSAGE_ID_CLASS(msg->type()) == InputMsgStart)
500 return input_router_->SendInput(make_scoped_ptr(msg));
502 return process_->Send(msg);
505 void RenderWidgetHostImpl::WasHidden() {
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() {
535 // Always repaint on restore.
536 bool needs_repainting = true;
537 needs_repainting_on_restore_ = false;
538 Send(new ViewMsg_WasShown(routing_id_, needs_repainting));
540 process_->WidgetRestored();
542 bool is_visible = true;
543 NotificationService::current()->Notify(
544 NOTIFICATION_RENDER_WIDGET_VISIBILITY_CHANGED,
545 Source<RenderWidgetHost>(this),
546 Details<bool>(&is_visible));
548 // It's possible for our size to be out of sync with the renderer. The
549 // following is one case that leads to this:
550 // 1. WasResized -> Send ViewMsg_Resize to render
551 // 2. WasResized -> do nothing as resize_ack_pending_ is true
553 // 4. OnUpdateRect from (1) processed. Does NOT invoke WasResized as view
554 // is hidden. Now renderer/browser out of sync with what they think size
556 // By invoking WasResized the renderer is updated as necessary. WasResized
557 // does nothing if the sizes are already in sync.
559 // TODO: ideally ViewMsg_WasShown would take a size. This way, the renderer
560 // could handle both the restore and resize at once. This isn't that big a
561 // deal as RenderWidget::WasShown delays updating, so that the resize from
562 // WasResized is usually processed before the renderer is painted.
566 void RenderWidgetHostImpl::WasResized() {
567 // Skip if the |delegate_| has already been detached because
568 // it's web contents is being deleted.
569 if (resize_ack_pending_ || !process_->HasConnection() || !view_ ||
570 !renderer_initialized_ || should_auto_resize_ || !delegate_) {
574 gfx::Size new_size(view_->GetRequestedRendererSize());
576 gfx::Size old_physical_backing_size = physical_backing_size_;
577 physical_backing_size_ = view_->GetPhysicalBackingSize();
578 bool was_fullscreen = is_fullscreen_;
579 is_fullscreen_ = IsFullscreen();
580 float old_overdraw_bottom_height = overdraw_bottom_height_;
581 overdraw_bottom_height_ = view_->GetOverdrawBottomHeight();
582 gfx::Size old_visible_viewport_size = visible_viewport_size_;
583 visible_viewport_size_ = view_->GetVisibleViewportSize();
585 bool size_changed = new_size != last_requested_size_;
586 bool side_payload_changed =
587 screen_info_out_of_date_ ||
588 old_physical_backing_size != physical_backing_size_ ||
589 was_fullscreen != is_fullscreen_ ||
590 old_overdraw_bottom_height != overdraw_bottom_height_ ||
591 old_visible_viewport_size != visible_viewport_size_;
593 if (!size_changed && !side_payload_changed)
597 screen_info_.reset(new blink::WebScreenInfo);
598 GetWebScreenInfo(screen_info_.get());
601 // We don't expect to receive an ACK when the requested size or the physical
602 // backing size is empty, or when the main viewport size didn't change.
603 if (!new_size.IsEmpty() && !physical_backing_size_.IsEmpty() && size_changed)
604 resize_ack_pending_ = g_check_for_pending_resize_ack;
606 ViewMsg_Resize_Params params;
607 params.screen_info = *screen_info_;
608 params.new_size = new_size;
609 params.physical_backing_size = physical_backing_size_;
610 params.overdraw_bottom_height = overdraw_bottom_height_;
611 params.visible_viewport_size = visible_viewport_size_;
612 params.resizer_rect = GetRootWindowResizerRect();
613 params.is_fullscreen = is_fullscreen_;
614 if (!Send(new ViewMsg_Resize(routing_id_, params))) {
615 resize_ack_pending_ = false;
617 last_requested_size_ = new_size;
621 void RenderWidgetHostImpl::ResizeRectChanged(const gfx::Rect& new_rect) {
622 Send(new ViewMsg_ChangeResizeRect(routing_id_, new_rect));
625 void RenderWidgetHostImpl::GotFocus() {
629 void RenderWidgetHostImpl::Focus() {
630 Send(new InputMsg_SetFocus(routing_id_, true));
633 void RenderWidgetHostImpl::Blur() {
634 // If there is a pending mouse lock request, we don't want to reject it at
635 // this point. The user can switch focus back to this view and approve the
638 view_->UnlockMouse();
641 touch_emulator_->CancelTouch();
643 Send(new InputMsg_SetFocus(routing_id_, false));
646 void RenderWidgetHostImpl::LostCapture() {
648 touch_emulator_->CancelTouch();
650 Send(new InputMsg_MouseCaptureLost(routing_id_));
653 void RenderWidgetHostImpl::SetActive(bool active) {
654 Send(new ViewMsg_SetActive(routing_id_, active));
657 void RenderWidgetHostImpl::LostMouseLock() {
658 Send(new ViewMsg_MouseLockLost(routing_id_));
661 void RenderWidgetHostImpl::ViewDestroyed() {
662 RejectMouseLockOrUnlockIfNecessary();
664 // TODO(evanm): tracking this may no longer be necessary;
665 // eliminate this function if so.
669 void RenderWidgetHostImpl::SetIsLoading(bool is_loading) {
670 is_loading_ = is_loading;
673 view_->SetIsLoading(is_loading);
676 void RenderWidgetHostImpl::CopyFromBackingStore(
677 const gfx::Rect& src_subrect,
678 const gfx::Size& accelerated_dst_size,
679 const base::Callback<void(bool, const SkBitmap&)>& callback,
680 const SkBitmap::Config& bitmap_config) {
682 TRACE_EVENT0("browser",
683 "RenderWidgetHostImpl::CopyFromBackingStore::FromCompositingSurface");
684 gfx::Rect accelerated_copy_rect = src_subrect.IsEmpty() ?
685 gfx::Rect(view_->GetViewBounds().size()) : src_subrect;
686 view_->CopyFromCompositingSurface(
687 accelerated_copy_rect, accelerated_dst_size, callback, bitmap_config);
691 callback.Run(false, SkBitmap());
694 bool RenderWidgetHostImpl::CanCopyFromBackingStore() {
696 return view_->IsSurfaceAvailableForCopy();
700 #if defined(OS_ANDROID)
701 void RenderWidgetHostImpl::LockBackingStore() {
703 view_->LockCompositingSurface();
706 void RenderWidgetHostImpl::UnlockBackingStore() {
708 view_->UnlockCompositingSurface();
712 void RenderWidgetHostImpl::PauseForPendingResizeOrRepaints() {
713 TRACE_EVENT0("browser",
714 "RenderWidgetHostImpl::PauseForPendingResizeOrRepaints");
716 if (!CanPauseForPendingResizeOrRepaints())
722 bool RenderWidgetHostImpl::CanPauseForPendingResizeOrRepaints() {
723 // Do not pause if the view is hidden.
727 // Do not pause if there is not a paint or resize already coming.
728 if (!repaint_ack_pending_ && !resize_ack_pending_)
734 void RenderWidgetHostImpl::WaitForSurface() {
735 TRACE_EVENT0("browser", "RenderWidgetHostImpl::WaitForSurface");
740 // The view_size will be current_size_ for auto-sized views and otherwise the
741 // size of the view_. (For auto-sized views, current_size_ is updated during
742 // UpdateRect messages.)
743 gfx::Size view_size = current_size_;
744 if (!should_auto_resize_) {
745 // Get the desired size from the current view bounds.
746 gfx::Rect view_rect = view_->GetViewBounds();
747 if (view_rect.IsEmpty())
749 view_size = view_rect.size();
752 TRACE_EVENT2("renderer_host",
753 "RenderWidgetHostImpl::WaitForBackingStore",
755 base::IntToString(view_size.width()),
757 base::IntToString(view_size.height()));
759 // We should not be asked to paint while we are hidden. If we are hidden,
760 // then it means that our consumer failed to call WasShown. If we're not
761 // force creating the backing store, it's OK since we can feel free to give
762 // out our cached one if we have it.
763 DCHECK(!is_hidden_) << "WaitForSurface called while hidden!";
765 // We should never be called recursively; this can theoretically lead to
766 // infinite recursion and almost certainly leads to lower performance.
767 DCHECK(!in_get_backing_store_) << "WaitForSurface called recursively!";
768 base::AutoReset<bool> auto_reset_in_get_backing_store(
769 &in_get_backing_store_, true);
771 // We might have a surface that we can use!
772 if (view_->HasAcceleratedSurface(view_size))
775 // We do not have a suitable backing store in the cache, so send out a
776 // request to the renderer to paint the view if required.
777 if (!repaint_ack_pending_ && !resize_ack_pending_) {
778 repaint_start_time_ = TimeTicks::Now();
779 repaint_ack_pending_ = true;
780 TRACE_EVENT_ASYNC_BEGIN0(
781 "renderer_host", "RenderWidgetHostImpl::repaint_ack_pending_", this);
782 Send(new ViewMsg_Repaint(routing_id_, view_size));
785 TimeDelta max_delay = TimeDelta::FromMilliseconds(kPaintMsgTimeoutMS);
786 TimeTicks end_time = TimeTicks::Now() + max_delay;
788 TRACE_EVENT0("renderer_host", "WaitForSurface::WaitForUpdate");
790 // When we have asked the RenderWidget to resize, and we are still waiting
791 // on a response, block for a little while to see if we can't get a response
792 // before returning the old (incorrectly sized) backing store.
794 if (process_->WaitForBackingStoreMsg(routing_id_, max_delay, &msg)) {
795 OnMessageReceived(msg);
797 // For auto-resized views, current_size_ determines the view_size and it
798 // may have changed during the handling of an UpdateRect message.
799 if (should_auto_resize_)
800 view_size = current_size_;
802 // Break now if we got a backing store or accelerated surface of the
804 if (view_->HasAcceleratedSurface(view_size))
807 TRACE_EVENT0("renderer_host", "WaitForSurface::Timeout");
811 // Loop if we still have time left and haven't gotten a properly sized
812 // BackingStore yet. This is necessary to support the GPU path which
813 // typically has multiple frames pipelined -- we may need to skip one or two
814 // BackingStore messages to get to the latest.
815 max_delay = end_time - TimeTicks::Now();
816 } while (max_delay > TimeDelta::FromSeconds(0));
819 bool RenderWidgetHostImpl::ScheduleComposite() {
820 if (is_hidden_ || current_size_.IsEmpty() || repaint_ack_pending_ ||
821 resize_ack_pending_) {
825 // Send out a request to the renderer to paint the view if required.
826 repaint_start_time_ = TimeTicks::Now();
827 repaint_ack_pending_ = true;
828 TRACE_EVENT_ASYNC_BEGIN0(
829 "renderer_host", "RenderWidgetHostImpl::repaint_ack_pending_", this);
830 Send(new ViewMsg_Repaint(routing_id_, current_size_));
834 void RenderWidgetHostImpl::StartHangMonitorTimeout(base::TimeDelta delay) {
835 if (hang_monitor_timeout_)
836 hang_monitor_timeout_->Start(delay);
839 void RenderWidgetHostImpl::RestartHangMonitorTimeout() {
840 if (hang_monitor_timeout_)
841 hang_monitor_timeout_->Restart(
842 base::TimeDelta::FromMilliseconds(hung_renderer_delay_ms_));
845 void RenderWidgetHostImpl::StopHangMonitorTimeout() {
846 if (hang_monitor_timeout_)
847 hang_monitor_timeout_->Stop();
848 RendererIsResponsive();
851 void RenderWidgetHostImpl::EnableFullAccessibilityMode() {
852 AddAccessibilityMode(AccessibilityModeComplete);
855 bool RenderWidgetHostImpl::IsFullAccessibilityModeForTesting() {
856 return accessibility_mode() == AccessibilityModeComplete;
859 void RenderWidgetHostImpl::EnableTreeOnlyAccessibilityMode() {
860 AddAccessibilityMode(AccessibilityModeTreeOnly);
863 bool RenderWidgetHostImpl::IsTreeOnlyAccessibilityModeForTesting() {
864 return accessibility_mode() == AccessibilityModeTreeOnly;
867 void RenderWidgetHostImpl::ForwardMouseEvent(const WebMouseEvent& mouse_event) {
868 ForwardMouseEventWithLatencyInfo(mouse_event, ui::LatencyInfo());
871 void RenderWidgetHostImpl::ForwardMouseEventWithLatencyInfo(
872 const blink::WebMouseEvent& mouse_event,
873 const ui::LatencyInfo& ui_latency) {
874 TRACE_EVENT2("input", "RenderWidgetHostImpl::ForwardMouseEvent",
875 "x", mouse_event.x, "y", mouse_event.y);
877 ui::LatencyInfo latency_info =
878 CreateRWHLatencyInfoIfNotExist(&ui_latency, mouse_event.type);
880 for (size_t i = 0; i < mouse_event_callbacks_.size(); ++i) {
881 if (mouse_event_callbacks_[i].Run(mouse_event))
885 if (IgnoreInputEvents())
888 if (touch_emulator_ && touch_emulator_->HandleMouseEvent(mouse_event))
891 input_router_->SendMouseEvent(MouseEventWithLatencyInfo(mouse_event,
895 void RenderWidgetHostImpl::OnPointerEventActivate() {
898 void RenderWidgetHostImpl::ForwardWheelEvent(
899 const WebMouseWheelEvent& wheel_event) {
900 ForwardWheelEventWithLatencyInfo(wheel_event, ui::LatencyInfo());
903 void RenderWidgetHostImpl::ForwardWheelEventWithLatencyInfo(
904 const blink::WebMouseWheelEvent& wheel_event,
905 const ui::LatencyInfo& ui_latency) {
906 TRACE_EVENT0("input", "RenderWidgetHostImpl::ForwardWheelEvent");
908 ui::LatencyInfo latency_info =
909 CreateRWHLatencyInfoIfNotExist(&ui_latency, wheel_event.type);
911 if (IgnoreInputEvents())
914 if (touch_emulator_ && touch_emulator_->HandleMouseWheelEvent(wheel_event))
917 input_router_->SendWheelEvent(MouseWheelEventWithLatencyInfo(wheel_event,
921 void RenderWidgetHostImpl::ForwardGestureEvent(
922 const blink::WebGestureEvent& gesture_event) {
923 ForwardGestureEventWithLatencyInfo(gesture_event, ui::LatencyInfo());
926 void RenderWidgetHostImpl::ForwardGestureEventWithLatencyInfo(
927 const blink::WebGestureEvent& gesture_event,
928 const ui::LatencyInfo& ui_latency) {
929 TRACE_EVENT0("input", "RenderWidgetHostImpl::ForwardGestureEvent");
930 // Early out if necessary, prior to performing latency logic.
931 if (IgnoreInputEvents())
934 if (delegate_->PreHandleGestureEvent(gesture_event))
937 ui::LatencyInfo latency_info =
938 CreateRWHLatencyInfoIfNotExist(&ui_latency, gesture_event.type);
940 if (gesture_event.type == blink::WebInputEvent::GestureScrollUpdate) {
941 latency_info.AddLatencyNumber(
942 ui::INPUT_EVENT_LATENCY_SCROLL_UPDATE_RWH_COMPONENT,
943 GetLatencyComponentId(),
944 ++last_input_number_);
946 // Make a copy of the INPUT_EVENT_LATENCY_ORIGINAL_COMPONENT with a
947 // different name INPUT_EVENT_LATENCY_SCROLL_UPDATE_ORIGINAL_COMPONENT.
948 // So we can track the latency specifically for scroll update events.
949 ui::LatencyInfo::LatencyComponent original_component;
950 if (latency_info.FindLatency(ui::INPUT_EVENT_LATENCY_ORIGINAL_COMPONENT,
952 &original_component)) {
953 latency_info.AddLatencyNumberWithTimestamp(
954 ui::INPUT_EVENT_LATENCY_SCROLL_UPDATE_ORIGINAL_COMPONENT,
955 GetLatencyComponentId(),
956 original_component.sequence_number,
957 original_component.event_time,
958 original_component.event_count);
962 GestureEventWithLatencyInfo gesture_with_latency(gesture_event, latency_info);
963 input_router_->SendGestureEvent(gesture_with_latency);
966 void RenderWidgetHostImpl::ForwardTouchEvent(
967 const blink::WebTouchEvent& touch_event) {
968 ForwardTouchEventWithLatencyInfo(touch_event, ui::LatencyInfo());
971 void RenderWidgetHostImpl::ForwardTouchEventWithLatencyInfo(
972 const blink::WebTouchEvent& touch_event,
973 const ui::LatencyInfo& ui_latency) {
974 TRACE_EVENT0("input", "RenderWidgetHostImpl::ForwardTouchEvent");
976 // Always forward TouchEvents for touch stream consistency. They will be
977 // ignored if appropriate in FilterInputEvent().
979 ui::LatencyInfo latency_info =
980 CreateRWHLatencyInfoIfNotExist(&ui_latency, touch_event.type);
981 TouchEventWithLatencyInfo touch_with_latency(touch_event, latency_info);
982 input_router_->SendTouchEvent(touch_with_latency);
985 void RenderWidgetHostImpl::ForwardKeyboardEvent(
986 const NativeWebKeyboardEvent& key_event) {
987 TRACE_EVENT0("input", "RenderWidgetHostImpl::ForwardKeyboardEvent");
988 if (IgnoreInputEvents())
991 if (!process_->HasConnection())
994 // First, let keypress listeners take a shot at handling the event. If a
995 // listener handles the event, it should not be propagated to the renderer.
996 if (KeyPressListenersHandleEvent(key_event)) {
997 // Some keypresses that are accepted by the listener might have follow up
998 // char events, which should be ignored.
999 if (key_event.type == WebKeyboardEvent::RawKeyDown)
1000 suppress_next_char_events_ = true;
1004 if (key_event.type == WebKeyboardEvent::Char &&
1005 (key_event.windowsKeyCode == ui::VKEY_RETURN ||
1006 key_event.windowsKeyCode == ui::VKEY_SPACE)) {
1010 // Double check the type to make sure caller hasn't sent us nonsense that
1011 // will mess up our key queue.
1012 if (!WebInputEvent::isKeyboardEventType(key_event.type))
1015 if (suppress_next_char_events_) {
1016 // If preceding RawKeyDown event was handled by the browser, then we need
1017 // suppress all Char events generated by it. Please note that, one
1018 // RawKeyDown event may generate multiple Char events, so we can't reset
1019 // |suppress_next_char_events_| until we get a KeyUp or a RawKeyDown.
1020 if (key_event.type == WebKeyboardEvent::Char)
1022 // We get a KeyUp or a RawKeyDown event.
1023 suppress_next_char_events_ = false;
1026 bool is_shortcut = false;
1028 // Only pre-handle the key event if it's not handled by the input method.
1029 if (delegate_ && !key_event.skip_in_browser) {
1030 // We need to set |suppress_next_char_events_| to true if
1031 // PreHandleKeyboardEvent() returns true, but |this| may already be
1032 // destroyed at that time. So set |suppress_next_char_events_| true here,
1033 // then revert it afterwards when necessary.
1034 if (key_event.type == WebKeyboardEvent::RawKeyDown)
1035 suppress_next_char_events_ = true;
1037 // Tab switching/closing accelerators aren't sent to the renderer to avoid
1038 // a hung/malicious renderer from interfering.
1039 if (delegate_->PreHandleKeyboardEvent(key_event, &is_shortcut))
1042 if (key_event.type == WebKeyboardEvent::RawKeyDown)
1043 suppress_next_char_events_ = false;
1046 if (touch_emulator_ && touch_emulator_->HandleKeyboardEvent(key_event))
1049 input_router_->SendKeyboardEvent(
1051 CreateRWHLatencyInfoIfNotExist(NULL, key_event.type),
1055 void RenderWidgetHostImpl::QueueSyntheticGesture(
1056 scoped_ptr<SyntheticGesture> synthetic_gesture,
1057 const base::Callback<void(SyntheticGesture::Result)>& on_complete) {
1058 if (!synthetic_gesture_controller_ && view_) {
1059 synthetic_gesture_controller_.reset(
1060 new SyntheticGestureController(
1061 view_->CreateSyntheticGestureTarget().Pass()));
1063 if (synthetic_gesture_controller_) {
1064 synthetic_gesture_controller_->QueueSyntheticGesture(
1065 synthetic_gesture.Pass(), on_complete);
1069 void RenderWidgetHostImpl::SetCursor(const WebCursor& cursor) {
1072 view_->UpdateCursor(cursor);
1075 void RenderWidgetHostImpl::SendCursorVisibilityState(bool is_visible) {
1076 Send(new InputMsg_CursorVisibilityChange(GetRoutingID(), is_visible));
1079 int64 RenderWidgetHostImpl::GetLatencyComponentId() {
1080 return GetRoutingID() | (static_cast<int64>(GetProcess()->GetID()) << 32);
1084 void RenderWidgetHostImpl::DisableResizeAckCheckForTesting() {
1085 g_check_for_pending_resize_ack = false;
1088 ui::LatencyInfo RenderWidgetHostImpl::CreateRWHLatencyInfoIfNotExist(
1089 const ui::LatencyInfo* original, WebInputEvent::Type type) {
1090 ui::LatencyInfo info;
1093 // In Aura, gesture event will already carry its original touch event's
1094 // INPUT_EVENT_LATENCY_RWH_COMPONENT.
1095 if (!info.FindLatency(ui::INPUT_EVENT_LATENCY_BEGIN_RWH_COMPONENT,
1096 GetLatencyComponentId(),
1098 info.AddLatencyNumber(ui::INPUT_EVENT_LATENCY_BEGIN_RWH_COMPONENT,
1099 GetLatencyComponentId(),
1100 ++last_input_number_);
1101 info.TraceEventType(WebInputEventTraits::GetName(type));
1107 void RenderWidgetHostImpl::AddKeyPressEventCallback(
1108 const KeyPressEventCallback& callback) {
1109 key_press_event_callbacks_.push_back(callback);
1112 void RenderWidgetHostImpl::RemoveKeyPressEventCallback(
1113 const KeyPressEventCallback& callback) {
1114 for (size_t i = 0; i < key_press_event_callbacks_.size(); ++i) {
1115 if (key_press_event_callbacks_[i].Equals(callback)) {
1116 key_press_event_callbacks_.erase(
1117 key_press_event_callbacks_.begin() + i);
1123 void RenderWidgetHostImpl::AddMouseEventCallback(
1124 const MouseEventCallback& callback) {
1125 mouse_event_callbacks_.push_back(callback);
1128 void RenderWidgetHostImpl::RemoveMouseEventCallback(
1129 const MouseEventCallback& callback) {
1130 for (size_t i = 0; i < mouse_event_callbacks_.size(); ++i) {
1131 if (mouse_event_callbacks_[i].Equals(callback)) {
1132 mouse_event_callbacks_.erase(mouse_event_callbacks_.begin() + i);
1138 void RenderWidgetHostImpl::GetWebScreenInfo(blink::WebScreenInfo* result) {
1139 TRACE_EVENT0("renderer_host", "RenderWidgetHostImpl::GetWebScreenInfo");
1141 view_->GetScreenInfo(result);
1143 RenderWidgetHostViewBase::GetDefaultScreenInfo(result);
1144 screen_info_out_of_date_ = false;
1147 const NativeWebKeyboardEvent*
1148 RenderWidgetHostImpl::GetLastKeyboardEvent() const {
1149 return input_router_->GetLastKeyboardEvent();
1152 void RenderWidgetHostImpl::NotifyScreenInfoChanged() {
1153 // The resize message (which may not happen immediately) will carry with it
1154 // the screen info as well as the new size (if the screen has changed scale
1156 InvalidateScreenInfo();
1160 void RenderWidgetHostImpl::InvalidateScreenInfo() {
1161 screen_info_out_of_date_ = true;
1162 screen_info_.reset();
1165 void RenderWidgetHostImpl::OnSelectionChanged(const base::string16& text,
1167 const gfx::Range& range) {
1169 view_->SelectionChanged(text, offset, range);
1172 void RenderWidgetHostImpl::OnSelectionBoundsChanged(
1173 const ViewHostMsg_SelectionBounds_Params& params) {
1175 view_->SelectionBoundsChanged(params);
1179 void RenderWidgetHostImpl::UpdateVSyncParameters(base::TimeTicks timebase,
1180 base::TimeDelta interval) {
1181 Send(new ViewMsg_UpdateVSyncParameters(GetRoutingID(), timebase, interval));
1184 void RenderWidgetHostImpl::RendererExited(base::TerminationStatus status,
1186 // Clearing this flag causes us to re-create the renderer when recovering
1187 // from a crashed renderer.
1188 renderer_initialized_ = false;
1190 waiting_for_screen_rects_ack_ = false;
1192 // Reset to ensure that input routing works with a new renderer.
1193 input_router_.reset(new InputRouterImpl(
1194 process_, this, this, routing_id_, GetInputRouterConfigForPlatform()));
1196 // Must reset these to ensure that keyboard events work with a new renderer.
1197 suppress_next_char_events_ = false;
1199 // Reset some fields in preparation for recovering from a crash.
1200 ResetSizeAndRepaintPendingFlags();
1201 current_size_.SetSize(0, 0);
1204 // Reset this to ensure the hung renderer mechanism is working properly.
1205 in_flight_event_count_ = 0;
1208 GpuSurfaceTracker::Get()->SetSurfaceHandle(surface_id_,
1209 gfx::GLSurfaceHandle());
1210 view_->RenderProcessGone(status, exit_code);
1211 view_ = NULL; // The View should be deleted by RenderProcessGone.
1214 synthetic_gesture_controller_.reset();
1217 void RenderWidgetHostImpl::UpdateTextDirection(WebTextDirection direction) {
1218 text_direction_updated_ = true;
1219 text_direction_ = direction;
1222 void RenderWidgetHostImpl::CancelUpdateTextDirection() {
1223 if (text_direction_updated_)
1224 text_direction_canceled_ = true;
1227 void RenderWidgetHostImpl::NotifyTextDirection() {
1228 if (text_direction_updated_) {
1229 if (!text_direction_canceled_)
1230 Send(new ViewMsg_SetTextDirection(GetRoutingID(), text_direction_));
1231 text_direction_updated_ = false;
1232 text_direction_canceled_ = false;
1236 void RenderWidgetHostImpl::SetInputMethodActive(bool activate) {
1237 input_method_active_ = activate;
1238 Send(new ViewMsg_SetInputMethodActive(GetRoutingID(), activate));
1241 void RenderWidgetHostImpl::CandidateWindowShown() {
1242 Send(new ViewMsg_CandidateWindowShown(GetRoutingID()));
1245 void RenderWidgetHostImpl::CandidateWindowUpdated() {
1246 Send(new ViewMsg_CandidateWindowUpdated(GetRoutingID()));
1249 void RenderWidgetHostImpl::CandidateWindowHidden() {
1250 Send(new ViewMsg_CandidateWindowHidden(GetRoutingID()));
1253 void RenderWidgetHostImpl::ImeSetComposition(
1254 const base::string16& text,
1255 const std::vector<blink::WebCompositionUnderline>& underlines,
1256 int selection_start,
1257 int selection_end) {
1258 Send(new ViewMsg_ImeSetComposition(
1259 GetRoutingID(), text, underlines, selection_start, selection_end));
1262 void RenderWidgetHostImpl::ImeConfirmComposition(
1263 const base::string16& text,
1264 const gfx::Range& replacement_range,
1265 bool keep_selection) {
1266 Send(new ViewMsg_ImeConfirmComposition(
1267 GetRoutingID(), text, replacement_range, keep_selection));
1270 void RenderWidgetHostImpl::ImeCancelComposition() {
1271 Send(new ViewMsg_ImeSetComposition(GetRoutingID(), base::string16(),
1272 std::vector<blink::WebCompositionUnderline>(), 0, 0));
1275 gfx::Rect RenderWidgetHostImpl::GetRootWindowResizerRect() const {
1279 void RenderWidgetHostImpl::RequestToLockMouse(bool user_gesture,
1280 bool last_unlocked_by_target) {
1281 // Directly reject to lock the mouse. Subclass can override this method to
1282 // decide whether to allow mouse lock or not.
1283 GotResponseToLockMouseRequest(false);
1286 void RenderWidgetHostImpl::RejectMouseLockOrUnlockIfNecessary() {
1287 DCHECK(!pending_mouse_lock_request_ || !IsMouseLocked());
1288 if (pending_mouse_lock_request_) {
1289 pending_mouse_lock_request_ = false;
1290 Send(new ViewMsg_LockMouse_ACK(routing_id_, false));
1291 } else if (IsMouseLocked()) {
1292 view_->UnlockMouse();
1296 bool RenderWidgetHostImpl::IsMouseLocked() const {
1297 return view_ ? view_->IsMouseLocked() : false;
1300 bool RenderWidgetHostImpl::IsFullscreen() const {
1304 void RenderWidgetHostImpl::SetShouldAutoResize(bool enable) {
1305 should_auto_resize_ = enable;
1308 void RenderWidgetHostImpl::Destroy() {
1309 NotificationService::current()->Notify(
1310 NOTIFICATION_RENDER_WIDGET_HOST_DESTROYED,
1311 Source<RenderWidgetHost>(this),
1312 NotificationService::NoDetails());
1314 // Tell the view to die.
1315 // Note that in the process of the view shutting down, it can call a ton
1316 // of other messages on us. So if you do any other deinitialization here,
1317 // do it after this call to view_->Destroy().
1324 void RenderWidgetHostImpl::RendererIsUnresponsive() {
1325 NotificationService::current()->Notify(
1326 NOTIFICATION_RENDER_WIDGET_HOST_HANG,
1327 Source<RenderWidgetHost>(this),
1328 NotificationService::NoDetails());
1329 is_unresponsive_ = true;
1330 NotifyRendererUnresponsive();
1333 void RenderWidgetHostImpl::RendererIsResponsive() {
1334 if (is_unresponsive_) {
1335 is_unresponsive_ = false;
1336 NotifyRendererResponsive();
1340 void RenderWidgetHostImpl::OnRenderViewReady() {
1345 void RenderWidgetHostImpl::OnRenderProcessGone(int status, int exit_code) {
1346 // TODO(evanm): This synchronously ends up calling "delete this".
1347 // Is that really what we want in response to this message? I'm matching
1348 // previous behavior of the code here.
1352 void RenderWidgetHostImpl::OnClose() {
1356 void RenderWidgetHostImpl::OnSetTooltipText(
1357 const base::string16& tooltip_text,
1358 WebTextDirection text_direction_hint) {
1359 // First, add directionality marks around tooltip text if necessary.
1360 // A naive solution would be to simply always wrap the text. However, on
1361 // windows, Unicode directional embedding characters can't be displayed on
1362 // systems that lack RTL fonts and are instead displayed as empty squares.
1364 // To get around this we only wrap the string when we deem it necessary i.e.
1365 // when the locale direction is different than the tooltip direction hint.
1367 // Currently, we use element's directionality as the tooltip direction hint.
1368 // An alternate solution would be to set the overall directionality based on
1369 // trying to detect the directionality from the tooltip text rather than the
1370 // element direction. One could argue that would be a preferable solution
1371 // but we use the current approach to match Fx & IE's behavior.
1372 base::string16 wrapped_tooltip_text = tooltip_text;
1373 if (!tooltip_text.empty()) {
1374 if (text_direction_hint == blink::WebTextDirectionLeftToRight) {
1375 // Force the tooltip to have LTR directionality.
1376 wrapped_tooltip_text =
1377 base::i18n::GetDisplayStringInLTRDirectionality(wrapped_tooltip_text);
1378 } else if (text_direction_hint == blink::WebTextDirectionRightToLeft &&
1379 !base::i18n::IsRTL()) {
1380 // Force the tooltip to have RTL directionality.
1381 base::i18n::WrapStringWithRTLFormatting(&wrapped_tooltip_text);
1385 view_->SetTooltipText(wrapped_tooltip_text);
1388 void RenderWidgetHostImpl::OnUpdateScreenRectsAck() {
1389 waiting_for_screen_rects_ack_ = false;
1393 if (view_->GetViewBounds() == last_view_screen_rect_ &&
1394 view_->GetBoundsInRootWindow() == last_window_screen_rect_) {
1401 void RenderWidgetHostImpl::OnRequestMove(const gfx::Rect& pos) {
1403 view_->SetBounds(pos);
1404 Send(new ViewMsg_Move_ACK(routing_id_));
1408 #if defined(OS_MACOSX)
1409 void RenderWidgetHostImpl::OnCompositorSurfaceBuffersSwapped(
1410 const ViewHostMsg_CompositorSurfaceBuffersSwapped_Params& params) {
1411 // This trace event is used in
1412 // chrome/browser/extensions/api/cast_streaming/performance_test.cc
1413 TRACE_EVENT0("renderer_host",
1414 "RenderWidgetHostImpl::OnCompositorSurfaceBuffersSwapped");
1415 // This trace event is used in
1416 // chrome/browser/extensions/api/cast_streaming/performance_test.cc
1417 UNSHIPPED_TRACE_EVENT0("test_fps",
1418 TRACE_DISABLED_BY_DEFAULT("OnSwapCompositorFrame"));
1419 if (!ui::LatencyInfo::Verify(params.latency_info,
1420 "ViewHostMsg_CompositorSurfaceBuffersSwapped"))
1423 AcceleratedSurfaceMsg_BufferPresented_Params ack_params;
1424 ack_params.sync_point = 0;
1425 RenderWidgetHostImpl::AcknowledgeBufferPresent(params.route_id,
1426 params.gpu_process_host_id,
1430 GpuHostMsg_AcceleratedSurfaceBuffersSwapped_Params gpu_params;
1431 gpu_params.surface_id = params.surface_id;
1432 gpu_params.surface_handle = params.surface_handle;
1433 gpu_params.route_id = params.route_id;
1434 gpu_params.size = params.size;
1435 gpu_params.scale_factor = params.scale_factor;
1436 gpu_params.latency_info = params.latency_info;
1437 for (size_t i = 0; i < gpu_params.latency_info.size(); i++)
1438 AddLatencyInfoComponentIds(&gpu_params.latency_info[i]);
1439 view_->AcceleratedSurfaceBuffersSwapped(gpu_params,
1440 params.gpu_process_host_id);
1441 view_->DidReceiveRendererFrame();
1445 bool RenderWidgetHostImpl::OnSwapCompositorFrame(
1446 const IPC::Message& message) {
1447 // This trace event is used in
1448 // chrome/browser/extensions/api/cast_streaming/performance_test.cc
1449 UNSHIPPED_TRACE_EVENT0("test_fps",
1450 TRACE_DISABLED_BY_DEFAULT("OnSwapCompositorFrame"));
1451 ViewHostMsg_SwapCompositorFrame::Param param;
1452 if (!ViewHostMsg_SwapCompositorFrame::Read(&message, ¶m))
1454 scoped_ptr<cc::CompositorFrame> frame(new cc::CompositorFrame);
1455 uint32 output_surface_id = param.a;
1456 param.b.AssignTo(frame.get());
1458 for (size_t i = 0; i < frame->metadata.latency_info.size(); i++)
1459 AddLatencyInfoComponentIds(&frame->metadata.latency_info[i]);
1461 input_router_->OnViewUpdated(
1462 GetInputRouterViewFlagsFromCompositorFrameMetadata(frame->metadata));
1465 view_->OnSwapCompositorFrame(output_surface_id, frame.Pass());
1466 view_->DidReceiveRendererFrame();
1468 cc::CompositorFrameAck ack;
1469 if (frame->gl_frame_data) {
1470 ack.gl_frame_data = frame->gl_frame_data.Pass();
1471 ack.gl_frame_data->sync_point = 0;
1472 } else if (frame->delegated_frame_data) {
1473 cc::TransferableResource::ReturnResources(
1474 frame->delegated_frame_data->resource_list,
1476 } else if (frame->software_frame_data) {
1477 ack.last_software_frame_id = frame->software_frame_data->id;
1479 SendSwapCompositorFrameAck(routing_id_, output_surface_id,
1480 process_->GetID(), ack);
1485 void RenderWidgetHostImpl::OnFlingingStopped() {
1487 view_->DidStopFlinging();
1490 void RenderWidgetHostImpl::OnUpdateRect(
1491 const ViewHostMsg_UpdateRect_Params& params) {
1492 TRACE_EVENT0("renderer_host", "RenderWidgetHostImpl::OnUpdateRect");
1493 TimeTicks paint_start = TimeTicks::Now();
1495 // Update our knowledge of the RenderWidget's size.
1496 current_size_ = params.view_size;
1497 // Update our knowledge of the RenderWidget's scroll offset.
1498 last_scroll_offset_ = params.scroll_offset;
1500 bool is_resize_ack =
1501 ViewHostMsg_UpdateRect_Flags::is_resize_ack(params.flags);
1503 // resize_ack_pending_ needs to be cleared before we call DidPaintRect, since
1504 // that will end up reaching GetBackingStore.
1505 if (is_resize_ack) {
1506 DCHECK(!g_check_for_pending_resize_ack || resize_ack_pending_);
1507 resize_ack_pending_ = false;
1510 bool is_repaint_ack =
1511 ViewHostMsg_UpdateRect_Flags::is_repaint_ack(params.flags);
1512 if (is_repaint_ack) {
1513 DCHECK(repaint_ack_pending_);
1514 TRACE_EVENT_ASYNC_END0(
1515 "renderer_host", "RenderWidgetHostImpl::repaint_ack_pending_", this);
1516 repaint_ack_pending_ = false;
1517 TimeDelta delta = TimeTicks::Now() - repaint_start_time_;
1518 UMA_HISTOGRAM_TIMES("MPArch.RWH_RepaintDelta", delta);
1521 DCHECK(!params.view_size.IsEmpty());
1523 DidUpdateBackingStore(params, paint_start);
1525 if (should_auto_resize_) {
1526 bool post_callback = new_auto_size_.IsEmpty();
1527 new_auto_size_ = params.view_size;
1528 if (post_callback) {
1529 base::MessageLoop::current()->PostTask(
1531 base::Bind(&RenderWidgetHostImpl::DelayedAutoResized,
1532 weak_factory_.GetWeakPtr()));
1536 // Log the time delta for processing a paint message. On platforms that don't
1537 // support asynchronous painting, this is equivalent to
1538 // MPArch.RWH_TotalPaintTime.
1539 TimeDelta delta = TimeTicks::Now() - paint_start;
1540 UMA_HISTOGRAM_TIMES("MPArch.RWH_OnMsgUpdateRect", delta);
1543 void RenderWidgetHostImpl::DidUpdateBackingStore(
1544 const ViewHostMsg_UpdateRect_Params& params,
1545 const TimeTicks& paint_start) {
1546 TRACE_EVENT0("renderer_host", "RenderWidgetHostImpl::DidUpdateBackingStore");
1547 TimeTicks update_start = TimeTicks::Now();
1549 // Move the plugins if the view hasn't already been destroyed. Plugin moves
1550 // will not be re-issued, so must move them now, regardless of whether we
1551 // paint or not. MovePluginWindows attempts to move the plugin windows and
1552 // in the process could dispatch other window messages which could cause the
1553 // view to be destroyed.
1555 view_->MovePluginWindows(params.plugin_window_moves);
1557 NotificationService::current()->Notify(
1558 NOTIFICATION_RENDER_WIDGET_HOST_DID_UPDATE_BACKING_STORE,
1559 Source<RenderWidgetHost>(this),
1560 NotificationService::NoDetails());
1562 // We don't need to update the view if the view is hidden. We must do this
1563 // early return after the ACK is sent, however, or the renderer will not send
1568 // If we got a resize ack, then perhaps we have another resize to send?
1569 bool is_resize_ack =
1570 ViewHostMsg_UpdateRect_Flags::is_resize_ack(params.flags);
1574 // Log the time delta for processing a paint message.
1575 TimeTicks now = TimeTicks::Now();
1576 TimeDelta delta = now - update_start;
1577 UMA_HISTOGRAM_TIMES("MPArch.RWH_DidUpdateBackingStore", delta);
1580 void RenderWidgetHostImpl::OnQueueSyntheticGesture(
1581 const SyntheticGesturePacket& gesture_packet) {
1582 // Only allow untrustworthy gestures if explicitly enabled.
1583 if (!CommandLine::ForCurrentProcess()->HasSwitch(
1584 cc::switches::kEnableGpuBenchmarking)) {
1585 RecordAction(base::UserMetricsAction("BadMessageTerminate_RWH7"));
1586 GetProcess()->ReceivedBadMessage();
1590 QueueSyntheticGesture(
1591 SyntheticGesture::Create(*gesture_packet.gesture_params()),
1592 base::Bind(&RenderWidgetHostImpl::OnSyntheticGestureCompleted,
1593 weak_factory_.GetWeakPtr()));
1596 void RenderWidgetHostImpl::OnFocus() {
1597 // Only RenderViewHost can deal with that message.
1598 RecordAction(base::UserMetricsAction("BadMessageTerminate_RWH4"));
1599 GetProcess()->ReceivedBadMessage();
1602 void RenderWidgetHostImpl::OnBlur() {
1603 // Only RenderViewHost can deal with that message.
1604 RecordAction(base::UserMetricsAction("BadMessageTerminate_RWH5"));
1605 GetProcess()->ReceivedBadMessage();
1608 void RenderWidgetHostImpl::OnSetCursor(const WebCursor& cursor) {
1612 void RenderWidgetHostImpl::OnSetTouchEventEmulationEnabled(
1613 bool enabled, bool allow_pinch) {
1615 delegate_->OnTouchEmulationEnabled(enabled);
1618 if (!touch_emulator_)
1619 touch_emulator_.reset(new TouchEmulator(this));
1620 touch_emulator_->Enable(allow_pinch);
1622 if (touch_emulator_)
1623 touch_emulator_->Disable();
1627 void RenderWidgetHostImpl::OnTextInputStateChanged(
1628 const ViewHostMsg_TextInputState_Params& params) {
1630 view_->TextInputStateChanged(params);
1633 #if defined(OS_MACOSX) || defined(USE_AURA)
1634 void RenderWidgetHostImpl::OnImeCompositionRangeChanged(
1635 const gfx::Range& range,
1636 const std::vector<gfx::Rect>& character_bounds) {
1638 view_->ImeCompositionRangeChanged(range, character_bounds);
1642 void RenderWidgetHostImpl::OnImeCancelComposition() {
1644 view_->ImeCancelComposition();
1647 void RenderWidgetHostImpl::OnLockMouse(bool user_gesture,
1648 bool last_unlocked_by_target,
1651 if (pending_mouse_lock_request_) {
1652 Send(new ViewMsg_LockMouse_ACK(routing_id_, false));
1654 } else if (IsMouseLocked()) {
1655 Send(new ViewMsg_LockMouse_ACK(routing_id_, true));
1659 pending_mouse_lock_request_ = true;
1660 if (privileged && allow_privileged_mouse_lock_) {
1661 // Directly approve to lock the mouse.
1662 GotResponseToLockMouseRequest(true);
1664 RequestToLockMouse(user_gesture, last_unlocked_by_target);
1668 void RenderWidgetHostImpl::OnUnlockMouse() {
1669 RejectMouseLockOrUnlockIfNecessary();
1672 void RenderWidgetHostImpl::OnShowDisambiguationPopup(
1673 const gfx::Rect& rect,
1674 const gfx::Size& size,
1675 const cc::SharedBitmapId& id) {
1676 DCHECK(!rect.IsEmpty());
1677 DCHECK(!size.IsEmpty());
1679 scoped_ptr<cc::SharedBitmap> bitmap =
1680 HostSharedBitmapManager::current()->GetSharedBitmapFromId(size, id);
1682 RecordAction(base::UserMetricsAction("BadMessageTerminate_RWH6"));
1683 GetProcess()->ReceivedBadMessage();
1687 DCHECK(bitmap->pixels());
1689 SkBitmap zoomed_bitmap;
1690 zoomed_bitmap.setConfig(SkBitmap::kARGB_8888_Config,
1691 size.width(), size.height());
1692 zoomed_bitmap.setPixels(bitmap->pixels());
1694 #if defined(OS_ANDROID)
1696 view_->ShowDisambiguationPopup(rect, zoomed_bitmap);
1701 zoomed_bitmap.setPixels(0);
1702 Send(new ViewMsg_ReleaseDisambiguationPopupBitmap(GetRoutingID(), id));
1706 void RenderWidgetHostImpl::OnWindowlessPluginDummyWindowCreated(
1707 gfx::NativeViewId dummy_activation_window) {
1708 HWND hwnd = reinterpret_cast<HWND>(dummy_activation_window);
1710 // This may happen as a result of a race condition when the plugin is going
1712 wchar_t window_title[MAX_PATH + 1] = {0};
1713 if (!IsWindow(hwnd) ||
1714 !GetWindowText(hwnd, window_title, arraysize(window_title)) ||
1715 lstrcmpiW(window_title, kDummyActivationWindowName) != 0) {
1719 #if defined(USE_AURA)
1721 reinterpret_cast<HWND>(view_->GetParentForWindowlessPlugin()));
1723 SetParent(hwnd, reinterpret_cast<HWND>(GetNativeViewId()));
1725 dummy_windows_for_activation_.push_back(hwnd);
1728 void RenderWidgetHostImpl::OnWindowlessPluginDummyWindowDestroyed(
1729 gfx::NativeViewId dummy_activation_window) {
1730 HWND hwnd = reinterpret_cast<HWND>(dummy_activation_window);
1731 std::list<HWND>::iterator i = dummy_windows_for_activation_.begin();
1732 for (; i != dummy_windows_for_activation_.end(); ++i) {
1734 dummy_windows_for_activation_.erase(i);
1738 NOTREACHED() << "Unknown dummy window";
1742 void RenderWidgetHostImpl::SetIgnoreInputEvents(bool ignore_input_events) {
1743 ignore_input_events_ = ignore_input_events;
1746 bool RenderWidgetHostImpl::KeyPressListenersHandleEvent(
1747 const NativeWebKeyboardEvent& event) {
1748 if (event.skip_in_browser || event.type != WebKeyboardEvent::RawKeyDown)
1751 for (size_t i = 0; i < key_press_event_callbacks_.size(); i++) {
1752 size_t original_size = key_press_event_callbacks_.size();
1753 if (key_press_event_callbacks_[i].Run(event))
1756 // Check whether the callback that just ran removed itself, in which case
1757 // the iterator needs to be decremented to properly account for the removal.
1758 size_t current_size = key_press_event_callbacks_.size();
1759 if (current_size != original_size) {
1760 DCHECK_EQ(original_size - 1, current_size);
1768 InputEventAckState RenderWidgetHostImpl::FilterInputEvent(
1769 const blink::WebInputEvent& event, const ui::LatencyInfo& latency_info) {
1770 // Don't ignore touch cancel events, since they may be sent while input
1771 // events are being ignored in order to keep the renderer from getting
1772 // confused about how many touches are active.
1773 if (IgnoreInputEvents() && event.type != WebInputEvent::TouchCancel)
1774 return INPUT_EVENT_ACK_STATE_NO_CONSUMER_EXISTS;
1776 if (!process_->HasConnection())
1777 return INPUT_EVENT_ACK_STATE_UNKNOWN;
1779 if (event.type == WebInputEvent::MouseDown)
1782 return view_ ? view_->FilterInputEvent(event)
1783 : INPUT_EVENT_ACK_STATE_NOT_CONSUMED;
1786 void RenderWidgetHostImpl::IncrementInFlightEventCount() {
1787 StartHangMonitorTimeout(
1788 TimeDelta::FromMilliseconds(hung_renderer_delay_ms_));
1789 increment_in_flight_event_count();
1792 void RenderWidgetHostImpl::DecrementInFlightEventCount() {
1793 DCHECK_GE(in_flight_event_count_, 0);
1794 // Cancel pending hung renderer checks since the renderer is responsive.
1795 if (decrement_in_flight_event_count() <= 0)
1796 StopHangMonitorTimeout();
1799 void RenderWidgetHostImpl::OnHasTouchEventHandlers(bool has_handlers) {
1800 has_touch_handler_ = has_handlers;
1803 void RenderWidgetHostImpl::DidFlush() {
1804 if (synthetic_gesture_controller_)
1805 synthetic_gesture_controller_->OnDidFlushInput();
1807 view_->OnDidFlushInput();
1810 void RenderWidgetHostImpl::DidOverscroll(const DidOverscrollParams& params) {
1812 view_->DidOverscroll(params);
1815 void RenderWidgetHostImpl::OnKeyboardEventAck(
1816 const NativeWebKeyboardEvent& event,
1817 InputEventAckState ack_result) {
1818 #if defined(OS_MACOSX)
1819 if (!is_hidden() && view_ && view_->PostProcessEventForPluginIme(event))
1823 // We only send unprocessed key event upwards if we are not hidden,
1824 // because the user has moved away from us and no longer expect any effect
1825 // of this key event.
1826 const bool processed = (INPUT_EVENT_ACK_STATE_CONSUMED == ack_result);
1827 if (delegate_ && !processed && !is_hidden() && !event.skip_in_browser) {
1828 delegate_->HandleKeyboardEvent(event);
1830 // WARNING: This RenderWidgetHostImpl can be deallocated at this point
1831 // (i.e. in the case of Ctrl+W, where the call to
1832 // HandleKeyboardEvent destroys this RenderWidgetHostImpl).
1836 void RenderWidgetHostImpl::OnWheelEventAck(
1837 const MouseWheelEventWithLatencyInfo& wheel_event,
1838 InputEventAckState ack_result) {
1839 if (!wheel_event.latency.FindLatency(
1840 ui::INPUT_EVENT_LATENCY_RENDERING_SCHEDULED_COMPONENT, 0, NULL)) {
1841 // MouseWheelEvent latency ends when it is acked but does not cause any
1842 // rendering scheduled.
1843 ui::LatencyInfo latency = wheel_event.latency;
1844 latency.AddLatencyNumber(
1845 ui::INPUT_EVENT_LATENCY_TERMINATED_MOUSE_COMPONENT, 0, 0);
1848 if (!is_hidden() && view_) {
1849 if (ack_result != INPUT_EVENT_ACK_STATE_CONSUMED &&
1850 delegate_->HandleWheelEvent(wheel_event.event)) {
1851 ack_result = INPUT_EVENT_ACK_STATE_CONSUMED;
1853 view_->WheelEventAck(wheel_event.event, ack_result);
1857 void RenderWidgetHostImpl::OnGestureEventAck(
1858 const GestureEventWithLatencyInfo& event,
1859 InputEventAckState ack_result) {
1860 if (!event.latency.FindLatency(
1861 ui::INPUT_EVENT_LATENCY_RENDERING_SCHEDULED_COMPONENT, 0, NULL)) {
1862 // GestureEvent latency ends when it is acked but does not cause any
1863 // rendering scheduled.
1864 ui::LatencyInfo latency = event.latency;
1865 latency.AddLatencyNumber(
1866 ui::INPUT_EVENT_LATENCY_TERMINATED_GESTURE_COMPONENT, 0 ,0);
1869 if (ack_result != INPUT_EVENT_ACK_STATE_CONSUMED) {
1870 if (delegate_->HandleGestureEvent(event.event))
1871 ack_result = INPUT_EVENT_ACK_STATE_CONSUMED;
1875 view_->GestureEventAck(event.event, ack_result);
1878 void RenderWidgetHostImpl::OnTouchEventAck(
1879 const TouchEventWithLatencyInfo& event,
1880 InputEventAckState ack_result) {
1881 TouchEventWithLatencyInfo touch_event = event;
1882 touch_event.latency.AddLatencyNumber(
1883 ui::INPUT_EVENT_LATENCY_ACKED_TOUCH_COMPONENT, 0, 0);
1884 // TouchEvent latency ends at ack if it didn't cause any rendering.
1885 if (!touch_event.latency.FindLatency(
1886 ui::INPUT_EVENT_LATENCY_RENDERING_SCHEDULED_COMPONENT, 0, NULL)) {
1887 touch_event.latency.AddLatencyNumber(
1888 ui::INPUT_EVENT_LATENCY_TERMINATED_TOUCH_COMPONENT, 0, 0);
1890 ComputeTouchLatency(touch_event.latency);
1892 if (touch_emulator_ && touch_emulator_->HandleTouchEventAck(ack_result))
1896 view_->ProcessAckedTouchEvent(touch_event, ack_result);
1899 void RenderWidgetHostImpl::OnUnexpectedEventAck(UnexpectedEventAckType type) {
1900 if (type == BAD_ACK_MESSAGE) {
1901 RecordAction(base::UserMetricsAction("BadMessageTerminate_RWH2"));
1902 process_->ReceivedBadMessage();
1903 } else if (type == UNEXPECTED_EVENT_TYPE) {
1904 suppress_next_char_events_ = false;
1908 void RenderWidgetHostImpl::OnSyntheticGestureCompleted(
1909 SyntheticGesture::Result result) {
1910 Send(new InputMsg_SyntheticGestureCompleted(GetRoutingID()));
1913 const gfx::Vector2d& RenderWidgetHostImpl::GetLastScrollOffset() const {
1914 return last_scroll_offset_;
1917 bool RenderWidgetHostImpl::IgnoreInputEvents() const {
1918 return ignore_input_events_ || process_->IgnoreInputEvents();
1921 bool RenderWidgetHostImpl::ShouldForwardTouchEvent() const {
1922 return input_router_->ShouldForwardTouchEvent();
1925 void RenderWidgetHostImpl::StartUserGesture() {
1929 void RenderWidgetHostImpl::Stop() {
1930 Send(new ViewMsg_Stop(GetRoutingID()));
1933 void RenderWidgetHostImpl::SetBackgroundOpaque(bool opaque) {
1934 Send(new ViewMsg_SetBackgroundOpaque(GetRoutingID(), opaque));
1937 void RenderWidgetHostImpl::SetEditCommandsForNextKeyEvent(
1938 const std::vector<EditCommand>& commands) {
1939 Send(new InputMsg_SetEditCommandsForNextKeyEvent(GetRoutingID(), commands));
1942 void RenderWidgetHostImpl::AddAccessibilityMode(AccessibilityMode mode) {
1943 SetAccessibilityMode(
1944 content::AddAccessibilityModeTo(accessibility_mode_, mode));
1947 void RenderWidgetHostImpl::RemoveAccessibilityMode(AccessibilityMode mode) {
1948 SetAccessibilityMode(
1949 content::RemoveAccessibilityModeFrom(accessibility_mode_, mode));
1952 void RenderWidgetHostImpl::ResetAccessibilityMode() {
1953 SetAccessibilityMode(
1954 BrowserAccessibilityStateImpl::GetInstance()->accessibility_mode());
1957 void RenderWidgetHostImpl::SetAccessibilityMode(AccessibilityMode mode) {
1958 accessibility_mode_ = mode;
1959 Send(new ViewMsg_SetAccessibilityMode(GetRoutingID(), mode));
1962 void RenderWidgetHostImpl::AccessibilitySetFocus(int object_id) {
1963 Send(new AccessibilityMsg_SetFocus(GetRoutingID(), object_id));
1964 view_->OnAccessibilitySetFocus(object_id);
1967 void RenderWidgetHostImpl::AccessibilityDoDefaultAction(int object_id) {
1968 Send(new AccessibilityMsg_DoDefaultAction(GetRoutingID(), object_id));
1971 void RenderWidgetHostImpl::AccessibilityShowMenu(int object_id) {
1972 view_->AccessibilityShowMenu(object_id);
1975 void RenderWidgetHostImpl::AccessibilityScrollToMakeVisible(
1976 int acc_obj_id, gfx::Rect subfocus) {
1977 Send(new AccessibilityMsg_ScrollToMakeVisible(
1978 GetRoutingID(), acc_obj_id, subfocus));
1981 void RenderWidgetHostImpl::AccessibilityScrollToPoint(
1982 int acc_obj_id, gfx::Point point) {
1983 Send(new AccessibilityMsg_ScrollToPoint(
1984 GetRoutingID(), acc_obj_id, point));
1987 void RenderWidgetHostImpl::AccessibilitySetTextSelection(
1988 int object_id, int start_offset, int end_offset) {
1989 Send(new AccessibilityMsg_SetTextSelection(
1990 GetRoutingID(), object_id, start_offset, end_offset));
1993 bool RenderWidgetHostImpl::AccessibilityViewHasFocus() const {
1994 return view_->HasFocus();
1997 gfx::Rect RenderWidgetHostImpl::AccessibilityGetViewBounds() const {
1998 return view_->GetViewBounds();
2001 gfx::Point RenderWidgetHostImpl::AccessibilityOriginInScreen(
2002 const gfx::Rect& bounds) const {
2003 return view_->AccessibilityOriginInScreen(bounds);
2006 void RenderWidgetHostImpl::AccessibilityHitTest(const gfx::Point& point) {
2007 Send(new AccessibilityMsg_HitTest(GetRoutingID(), point));
2010 void RenderWidgetHostImpl::AccessibilityFatalError() {
2011 Send(new AccessibilityMsg_FatalError(GetRoutingID()));
2012 view_->SetBrowserAccessibilityManager(NULL);
2016 void RenderWidgetHostImpl::SetParentNativeViewAccessible(
2017 gfx::NativeViewAccessible accessible_parent) {
2019 view_->SetParentNativeViewAccessible(accessible_parent);
2022 gfx::NativeViewAccessible
2023 RenderWidgetHostImpl::GetParentNativeViewAccessible() const {
2024 return delegate_->GetParentNativeViewAccessible();
2028 void RenderWidgetHostImpl::ExecuteEditCommand(const std::string& command,
2029 const std::string& value) {
2030 Send(new InputMsg_ExecuteEditCommand(GetRoutingID(), command, value));
2033 void RenderWidgetHostImpl::ScrollFocusedEditableNodeIntoRect(
2034 const gfx::Rect& rect) {
2035 Send(new InputMsg_ScrollFocusedEditableNodeIntoRect(GetRoutingID(), rect));
2038 void RenderWidgetHostImpl::MoveCaret(const gfx::Point& point) {
2039 Send(new InputMsg_MoveCaret(GetRoutingID(), point));
2042 bool RenderWidgetHostImpl::GotResponseToLockMouseRequest(bool allowed) {
2044 RejectMouseLockOrUnlockIfNecessary();
2047 if (!pending_mouse_lock_request_) {
2048 // This is possible, e.g., the plugin sends us an unlock request before
2049 // the user allows to lock to mouse.
2053 pending_mouse_lock_request_ = false;
2054 if (!view_ || !view_->HasFocus()|| !view_->LockMouse()) {
2055 Send(new ViewMsg_LockMouse_ACK(routing_id_, false));
2058 Send(new ViewMsg_LockMouse_ACK(routing_id_, true));
2065 void RenderWidgetHostImpl::AcknowledgeBufferPresent(
2066 int32 route_id, int gpu_host_id,
2067 const AcceleratedSurfaceMsg_BufferPresented_Params& params) {
2068 GpuProcessHostUIShim* ui_shim = GpuProcessHostUIShim::FromID(gpu_host_id);
2070 ui_shim->Send(new AcceleratedSurfaceMsg_BufferPresented(route_id,
2076 void RenderWidgetHostImpl::SendSwapCompositorFrameAck(
2078 uint32 output_surface_id,
2079 int renderer_host_id,
2080 const cc::CompositorFrameAck& ack) {
2081 RenderProcessHost* host = RenderProcessHost::FromID(renderer_host_id);
2084 host->Send(new ViewMsg_SwapCompositorFrameAck(
2085 route_id, output_surface_id, ack));
2089 void RenderWidgetHostImpl::SendReclaimCompositorResources(
2091 uint32 output_surface_id,
2092 int renderer_host_id,
2093 const cc::CompositorFrameAck& ack) {
2094 RenderProcessHost* host = RenderProcessHost::FromID(renderer_host_id);
2098 new ViewMsg_ReclaimCompositorResources(route_id, output_surface_id, ack));
2101 void RenderWidgetHostImpl::DelayedAutoResized() {
2102 gfx::Size new_size = new_auto_size_;
2103 // Clear the new_auto_size_ since the empty value is used as a flag to
2104 // indicate that no callback is in progress (i.e. without this line
2105 // DelayedAutoResized will not get called again).
2106 new_auto_size_.SetSize(0, 0);
2107 if (!should_auto_resize_)
2110 OnRenderAutoResized(new_size);
2113 void RenderWidgetHostImpl::DetachDelegate() {
2117 void RenderWidgetHostImpl::ComputeTouchLatency(
2118 const ui::LatencyInfo& latency_info) {
2119 ui::LatencyInfo::LatencyComponent ui_component;
2120 ui::LatencyInfo::LatencyComponent rwh_component;
2121 ui::LatencyInfo::LatencyComponent acked_component;
2123 if (!latency_info.FindLatency(ui::INPUT_EVENT_LATENCY_UI_COMPONENT,
2126 !latency_info.FindLatency(ui::INPUT_EVENT_LATENCY_BEGIN_RWH_COMPONENT,
2127 GetLatencyComponentId(),
2131 DCHECK(ui_component.event_count == 1);
2132 DCHECK(rwh_component.event_count == 1);
2134 base::TimeDelta ui_delta =
2135 rwh_component.event_time - ui_component.event_time;
2136 UMA_HISTOGRAM_CUSTOM_COUNTS(
2137 "Event.Latency.Browser.TouchUI",
2138 ui_delta.InMicroseconds(),
2143 if (latency_info.FindLatency(ui::INPUT_EVENT_LATENCY_ACKED_TOUCH_COMPONENT,
2145 &acked_component)) {
2146 DCHECK(acked_component.event_count == 1);
2147 base::TimeDelta acked_delta =
2148 acked_component.event_time - rwh_component.event_time;
2149 UMA_HISTOGRAM_CUSTOM_COUNTS(
2150 "Event.Latency.Browser.TouchAcked",
2151 acked_delta.InMicroseconds(),
2158 void RenderWidgetHostImpl::FrameSwapped(const ui::LatencyInfo& latency_info) {
2159 ui::LatencyInfo::LatencyComponent window_snapshot_component;
2160 if (latency_info.FindLatency(ui::WINDOW_SNAPSHOT_FRAME_NUMBER_COMPONENT,
2161 GetLatencyComponentId(),
2162 &window_snapshot_component)) {
2163 WindowSnapshotReachedScreen(
2164 static_cast<int>(window_snapshot_component.sequence_number));
2167 ui::LatencyInfo::LatencyComponent rwh_component;
2168 ui::LatencyInfo::LatencyComponent swap_component;
2169 if (!latency_info.FindLatency(ui::INPUT_EVENT_LATENCY_BEGIN_RWH_COMPONENT,
2170 GetLatencyComponentId(),
2172 !latency_info.FindLatency(
2173 ui::INPUT_EVENT_LATENCY_TERMINATED_FRAME_SWAP_COMPONENT,
2174 0, &swap_component)) {
2178 ui::LatencyInfo::LatencyComponent original_component;
2179 if (latency_info.FindLatency(
2180 ui::INPUT_EVENT_LATENCY_SCROLL_UPDATE_ORIGINAL_COMPONENT,
2181 GetLatencyComponentId(),
2182 &original_component)) {
2183 // This UMA metric tracks the time from when the original touch event is
2184 // created (averaged if there are multiple) to when the scroll gesture
2185 // results in final frame swap.
2186 base::TimeDelta delta =
2187 swap_component.event_time - original_component.event_time;
2188 for (size_t i = 0; i < original_component.event_count; i++) {
2189 UMA_HISTOGRAM_CUSTOM_COUNTS(
2190 "Event.Latency.TouchToScrollUpdateSwap",
2191 delta.InMicroseconds(),
2199 void RenderWidgetHostImpl::DidReceiveRendererFrame() {
2200 view_->DidReceiveRendererFrame();
2203 void RenderWidgetHostImpl::WindowSnapshotAsyncCallback(
2206 gfx::Size snapshot_size,
2207 scoped_refptr<base::RefCountedBytes> png_data) {
2209 std::vector<unsigned char> png_vector;
2210 Send(new ViewMsg_WindowSnapshotCompleted(
2211 routing_id, snapshot_id, gfx::Size(), png_vector));
2215 Send(new ViewMsg_WindowSnapshotCompleted(
2216 routing_id, snapshot_id, snapshot_size, png_data->data()));
2219 void RenderWidgetHostImpl::WindowSnapshotReachedScreen(int snapshot_id) {
2220 DCHECK(base::MessageLoopForUI::IsCurrent());
2222 std::vector<unsigned char> png;
2224 // This feature is behind the kEnableGpuBenchmarking command line switch
2225 // because it poses security concerns and should only be used for testing.
2226 const CommandLine& command_line = *CommandLine::ForCurrentProcess();
2227 if (!command_line.HasSwitch(cc::switches::kEnableGpuBenchmarking)) {
2228 Send(new ViewMsg_WindowSnapshotCompleted(
2229 GetRoutingID(), snapshot_id, gfx::Size(), png));
2233 gfx::Rect view_bounds = GetView()->GetViewBounds();
2234 gfx::Rect snapshot_bounds(view_bounds.size());
2235 gfx::Size snapshot_size = snapshot_bounds.size();
2237 if (ui::GrabViewSnapshot(
2238 GetView()->GetNativeView(), &png, snapshot_bounds)) {
2239 Send(new ViewMsg_WindowSnapshotCompleted(
2240 GetRoutingID(), snapshot_id, snapshot_size, png));
2244 ui::GrabViewSnapshotAsync(
2245 GetView()->GetNativeView(),
2247 base::ThreadTaskRunnerHandle::Get(),
2248 base::Bind(&RenderWidgetHostImpl::WindowSnapshotAsyncCallback,
2249 weak_factory_.GetWeakPtr(),
2256 void RenderWidgetHostImpl::CompositorFrameDrawn(
2257 const std::vector<ui::LatencyInfo>& latency_info) {
2258 for (size_t i = 0; i < latency_info.size(); i++) {
2259 std::set<RenderWidgetHostImpl*> rwhi_set;
2260 for (ui::LatencyInfo::LatencyMap::const_iterator b =
2261 latency_info[i].latency_components.begin();
2262 b != latency_info[i].latency_components.end();
2264 if (b->first.first == ui::INPUT_EVENT_LATENCY_BEGIN_RWH_COMPONENT ||
2265 b->first.first == ui::WINDOW_SNAPSHOT_FRAME_NUMBER_COMPONENT) {
2266 // Matches with GetLatencyComponentId
2267 int routing_id = b->first.second & 0xffffffff;
2268 int process_id = (b->first.second >> 32) & 0xffffffff;
2269 RenderWidgetHost* rwh =
2270 RenderWidgetHost::FromID(process_id, routing_id);
2274 RenderWidgetHostImpl* rwhi = RenderWidgetHostImpl::From(rwh);
2275 if (rwhi_set.insert(rwhi).second)
2276 rwhi->FrameSwapped(latency_info[i]);
2282 void RenderWidgetHostImpl::AddLatencyInfoComponentIds(
2283 ui::LatencyInfo* latency_info) {
2284 ui::LatencyInfo::LatencyMap new_components;
2285 ui::LatencyInfo::LatencyMap::iterator lc =
2286 latency_info->latency_components.begin();
2287 while (lc != latency_info->latency_components.end()) {
2288 ui::LatencyComponentType component_type = lc->first.first;
2289 if (component_type == ui::WINDOW_SNAPSHOT_FRAME_NUMBER_COMPONENT) {
2290 // Generate a new component entry with the correct component ID
2291 ui::LatencyInfo::LatencyMap::key_type key =
2292 std::make_pair(component_type, GetLatencyComponentId());
2293 new_components[key] = lc->second;
2295 // Remove the old entry
2296 latency_info->latency_components.erase(lc++);
2302 // Add newly generated components into the latency info
2303 for (lc = new_components.begin(); lc != new_components.end(); ++lc) {
2304 latency_info->latency_components[lc->first] = lc->second;
2308 SkBitmap::Config RenderWidgetHostImpl::PreferredReadbackFormat() {
2310 return view_->PreferredReadbackFormat();
2311 return SkBitmap::kARGB_8888_Config;
2314 } // namespace content