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/browser/renderer_host/render_widget_resize_helper.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 "content/public/common/web_preferences.h"
63 #include "skia/ext/image_operations.h"
64 #include "skia/ext/platform_canvas.h"
65 #include "third_party/WebKit/public/web/WebCompositionUnderline.h"
66 #include "ui/events/event.h"
67 #include "ui/events/keycodes/keyboard_codes.h"
68 #include "ui/gfx/size_conversions.h"
69 #include "ui/gfx/skbitmap_operations.h"
70 #include "ui/gfx/vector2d_conversions.h"
71 #include "ui/snapshot/snapshot.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 typedef std::pair<int32, int32> RenderWidgetHostID;
93 typedef base::hash_map<RenderWidgetHostID, RenderWidgetHostImpl*>
95 base::LazyInstance<RoutingIDWidgetMap> g_routing_id_widget_map =
96 LAZY_INSTANCE_INITIALIZER;
98 int GetInputRouterViewFlagsFromCompositorFrameMetadata(
99 const cc::CompositorFrameMetadata metadata) {
100 int view_flags = InputRouter::VIEW_FLAGS_NONE;
102 if (metadata.min_page_scale_factor == metadata.max_page_scale_factor)
103 view_flags |= InputRouter::FIXED_PAGE_SCALE;
105 const float window_width_dip = std::ceil(
106 metadata.page_scale_factor * metadata.scrollable_viewport_size.width());
107 const float content_width_css = metadata.root_layer_size.width();
108 if (content_width_css <= window_width_dip)
109 view_flags |= InputRouter::MOBILE_VIEWPORT;
114 // Implements the RenderWidgetHostIterator interface. It keeps a list of
115 // RenderWidgetHosts, and makes sure it returns a live RenderWidgetHost at each
116 // iteration (or NULL if there isn't any left).
117 class RenderWidgetHostIteratorImpl : public RenderWidgetHostIterator {
119 RenderWidgetHostIteratorImpl()
120 : current_index_(0) {
123 virtual ~RenderWidgetHostIteratorImpl() {
126 void Add(RenderWidgetHost* host) {
127 hosts_.push_back(RenderWidgetHostID(host->GetProcess()->GetID(),
128 host->GetRoutingID()));
131 // RenderWidgetHostIterator:
132 virtual RenderWidgetHost* GetNextHost() OVERRIDE {
133 RenderWidgetHost* host = NULL;
134 while (current_index_ < hosts_.size() && !host) {
135 RenderWidgetHostID id = hosts_[current_index_];
136 host = RenderWidgetHost::FromID(id.first, id.second);
143 std::vector<RenderWidgetHostID> hosts_;
144 size_t current_index_;
146 DISALLOW_COPY_AND_ASSIGN(RenderWidgetHostIteratorImpl);
151 ///////////////////////////////////////////////////////////////////////////////
152 // RenderWidgetHostImpl
154 RenderWidgetHostImpl::RenderWidgetHostImpl(RenderWidgetHostDelegate* delegate,
155 RenderProcessHost* process,
159 renderer_initialized_(false),
160 hung_renderer_delay_ms_(kHungRendererDelayMs),
163 routing_id_(routing_id),
167 is_fullscreen_(false),
168 repaint_ack_pending_(false),
169 resize_ack_pending_(false),
170 screen_info_out_of_date_(false),
171 top_controls_layout_height_(0.f),
172 should_auto_resize_(false),
173 waiting_for_screen_rects_ack_(false),
174 needs_repainting_on_restore_(false),
175 is_unresponsive_(false),
176 in_flight_event_count_(0),
177 in_get_backing_store_(false),
178 ignore_input_events_(false),
179 input_method_active_(false),
180 text_direction_updated_(false),
181 text_direction_(blink::WebTextDirectionLeftToRight),
182 text_direction_canceled_(false),
183 suppress_next_char_events_(false),
184 pending_mouse_lock_request_(false),
185 allow_privileged_mouse_lock_(false),
186 has_touch_handler_(false),
187 last_input_number_(static_cast<int64>(GetProcess()->GetID()) << 32),
188 next_browser_snapshot_id_(1),
189 weak_factory_(this) {
191 if (routing_id_ == MSG_ROUTING_NONE) {
192 routing_id_ = process_->GetNextRoutingID();
193 surface_id_ = GpuSurfaceTracker::Get()->AddSurfaceForRenderer(
197 // TODO(piman): This is a O(N) lookup, where we could forward the
198 // information from the RenderWidgetHelper. The problem is that doing so
199 // currently leaks outside of content all the way to chrome classes, and
200 // would be a layering violation. Since we don't expect more than a few
201 // hundreds of RWH, this seems acceptable. Revisit if performance become a
202 // problem, for example by tracking in the RenderWidgetHelper the routing id
203 // (and surface id) that have been created, but whose RWH haven't yet.
204 surface_id_ = GpuSurfaceTracker::Get()->LookupSurfaceForRenderer(
210 std::pair<RoutingIDWidgetMap::iterator, bool> result =
211 g_routing_id_widget_map.Get().insert(std::make_pair(
212 RenderWidgetHostID(process->GetID(), routing_id_), this));
213 CHECK(result.second) << "Inserting a duplicate item!";
214 process_->AddRoute(routing_id_, this);
216 // If we're initially visible, tell the process host that we're alive.
217 // Otherwise we'll notify the process host when we are first shown.
219 process_->WidgetRestored();
221 input_router_.reset(new InputRouterImpl(
222 process_, this, this, routing_id_, GetInputRouterConfigForPlatform()));
224 touch_emulator_.reset();
226 RenderViewHostImpl* rvh = static_cast<RenderViewHostImpl*>(
227 IsRenderView() ? RenderViewHost::From(this) : NULL);
228 if (BrowserPluginGuest::IsGuest(rvh) ||
229 !base::CommandLine::ForCurrentProcess()->HasSwitch(
230 switches::kDisableHangMonitor)) {
231 hang_monitor_timeout_.reset(new TimeoutMonitor(
232 base::Bind(&RenderWidgetHostImpl::RendererIsUnresponsive,
233 weak_factory_.GetWeakPtr())));
237 RenderWidgetHostImpl::~RenderWidgetHostImpl() {
239 view_weak_->RenderWidgetHostGone();
242 GpuSurfaceTracker::Get()->RemoveSurface(surface_id_);
245 process_->RemoveRoute(routing_id_);
246 g_routing_id_widget_map.Get().erase(
247 RenderWidgetHostID(process_->GetID(), routing_id_));
250 delegate_->RenderWidgetDeleted(this);
254 RenderWidgetHost* RenderWidgetHost::FromID(
257 return RenderWidgetHostImpl::FromID(process_id, routing_id);
261 RenderWidgetHostImpl* RenderWidgetHostImpl::FromID(
264 DCHECK_CURRENTLY_ON(BrowserThread::UI);
265 RoutingIDWidgetMap* widgets = g_routing_id_widget_map.Pointer();
266 RoutingIDWidgetMap::iterator it = widgets->find(
267 RenderWidgetHostID(process_id, routing_id));
268 return it == widgets->end() ? NULL : it->second;
272 scoped_ptr<RenderWidgetHostIterator> RenderWidgetHost::GetRenderWidgetHosts() {
273 RenderWidgetHostIteratorImpl* hosts = new RenderWidgetHostIteratorImpl();
274 RoutingIDWidgetMap* widgets = g_routing_id_widget_map.Pointer();
275 for (RoutingIDWidgetMap::const_iterator it = widgets->begin();
276 it != widgets->end();
278 RenderWidgetHost* widget = it->second;
280 if (!widget->IsRenderView()) {
285 // Add only active RenderViewHosts.
286 RenderViewHost* rvh = RenderViewHost::From(widget);
287 if (RenderViewHostImpl::IsRVHStateActive(
288 static_cast<RenderViewHostImpl*>(rvh)->rvh_state()))
292 return scoped_ptr<RenderWidgetHostIterator>(hosts);
296 scoped_ptr<RenderWidgetHostIterator>
297 RenderWidgetHostImpl::GetAllRenderWidgetHosts() {
298 RenderWidgetHostIteratorImpl* hosts = new RenderWidgetHostIteratorImpl();
299 RoutingIDWidgetMap* widgets = g_routing_id_widget_map.Pointer();
300 for (RoutingIDWidgetMap::const_iterator it = widgets->begin();
301 it != widgets->end();
303 hosts->Add(it->second);
306 return scoped_ptr<RenderWidgetHostIterator>(hosts);
310 RenderWidgetHostImpl* RenderWidgetHostImpl::From(RenderWidgetHost* rwh) {
311 return rwh->AsRenderWidgetHostImpl();
314 void RenderWidgetHostImpl::SetView(RenderWidgetHostViewBase* view) {
316 view_weak_ = view->GetWeakPtr();
321 GpuSurfaceTracker::Get()->SetSurfaceHandle(
322 surface_id_, GetCompositingSurface());
324 synthetic_gesture_controller_.reset();
327 RenderProcessHost* RenderWidgetHostImpl::GetProcess() const {
331 int RenderWidgetHostImpl::GetRoutingID() const {
335 RenderWidgetHostView* RenderWidgetHostImpl::GetView() const {
339 RenderWidgetHostImpl* RenderWidgetHostImpl::AsRenderWidgetHostImpl() {
343 gfx::NativeViewId RenderWidgetHostImpl::GetNativeViewId() const {
345 return view_->GetNativeViewId();
349 gfx::GLSurfaceHandle RenderWidgetHostImpl::GetCompositingSurface() {
351 return view_->GetCompositingSurface();
352 return gfx::GLSurfaceHandle();
355 void RenderWidgetHostImpl::ResetSizeAndRepaintPendingFlags() {
356 resize_ack_pending_ = false;
357 if (repaint_ack_pending_) {
358 TRACE_EVENT_ASYNC_END0(
359 "renderer_host", "RenderWidgetHostImpl::repaint_ack_pending_", this);
361 repaint_ack_pending_ = false;
362 last_requested_size_.SetSize(0, 0);
365 void RenderWidgetHostImpl::SendScreenRects() {
366 if (!renderer_initialized_ || waiting_for_screen_rects_ack_)
370 // On GTK, this comes in for backgrounded tabs. Ignore, to match what
371 // happens on Win & Mac, and when the view is shown it'll call this again.
378 last_view_screen_rect_ = view_->GetViewBounds();
379 last_window_screen_rect_ = view_->GetBoundsInRootWindow();
380 Send(new ViewMsg_UpdateScreenRects(
381 GetRoutingID(), last_view_screen_rect_, last_window_screen_rect_));
383 delegate_->DidSendScreenRects(this);
384 waiting_for_screen_rects_ack_ = true;
387 void RenderWidgetHostImpl::SuppressNextCharEvents() {
388 suppress_next_char_events_ = true;
391 void RenderWidgetHostImpl::FlushInput() {
392 input_router_->Flush();
393 if (synthetic_gesture_controller_)
394 synthetic_gesture_controller_->Flush(base::TimeTicks::Now());
397 void RenderWidgetHostImpl::SetNeedsFlush() {
399 view_->OnSetNeedsFlushInput();
402 void RenderWidgetHostImpl::Init() {
403 DCHECK(process_->HasConnection());
405 renderer_initialized_ = true;
407 GpuSurfaceTracker::Get()->SetSurfaceHandle(
408 surface_id_, GetCompositingSurface());
410 // Send the ack along with the information on placement.
411 Send(new ViewMsg_CreatingNew_ACK(routing_id_));
412 GetProcess()->ResumeRequestsForView(routing_id_);
417 void RenderWidgetHostImpl::Shutdown() {
418 RejectMouseLockOrUnlockIfNecessary();
420 if (process_->HasConnection()) {
421 // Tell the renderer object to close.
422 bool rv = Send(new ViewMsg_Close(routing_id_));
429 bool RenderWidgetHostImpl::IsLoading() const {
433 bool RenderWidgetHostImpl::IsRenderView() const {
437 bool RenderWidgetHostImpl::OnMessageReceived(const IPC::Message &msg) {
439 IPC_BEGIN_MESSAGE_MAP(RenderWidgetHostImpl, msg)
440 IPC_MESSAGE_HANDLER(InputHostMsg_QueueSyntheticGesture,
441 OnQueueSyntheticGesture)
442 IPC_MESSAGE_HANDLER(InputHostMsg_ImeCancelComposition,
443 OnImeCancelComposition)
444 IPC_MESSAGE_HANDLER(ViewHostMsg_RenderViewReady, OnRenderViewReady)
445 IPC_MESSAGE_HANDLER(ViewHostMsg_RenderProcessGone, OnRenderProcessGone)
446 IPC_MESSAGE_HANDLER(ViewHostMsg_Close, OnClose)
447 IPC_MESSAGE_HANDLER(ViewHostMsg_UpdateScreenRects_ACK,
448 OnUpdateScreenRectsAck)
449 IPC_MESSAGE_HANDLER(ViewHostMsg_RequestMove, OnRequestMove)
450 IPC_MESSAGE_HANDLER(ViewHostMsg_SetTooltipText, OnSetTooltipText)
451 IPC_MESSAGE_HANDLER_GENERIC(ViewHostMsg_SwapCompositorFrame,
452 OnSwapCompositorFrame(msg))
453 IPC_MESSAGE_HANDLER(ViewHostMsg_DidStopFlinging, OnFlingingStopped)
454 IPC_MESSAGE_HANDLER(ViewHostMsg_UpdateRect, OnUpdateRect)
455 IPC_MESSAGE_HANDLER(ViewHostMsg_Focus, OnFocus)
456 IPC_MESSAGE_HANDLER(ViewHostMsg_Blur, OnBlur)
457 IPC_MESSAGE_HANDLER(ViewHostMsg_SetCursor, OnSetCursor)
458 IPC_MESSAGE_HANDLER(ViewHostMsg_TextInputTypeChanged,
459 OnTextInputTypeChanged)
460 IPC_MESSAGE_HANDLER(ViewHostMsg_LockMouse, OnLockMouse)
461 IPC_MESSAGE_HANDLER(ViewHostMsg_UnlockMouse, OnUnlockMouse)
462 IPC_MESSAGE_HANDLER(ViewHostMsg_ShowDisambiguationPopup,
463 OnShowDisambiguationPopup)
464 IPC_MESSAGE_HANDLER(ViewHostMsg_SelectionChanged, OnSelectionChanged)
465 IPC_MESSAGE_HANDLER(ViewHostMsg_SelectionBoundsChanged,
466 OnSelectionBoundsChanged)
468 IPC_MESSAGE_HANDLER(ViewHostMsg_WindowlessPluginDummyWindowCreated,
469 OnWindowlessPluginDummyWindowCreated)
470 IPC_MESSAGE_HANDLER(ViewHostMsg_WindowlessPluginDummyWindowDestroyed,
471 OnWindowlessPluginDummyWindowDestroyed)
473 #if defined(OS_MACOSX) || defined(USE_AURA)
474 IPC_MESSAGE_HANDLER(InputHostMsg_ImeCompositionRangeChanged,
475 OnImeCompositionRangeChanged)
477 IPC_MESSAGE_UNHANDLED(handled = false)
478 IPC_END_MESSAGE_MAP()
480 if (!handled && input_router_ && input_router_->OnMessageReceived(msg))
483 if (!handled && view_ && view_->OnMessageReceived(msg))
489 bool RenderWidgetHostImpl::Send(IPC::Message* msg) {
490 if (IPC_MESSAGE_ID_CLASS(msg->type()) == InputMsgStart)
491 return input_router_->SendInput(make_scoped_ptr(msg));
493 return process_->Send(msg);
496 void RenderWidgetHostImpl::SetIsLoading(bool is_loading) {
497 is_loading_ = is_loading;
500 view_->SetIsLoading(is_loading);
503 void RenderWidgetHostImpl::WasHidden() {
509 // Don't bother reporting hung state when we aren't active.
510 StopHangMonitorTimeout();
512 // If we have a renderer, then inform it that we are being hidden so it can
513 // reduce its resource utilization.
514 Send(new ViewMsg_WasHidden(routing_id_));
516 // Tell the RenderProcessHost we were hidden.
517 process_->WidgetHidden();
519 bool is_visible = false;
520 NotificationService::current()->Notify(
521 NOTIFICATION_RENDER_WIDGET_VISIBILITY_CHANGED,
522 Source<RenderWidgetHost>(this),
523 Details<bool>(&is_visible));
526 void RenderWidgetHostImpl::WasShown(const ui::LatencyInfo& latency_info) {
533 // Always repaint on restore.
534 bool needs_repainting = true;
535 needs_repainting_on_restore_ = false;
536 Send(new ViewMsg_WasShown(routing_id_, needs_repainting, latency_info));
538 process_->WidgetRestored();
540 bool is_visible = true;
541 NotificationService::current()->Notify(
542 NOTIFICATION_RENDER_WIDGET_VISIBILITY_CHANGED,
543 Source<RenderWidgetHost>(this),
544 Details<bool>(&is_visible));
546 // It's possible for our size to be out of sync with the renderer. The
547 // following is one case that leads to this:
548 // 1. WasResized -> Send ViewMsg_Resize to render
549 // 2. WasResized -> do nothing as resize_ack_pending_ is true
551 // 4. OnUpdateRect from (1) processed. Does NOT invoke WasResized as view
552 // is hidden. Now renderer/browser out of sync with what they think size
554 // By invoking WasResized the renderer is updated as necessary. WasResized
555 // does nothing if the sizes are already in sync.
557 // TODO: ideally ViewMsg_WasShown would take a size. This way, the renderer
558 // could handle both the restore and resize at once. This isn't that big a
559 // deal as RenderWidget::WasShown delays updating, so that the resize from
560 // WasResized is usually processed before the renderer is painted.
564 void RenderWidgetHostImpl::WasResized() {
565 // Skip if the |delegate_| has already been detached because
566 // it's web contents is being deleted.
567 if (resize_ack_pending_ || !process_->HasConnection() || !view_ ||
568 !renderer_initialized_ || should_auto_resize_ || !delegate_) {
572 gfx::Size new_size(view_->GetRequestedRendererSize());
574 gfx::Size old_physical_backing_size = physical_backing_size_;
575 physical_backing_size_ = view_->GetPhysicalBackingSize();
576 bool was_fullscreen = is_fullscreen_;
577 is_fullscreen_ = IsFullscreen();
578 float old_top_controls_layout_height =
579 top_controls_layout_height_;
580 top_controls_layout_height_ =
581 view_->GetTopControlsLayoutHeight();
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_top_controls_layout_height !=
591 top_controls_layout_height_ ||
592 old_visible_viewport_size != visible_viewport_size_;
594 if (!size_changed && !side_payload_changed)
598 screen_info_.reset(new blink::WebScreenInfo);
599 GetWebScreenInfo(screen_info_.get());
602 // We don't expect to receive an ACK when the requested size or the physical
603 // backing size is empty, or when the main viewport size didn't change.
604 if (!new_size.IsEmpty() && !physical_backing_size_.IsEmpty() && size_changed)
605 resize_ack_pending_ = g_check_for_pending_resize_ack;
607 ViewMsg_Resize_Params params;
608 params.screen_info = *screen_info_;
609 params.new_size = new_size;
610 params.physical_backing_size = physical_backing_size_;
611 params.top_controls_layout_height = top_controls_layout_height_;
612 params.visible_viewport_size = visible_viewport_size_;
613 params.resizer_rect = GetRootWindowResizerRect();
614 params.is_fullscreen = is_fullscreen_;
615 if (!Send(new ViewMsg_Resize(routing_id_, params))) {
616 resize_ack_pending_ = false;
618 last_requested_size_ = new_size;
622 void RenderWidgetHostImpl::ResizeRectChanged(const gfx::Rect& new_rect) {
623 Send(new ViewMsg_ChangeResizeRect(routing_id_, new_rect));
626 void RenderWidgetHostImpl::GotFocus() {
630 void RenderWidgetHostImpl::Focus() {
631 Send(new InputMsg_SetFocus(routing_id_, true));
634 void RenderWidgetHostImpl::Blur() {
635 // If there is a pending mouse lock request, we don't want to reject it at
636 // this point. The user can switch focus back to this view and approve the
639 view_->UnlockMouse();
642 touch_emulator_->CancelTouch();
644 Send(new InputMsg_SetFocus(routing_id_, false));
647 void RenderWidgetHostImpl::LostCapture() {
649 touch_emulator_->CancelTouch();
651 Send(new InputMsg_MouseCaptureLost(routing_id_));
654 void RenderWidgetHostImpl::SetActive(bool active) {
655 Send(new ViewMsg_SetActive(routing_id_, active));
658 void RenderWidgetHostImpl::LostMouseLock() {
659 Send(new ViewMsg_MouseLockLost(routing_id_));
662 void RenderWidgetHostImpl::ViewDestroyed() {
663 RejectMouseLockOrUnlockIfNecessary();
665 // TODO(evanm): tracking this may no longer be necessary;
666 // eliminate this function if so.
670 void RenderWidgetHostImpl::CopyFromBackingStore(
671 const gfx::Rect& src_subrect,
672 const gfx::Size& accelerated_dst_size,
673 const base::Callback<void(bool, const SkBitmap&)>& callback,
674 const SkColorType color_type) {
676 TRACE_EVENT0("browser",
677 "RenderWidgetHostImpl::CopyFromBackingStore::FromCompositingSurface");
678 gfx::Rect accelerated_copy_rect = src_subrect.IsEmpty() ?
679 gfx::Rect(view_->GetViewBounds().size()) : src_subrect;
680 view_->CopyFromCompositingSurface(
681 accelerated_copy_rect, accelerated_dst_size, callback, color_type);
685 callback.Run(false, SkBitmap());
688 bool RenderWidgetHostImpl::CanCopyFromBackingStore() {
690 return view_->IsSurfaceAvailableForCopy();
694 #if defined(OS_ANDROID)
695 void RenderWidgetHostImpl::LockBackingStore() {
697 view_->LockCompositingSurface();
700 void RenderWidgetHostImpl::UnlockBackingStore() {
702 view_->UnlockCompositingSurface();
706 #if defined(OS_MACOSX)
707 void RenderWidgetHostImpl::PauseForPendingResizeOrRepaints() {
708 TRACE_EVENT0("browser",
709 "RenderWidgetHostImpl::PauseForPendingResizeOrRepaints");
711 if (!CanPauseForPendingResizeOrRepaints())
717 bool RenderWidgetHostImpl::CanPauseForPendingResizeOrRepaints() {
718 // Do not pause if the view is hidden.
722 // Do not pause if there is not a paint or resize already coming.
723 if (!repaint_ack_pending_ && !resize_ack_pending_)
729 void RenderWidgetHostImpl::WaitForSurface() {
730 TRACE_EVENT0("browser", "RenderWidgetHostImpl::WaitForSurface");
732 // How long to (synchronously) wait for the renderer to respond with a
733 // new frame when our current frame doesn't exist or is the wrong size.
734 // This timeout impacts the "choppiness" of our window resize.
735 const int kPaintMsgTimeoutMS = 50;
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 (RenderWidgetResizeHelper::Get()->WaitForSingleTaskToRun(max_delay)) {
796 // For auto-resized views, current_size_ determines the view_size and it
797 // may have changed during the handling of an UpdateRect message.
798 if (should_auto_resize_)
799 view_size = current_size_;
801 // Break now if we got a backing store or accelerated surface of the
803 if (view_->HasAcceleratedSurface(view_size))
806 TRACE_EVENT0("renderer_host", "WaitForSurface::Timeout");
810 // Loop if we still have time left and haven't gotten a properly sized
811 // BackingStore yet. This is necessary to support the GPU path which
812 // typically has multiple frames pipelined -- we may need to skip one or two
813 // BackingStore messages to get to the latest.
814 max_delay = end_time - TimeTicks::Now();
815 } 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::ForwardMouseEvent(const WebMouseEvent& mouse_event) {
852 ForwardMouseEventWithLatencyInfo(mouse_event, ui::LatencyInfo());
855 void RenderWidgetHostImpl::ForwardMouseEventWithLatencyInfo(
856 const blink::WebMouseEvent& mouse_event,
857 const ui::LatencyInfo& ui_latency) {
858 TRACE_EVENT2("input", "RenderWidgetHostImpl::ForwardMouseEvent",
859 "x", mouse_event.x, "y", mouse_event.y);
860 ui::LatencyInfo::InputCoordinate logical_coordinate(mouse_event.x,
863 ui::LatencyInfo latency_info = CreateRWHLatencyInfoIfNotExist(
864 &ui_latency, mouse_event.type, &logical_coordinate, 1);
866 for (size_t i = 0; i < mouse_event_callbacks_.size(); ++i) {
867 if (mouse_event_callbacks_[i].Run(mouse_event))
871 if (IgnoreInputEvents())
874 if (touch_emulator_ && touch_emulator_->HandleMouseEvent(mouse_event))
877 input_router_->SendMouseEvent(MouseEventWithLatencyInfo(mouse_event,
881 void RenderWidgetHostImpl::OnPointerEventActivate() {
884 void RenderWidgetHostImpl::ForwardWheelEvent(
885 const WebMouseWheelEvent& wheel_event) {
886 ForwardWheelEventWithLatencyInfo(wheel_event, ui::LatencyInfo());
889 void RenderWidgetHostImpl::ForwardWheelEventWithLatencyInfo(
890 const blink::WebMouseWheelEvent& wheel_event,
891 const ui::LatencyInfo& ui_latency) {
892 TRACE_EVENT0("input", "RenderWidgetHostImpl::ForwardWheelEvent");
894 ui::LatencyInfo::InputCoordinate logical_coordinate(wheel_event.x,
897 ui::LatencyInfo latency_info = CreateRWHLatencyInfoIfNotExist(
898 &ui_latency, wheel_event.type, &logical_coordinate, 1);
900 if (IgnoreInputEvents())
903 if (touch_emulator_ && touch_emulator_->HandleMouseWheelEvent(wheel_event))
906 input_router_->SendWheelEvent(MouseWheelEventWithLatencyInfo(wheel_event,
910 void RenderWidgetHostImpl::ForwardGestureEvent(
911 const blink::WebGestureEvent& gesture_event) {
912 ForwardGestureEventWithLatencyInfo(gesture_event, ui::LatencyInfo());
915 void RenderWidgetHostImpl::ForwardGestureEventWithLatencyInfo(
916 const blink::WebGestureEvent& gesture_event,
917 const ui::LatencyInfo& ui_latency) {
918 TRACE_EVENT0("input", "RenderWidgetHostImpl::ForwardGestureEvent");
919 // Early out if necessary, prior to performing latency logic.
920 if (IgnoreInputEvents())
923 if (delegate_->PreHandleGestureEvent(gesture_event))
926 ui::LatencyInfo::InputCoordinate logical_coordinate(gesture_event.x,
929 ui::LatencyInfo latency_info = CreateRWHLatencyInfoIfNotExist(
930 &ui_latency, gesture_event.type, &logical_coordinate, 1);
932 if (gesture_event.type == blink::WebInputEvent::GestureScrollUpdate) {
933 latency_info.AddLatencyNumber(
934 ui::INPUT_EVENT_LATENCY_SCROLL_UPDATE_RWH_COMPONENT,
935 GetLatencyComponentId(),
936 ++last_input_number_);
938 // Make a copy of the INPUT_EVENT_LATENCY_ORIGINAL_COMPONENT with a
939 // different name INPUT_EVENT_LATENCY_SCROLL_UPDATE_ORIGINAL_COMPONENT.
940 // So we can track the latency specifically for scroll update events.
941 ui::LatencyInfo::LatencyComponent original_component;
942 if (latency_info.FindLatency(ui::INPUT_EVENT_LATENCY_ORIGINAL_COMPONENT,
944 &original_component)) {
945 latency_info.AddLatencyNumberWithTimestamp(
946 ui::INPUT_EVENT_LATENCY_SCROLL_UPDATE_ORIGINAL_COMPONENT,
947 GetLatencyComponentId(),
948 original_component.sequence_number,
949 original_component.event_time,
950 original_component.event_count);
954 GestureEventWithLatencyInfo gesture_with_latency(gesture_event, latency_info);
955 input_router_->SendGestureEvent(gesture_with_latency);
958 void RenderWidgetHostImpl::ForwardEmulatedTouchEvent(
959 const blink::WebTouchEvent& touch_event) {
960 TRACE_EVENT0("input", "RenderWidgetHostImpl::ForwardEmulatedTouchEvent");
962 ui::LatencyInfo::InputCoordinate
963 logical_coordinates[ui::LatencyInfo::kMaxInputCoordinates];
964 size_t logical_coordinates_size =
965 std::min(arraysize(logical_coordinates),
966 static_cast<size_t>(touch_event.touchesLength));
967 for (size_t i = 0; i < logical_coordinates_size; i++) {
968 logical_coordinates[i] = ui::LatencyInfo::InputCoordinate(
969 touch_event.touches[i].position.x, touch_event.touches[i].position.y);
972 ui::LatencyInfo latency_info = CreateRWHLatencyInfoIfNotExist(
973 NULL, touch_event.type, logical_coordinates, logical_coordinates_size);
974 TouchEventWithLatencyInfo touch_with_latency(touch_event, latency_info);
975 input_router_->SendTouchEvent(touch_with_latency);
978 void RenderWidgetHostImpl::ForwardTouchEventWithLatencyInfo(
979 const blink::WebTouchEvent& touch_event,
980 const ui::LatencyInfo& ui_latency) {
981 TRACE_EVENT0("input", "RenderWidgetHostImpl::ForwardTouchEvent");
983 // Always forward TouchEvents for touch stream consistency. They will be
984 // ignored if appropriate in FilterInputEvent().
986 ui::LatencyInfo::InputCoordinate
987 logical_coordinates[ui::LatencyInfo::kMaxInputCoordinates];
988 size_t logical_coordinates_size =
989 std::min(arraysize(logical_coordinates),
990 static_cast<size_t>(touch_event.touchesLength));
991 for (size_t i = 0; i < logical_coordinates_size; i++) {
992 logical_coordinates[i] = ui::LatencyInfo::InputCoordinate(
993 touch_event.touches[i].position.x, touch_event.touches[i].position.y);
996 ui::LatencyInfo latency_info =
997 CreateRWHLatencyInfoIfNotExist(&ui_latency,
1000 logical_coordinates_size);
1001 TouchEventWithLatencyInfo touch_with_latency(touch_event, latency_info);
1003 if (touch_emulator_ &&
1004 touch_emulator_->HandleTouchEvent(touch_with_latency.event)) {
1006 view_->ProcessAckedTouchEvent(
1007 touch_with_latency, INPUT_EVENT_ACK_STATE_CONSUMED);
1012 input_router_->SendTouchEvent(touch_with_latency);
1015 void RenderWidgetHostImpl::ForwardKeyboardEvent(
1016 const NativeWebKeyboardEvent& key_event) {
1017 TRACE_EVENT0("input", "RenderWidgetHostImpl::ForwardKeyboardEvent");
1018 if (IgnoreInputEvents())
1021 if (!process_->HasConnection())
1024 // First, let keypress listeners take a shot at handling the event. If a
1025 // listener handles the event, it should not be propagated to the renderer.
1026 if (KeyPressListenersHandleEvent(key_event)) {
1027 // Some keypresses that are accepted by the listener might have follow up
1028 // char events, which should be ignored.
1029 if (key_event.type == WebKeyboardEvent::RawKeyDown)
1030 suppress_next_char_events_ = true;
1034 if (key_event.type == WebKeyboardEvent::Char &&
1035 (key_event.windowsKeyCode == ui::VKEY_RETURN ||
1036 key_event.windowsKeyCode == ui::VKEY_SPACE)) {
1040 // Double check the type to make sure caller hasn't sent us nonsense that
1041 // will mess up our key queue.
1042 if (!WebInputEvent::isKeyboardEventType(key_event.type))
1045 if (suppress_next_char_events_) {
1046 // If preceding RawKeyDown event was handled by the browser, then we need
1047 // suppress all Char events generated by it. Please note that, one
1048 // RawKeyDown event may generate multiple Char events, so we can't reset
1049 // |suppress_next_char_events_| until we get a KeyUp or a RawKeyDown.
1050 if (key_event.type == WebKeyboardEvent::Char)
1052 // We get a KeyUp or a RawKeyDown event.
1053 suppress_next_char_events_ = false;
1056 bool is_shortcut = false;
1058 // Only pre-handle the key event if it's not handled by the input method.
1059 if (delegate_ && !key_event.skip_in_browser) {
1060 // We need to set |suppress_next_char_events_| to true if
1061 // PreHandleKeyboardEvent() returns true, but |this| may already be
1062 // destroyed at that time. So set |suppress_next_char_events_| true here,
1063 // then revert it afterwards when necessary.
1064 if (key_event.type == WebKeyboardEvent::RawKeyDown)
1065 suppress_next_char_events_ = true;
1067 // Tab switching/closing accelerators aren't sent to the renderer to avoid
1068 // a hung/malicious renderer from interfering.
1069 if (delegate_->PreHandleKeyboardEvent(key_event, &is_shortcut))
1072 if (key_event.type == WebKeyboardEvent::RawKeyDown)
1073 suppress_next_char_events_ = false;
1076 if (touch_emulator_ && touch_emulator_->HandleKeyboardEvent(key_event))
1079 input_router_->SendKeyboardEvent(
1081 CreateRWHLatencyInfoIfNotExist(NULL, key_event.type, NULL, 0),
1085 void RenderWidgetHostImpl::QueueSyntheticGesture(
1086 scoped_ptr<SyntheticGesture> synthetic_gesture,
1087 const base::Callback<void(SyntheticGesture::Result)>& on_complete) {
1088 if (!synthetic_gesture_controller_ && view_) {
1089 synthetic_gesture_controller_.reset(
1090 new SyntheticGestureController(
1091 view_->CreateSyntheticGestureTarget().Pass()));
1093 if (synthetic_gesture_controller_) {
1094 synthetic_gesture_controller_->QueueSyntheticGesture(
1095 synthetic_gesture.Pass(), on_complete);
1099 void RenderWidgetHostImpl::SetCursor(const WebCursor& cursor) {
1102 view_->UpdateCursor(cursor);
1105 void RenderWidgetHostImpl::ShowContextMenuAtPoint(const gfx::Point& point) {
1106 Send(new ViewMsg_ShowContextMenu(
1107 GetRoutingID(), ui::MENU_SOURCE_MOUSE, point));
1110 void RenderWidgetHostImpl::SendCursorVisibilityState(bool is_visible) {
1111 Send(new InputMsg_CursorVisibilityChange(GetRoutingID(), is_visible));
1114 int64 RenderWidgetHostImpl::GetLatencyComponentId() {
1115 return GetRoutingID() | (static_cast<int64>(GetProcess()->GetID()) << 32);
1119 void RenderWidgetHostImpl::DisableResizeAckCheckForTesting() {
1120 g_check_for_pending_resize_ack = false;
1123 ui::LatencyInfo RenderWidgetHostImpl::CreateRWHLatencyInfoIfNotExist(
1124 const ui::LatencyInfo* original,
1125 WebInputEvent::Type type,
1126 const ui::LatencyInfo::InputCoordinate* logical_coordinates,
1127 size_t logical_coordinates_size) {
1128 ui::LatencyInfo info;
1131 // In Aura, gesture event will already carry its original touch event's
1132 // INPUT_EVENT_LATENCY_RWH_COMPONENT.
1133 if (!info.FindLatency(ui::INPUT_EVENT_LATENCY_BEGIN_RWH_COMPONENT,
1134 GetLatencyComponentId(),
1136 info.AddLatencyNumber(ui::INPUT_EVENT_LATENCY_BEGIN_RWH_COMPONENT,
1137 GetLatencyComponentId(),
1138 ++last_input_number_);
1139 info.TraceEventType(WebInputEventTraits::GetName(type));
1141 // Convert logical coordinates to physical coordinates, based on the
1142 // device scale factor.
1143 float device_scale_factor =
1144 screen_info_ ? screen_info_->deviceScaleFactor : 1;
1145 DCHECK(logical_coordinates_size <= ui::LatencyInfo::kMaxInputCoordinates);
1146 info.input_coordinates_size = logical_coordinates_size;
1147 for (size_t i = 0; i < info.input_coordinates_size; i++) {
1148 info.input_coordinates[i].x =
1149 logical_coordinates[i].x * device_scale_factor;
1150 info.input_coordinates[i].y =
1151 logical_coordinates[i].y * device_scale_factor;
1159 void RenderWidgetHostImpl::AddKeyPressEventCallback(
1160 const KeyPressEventCallback& callback) {
1161 key_press_event_callbacks_.push_back(callback);
1164 void RenderWidgetHostImpl::RemoveKeyPressEventCallback(
1165 const KeyPressEventCallback& callback) {
1166 for (size_t i = 0; i < key_press_event_callbacks_.size(); ++i) {
1167 if (key_press_event_callbacks_[i].Equals(callback)) {
1168 key_press_event_callbacks_.erase(
1169 key_press_event_callbacks_.begin() + i);
1175 void RenderWidgetHostImpl::AddMouseEventCallback(
1176 const MouseEventCallback& callback) {
1177 mouse_event_callbacks_.push_back(callback);
1180 void RenderWidgetHostImpl::RemoveMouseEventCallback(
1181 const MouseEventCallback& callback) {
1182 for (size_t i = 0; i < mouse_event_callbacks_.size(); ++i) {
1183 if (mouse_event_callbacks_[i].Equals(callback)) {
1184 mouse_event_callbacks_.erase(mouse_event_callbacks_.begin() + i);
1190 void RenderWidgetHostImpl::GetWebScreenInfo(blink::WebScreenInfo* result) {
1191 TRACE_EVENT0("renderer_host", "RenderWidgetHostImpl::GetWebScreenInfo");
1193 view_->GetScreenInfo(result);
1195 RenderWidgetHostViewBase::GetDefaultScreenInfo(result);
1196 screen_info_out_of_date_ = false;
1199 const NativeWebKeyboardEvent*
1200 RenderWidgetHostImpl::GetLastKeyboardEvent() const {
1201 return input_router_->GetLastKeyboardEvent();
1204 void RenderWidgetHostImpl::NotifyScreenInfoChanged() {
1205 // The resize message (which may not happen immediately) will carry with it
1206 // the screen info as well as the new size (if the screen has changed scale
1208 InvalidateScreenInfo();
1212 void RenderWidgetHostImpl::InvalidateScreenInfo() {
1213 screen_info_out_of_date_ = true;
1214 screen_info_.reset();
1217 void RenderWidgetHostImpl::GetSnapshotFromBrowser(
1218 const base::Callback<void(const unsigned char*,size_t)> callback) {
1219 int id = next_browser_snapshot_id_++;
1220 pending_browser_snapshots_.insert(std::make_pair(id, callback));
1221 Send(new ViewMsg_ForceRedraw(GetRoutingID(), id));
1224 void RenderWidgetHostImpl::OnSelectionChanged(const base::string16& text,
1226 const gfx::Range& range) {
1228 view_->SelectionChanged(text, offset, range);
1231 void RenderWidgetHostImpl::OnSelectionBoundsChanged(
1232 const ViewHostMsg_SelectionBounds_Params& params) {
1234 view_->SelectionBoundsChanged(params);
1238 void RenderWidgetHostImpl::UpdateVSyncParameters(base::TimeTicks timebase,
1239 base::TimeDelta interval) {
1240 Send(new ViewMsg_UpdateVSyncParameters(GetRoutingID(), timebase, interval));
1243 void RenderWidgetHostImpl::RendererExited(base::TerminationStatus status,
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 visible for the sake of internal accounting - be
1260 // careful about changing this - see http://crbug.com/401859.
1262 // We need to at least make sure that the RenderProcessHost is notified about
1263 // the |is_hidden_| change, so that the renderer will have correct visibility
1264 // set when respawned.
1266 process_->WidgetRestored();
1270 // Reset this to ensure the hung renderer mechanism is working properly.
1271 in_flight_event_count_ = 0;
1274 GpuSurfaceTracker::Get()->SetSurfaceHandle(surface_id_,
1275 gfx::GLSurfaceHandle());
1276 view_->RenderProcessGone(status, exit_code);
1277 view_ = NULL; // The View should be deleted by RenderProcessGone.
1281 // Reconstruct the input router to ensure that it has fresh state for a new
1282 // renderer. Otherwise it may be stuck waiting for the old renderer to ack an
1283 // event. (In particular, the above call to view_->RenderProcessGone will
1284 // destroy the aura window, which may dispatch a synthetic mouse move.)
1285 input_router_.reset(new InputRouterImpl(
1286 process_, this, this, routing_id_, GetInputRouterConfigForPlatform()));
1288 synthetic_gesture_controller_.reset();
1291 void RenderWidgetHostImpl::UpdateTextDirection(WebTextDirection direction) {
1292 text_direction_updated_ = true;
1293 text_direction_ = direction;
1296 void RenderWidgetHostImpl::CancelUpdateTextDirection() {
1297 if (text_direction_updated_)
1298 text_direction_canceled_ = true;
1301 void RenderWidgetHostImpl::NotifyTextDirection() {
1302 if (text_direction_updated_) {
1303 if (!text_direction_canceled_)
1304 Send(new ViewMsg_SetTextDirection(GetRoutingID(), text_direction_));
1305 text_direction_updated_ = false;
1306 text_direction_canceled_ = false;
1310 void RenderWidgetHostImpl::SetInputMethodActive(bool activate) {
1311 input_method_active_ = activate;
1312 Send(new ViewMsg_SetInputMethodActive(GetRoutingID(), activate));
1315 void RenderWidgetHostImpl::CandidateWindowShown() {
1316 Send(new ViewMsg_CandidateWindowShown(GetRoutingID()));
1319 void RenderWidgetHostImpl::CandidateWindowUpdated() {
1320 Send(new ViewMsg_CandidateWindowUpdated(GetRoutingID()));
1323 void RenderWidgetHostImpl::CandidateWindowHidden() {
1324 Send(new ViewMsg_CandidateWindowHidden(GetRoutingID()));
1327 void RenderWidgetHostImpl::ImeSetComposition(
1328 const base::string16& text,
1329 const std::vector<blink::WebCompositionUnderline>& underlines,
1330 int selection_start,
1331 int selection_end) {
1332 Send(new InputMsg_ImeSetComposition(
1333 GetRoutingID(), text, underlines, selection_start, selection_end));
1336 void RenderWidgetHostImpl::ImeConfirmComposition(
1337 const base::string16& text,
1338 const gfx::Range& replacement_range,
1339 bool keep_selection) {
1340 Send(new InputMsg_ImeConfirmComposition(
1341 GetRoutingID(), text, replacement_range, keep_selection));
1344 void RenderWidgetHostImpl::ImeCancelComposition() {
1345 Send(new InputMsg_ImeSetComposition(GetRoutingID(), base::string16(),
1346 std::vector<blink::WebCompositionUnderline>(), 0, 0));
1349 gfx::Rect RenderWidgetHostImpl::GetRootWindowResizerRect() const {
1353 void RenderWidgetHostImpl::RequestToLockMouse(bool user_gesture,
1354 bool last_unlocked_by_target) {
1355 // Directly reject to lock the mouse. Subclass can override this method to
1356 // decide whether to allow mouse lock or not.
1357 GotResponseToLockMouseRequest(false);
1360 void RenderWidgetHostImpl::RejectMouseLockOrUnlockIfNecessary() {
1361 DCHECK(!pending_mouse_lock_request_ || !IsMouseLocked());
1362 if (pending_mouse_lock_request_) {
1363 pending_mouse_lock_request_ = false;
1364 Send(new ViewMsg_LockMouse_ACK(routing_id_, false));
1365 } else if (IsMouseLocked()) {
1366 view_->UnlockMouse();
1370 bool RenderWidgetHostImpl::IsMouseLocked() const {
1371 return view_ ? view_->IsMouseLocked() : false;
1374 bool RenderWidgetHostImpl::IsFullscreen() const {
1378 void RenderWidgetHostImpl::SetShouldAutoResize(bool enable) {
1379 should_auto_resize_ = enable;
1382 void RenderWidgetHostImpl::Destroy() {
1383 NotificationService::current()->Notify(
1384 NOTIFICATION_RENDER_WIDGET_HOST_DESTROYED,
1385 Source<RenderWidgetHost>(this),
1386 NotificationService::NoDetails());
1388 // Tell the view to die.
1389 // Note that in the process of the view shutting down, it can call a ton
1390 // of other messages on us. So if you do any other deinitialization here,
1391 // do it after this call to view_->Destroy().
1398 void RenderWidgetHostImpl::RendererIsUnresponsive() {
1399 NotificationService::current()->Notify(
1400 NOTIFICATION_RENDER_WIDGET_HOST_HANG,
1401 Source<RenderWidgetHost>(this),
1402 NotificationService::NoDetails());
1403 is_unresponsive_ = true;
1404 NotifyRendererUnresponsive();
1407 void RenderWidgetHostImpl::RendererIsResponsive() {
1408 if (is_unresponsive_) {
1409 is_unresponsive_ = false;
1410 NotifyRendererResponsive();
1414 void RenderWidgetHostImpl::OnRenderViewReady() {
1419 void RenderWidgetHostImpl::OnRenderProcessGone(int status, int exit_code) {
1420 // TODO(evanm): This synchronously ends up calling "delete this".
1421 // Is that really what we want in response to this message? I'm matching
1422 // previous behavior of the code here.
1426 void RenderWidgetHostImpl::OnClose() {
1430 void RenderWidgetHostImpl::OnSetTooltipText(
1431 const base::string16& tooltip_text,
1432 WebTextDirection text_direction_hint) {
1433 // First, add directionality marks around tooltip text if necessary.
1434 // A naive solution would be to simply always wrap the text. However, on
1435 // windows, Unicode directional embedding characters can't be displayed on
1436 // systems that lack RTL fonts and are instead displayed as empty squares.
1438 // To get around this we only wrap the string when we deem it necessary i.e.
1439 // when the locale direction is different than the tooltip direction hint.
1441 // Currently, we use element's directionality as the tooltip direction hint.
1442 // An alternate solution would be to set the overall directionality based on
1443 // trying to detect the directionality from the tooltip text rather than the
1444 // element direction. One could argue that would be a preferable solution
1445 // but we use the current approach to match Fx & IE's behavior.
1446 base::string16 wrapped_tooltip_text = tooltip_text;
1447 if (!tooltip_text.empty()) {
1448 if (text_direction_hint == blink::WebTextDirectionLeftToRight) {
1449 // Force the tooltip to have LTR directionality.
1450 wrapped_tooltip_text =
1451 base::i18n::GetDisplayStringInLTRDirectionality(wrapped_tooltip_text);
1452 } else if (text_direction_hint == blink::WebTextDirectionRightToLeft &&
1453 !base::i18n::IsRTL()) {
1454 // Force the tooltip to have RTL directionality.
1455 base::i18n::WrapStringWithRTLFormatting(&wrapped_tooltip_text);
1459 view_->SetTooltipText(wrapped_tooltip_text);
1462 void RenderWidgetHostImpl::OnUpdateScreenRectsAck() {
1463 waiting_for_screen_rects_ack_ = false;
1467 if (view_->GetViewBounds() == last_view_screen_rect_ &&
1468 view_->GetBoundsInRootWindow() == last_window_screen_rect_) {
1475 void RenderWidgetHostImpl::OnRequestMove(const gfx::Rect& pos) {
1477 view_->SetBounds(pos);
1478 Send(new ViewMsg_Move_ACK(routing_id_));
1482 bool RenderWidgetHostImpl::OnSwapCompositorFrame(
1483 const IPC::Message& message) {
1484 // This trace event is used in
1485 // chrome/browser/extensions/api/cast_streaming/performance_test.cc
1486 TRACE_EVENT0("test_fps",
1487 TRACE_DISABLED_BY_DEFAULT("OnSwapCompositorFrame"));
1488 ViewHostMsg_SwapCompositorFrame::Param param;
1489 if (!ViewHostMsg_SwapCompositorFrame::Read(&message, ¶m))
1491 scoped_ptr<cc::CompositorFrame> frame(new cc::CompositorFrame);
1492 uint32 output_surface_id = param.a;
1493 param.b.AssignTo(frame.get());
1494 std::vector<IPC::Message> messages_to_deliver_with_frame;
1495 messages_to_deliver_with_frame.swap(param.c);
1497 for (size_t i = 0; i < frame->metadata.latency_info.size(); i++)
1498 AddLatencyInfoComponentIds(&frame->metadata.latency_info[i]);
1500 input_router_->OnViewUpdated(
1501 GetInputRouterViewFlagsFromCompositorFrameMetadata(frame->metadata));
1504 view_->OnSwapCompositorFrame(output_surface_id, frame.Pass());
1505 view_->DidReceiveRendererFrame();
1507 cc::CompositorFrameAck ack;
1508 if (frame->gl_frame_data) {
1509 ack.gl_frame_data = frame->gl_frame_data.Pass();
1510 ack.gl_frame_data->sync_point = 0;
1511 } else if (frame->delegated_frame_data) {
1512 cc::TransferableResource::ReturnResources(
1513 frame->delegated_frame_data->resource_list,
1515 } else if (frame->software_frame_data) {
1516 ack.last_software_frame_id = frame->software_frame_data->id;
1518 SendSwapCompositorFrameAck(routing_id_, output_surface_id,
1519 process_->GetID(), ack);
1522 RenderProcessHost* rph = GetProcess();
1523 for (std::vector<IPC::Message>::const_iterator i =
1524 messages_to_deliver_with_frame.begin();
1525 i != messages_to_deliver_with_frame.end();
1527 rph->OnMessageReceived(*i);
1528 if (i->dispatch_error())
1529 rph->OnBadMessageReceived(*i);
1531 messages_to_deliver_with_frame.clear();
1536 void RenderWidgetHostImpl::OnFlingingStopped() {
1538 view_->DidStopFlinging();
1541 void RenderWidgetHostImpl::OnUpdateRect(
1542 const ViewHostMsg_UpdateRect_Params& params) {
1543 TRACE_EVENT0("renderer_host", "RenderWidgetHostImpl::OnUpdateRect");
1544 TimeTicks paint_start = TimeTicks::Now();
1546 // Update our knowledge of the RenderWidget's size.
1547 current_size_ = params.view_size;
1549 bool is_resize_ack =
1550 ViewHostMsg_UpdateRect_Flags::is_resize_ack(params.flags);
1552 // resize_ack_pending_ needs to be cleared before we call DidPaintRect, since
1553 // that will end up reaching GetBackingStore.
1554 if (is_resize_ack) {
1555 DCHECK(!g_check_for_pending_resize_ack || resize_ack_pending_);
1556 resize_ack_pending_ = false;
1559 bool is_repaint_ack =
1560 ViewHostMsg_UpdateRect_Flags::is_repaint_ack(params.flags);
1561 if (is_repaint_ack) {
1562 DCHECK(repaint_ack_pending_);
1563 TRACE_EVENT_ASYNC_END0(
1564 "renderer_host", "RenderWidgetHostImpl::repaint_ack_pending_", this);
1565 repaint_ack_pending_ = false;
1566 TimeDelta delta = TimeTicks::Now() - repaint_start_time_;
1567 UMA_HISTOGRAM_TIMES("MPArch.RWH_RepaintDelta", delta);
1570 DCHECK(!params.view_size.IsEmpty());
1572 DidUpdateBackingStore(params, paint_start);
1574 if (should_auto_resize_) {
1575 bool post_callback = new_auto_size_.IsEmpty();
1576 new_auto_size_ = params.view_size;
1577 if (post_callback) {
1578 base::MessageLoop::current()->PostTask(
1580 base::Bind(&RenderWidgetHostImpl::DelayedAutoResized,
1581 weak_factory_.GetWeakPtr()));
1585 // Log the time delta for processing a paint message. On platforms that don't
1586 // support asynchronous painting, this is equivalent to
1587 // MPArch.RWH_TotalPaintTime.
1588 TimeDelta delta = TimeTicks::Now() - paint_start;
1589 UMA_HISTOGRAM_TIMES("MPArch.RWH_OnMsgUpdateRect", delta);
1592 void RenderWidgetHostImpl::DidUpdateBackingStore(
1593 const ViewHostMsg_UpdateRect_Params& params,
1594 const TimeTicks& paint_start) {
1595 TRACE_EVENT0("renderer_host", "RenderWidgetHostImpl::DidUpdateBackingStore");
1596 TimeTicks update_start = TimeTicks::Now();
1598 // Move the plugins if the view hasn't already been destroyed. Plugin moves
1599 // will not be re-issued, so must move them now, regardless of whether we
1600 // paint or not. MovePluginWindows attempts to move the plugin windows and
1601 // in the process could dispatch other window messages which could cause the
1602 // view to be destroyed.
1604 view_->MovePluginWindows(params.plugin_window_moves);
1606 NotificationService::current()->Notify(
1607 NOTIFICATION_RENDER_WIDGET_HOST_DID_UPDATE_BACKING_STORE,
1608 Source<RenderWidgetHost>(this),
1609 NotificationService::NoDetails());
1611 // We don't need to update the view if the view is hidden. We must do this
1612 // early return after the ACK is sent, however, or the renderer will not send
1617 // If we got a resize ack, then perhaps we have another resize to send?
1618 bool is_resize_ack =
1619 ViewHostMsg_UpdateRect_Flags::is_resize_ack(params.flags);
1623 // Log the time delta for processing a paint message.
1624 TimeTicks now = TimeTicks::Now();
1625 TimeDelta delta = now - update_start;
1626 UMA_HISTOGRAM_TIMES("MPArch.RWH_DidUpdateBackingStore", delta);
1629 void RenderWidgetHostImpl::OnQueueSyntheticGesture(
1630 const SyntheticGesturePacket& gesture_packet) {
1631 // Only allow untrustworthy gestures if explicitly enabled.
1632 if (!base::CommandLine::ForCurrentProcess()->HasSwitch(
1633 cc::switches::kEnableGpuBenchmarking)) {
1634 RecordAction(base::UserMetricsAction("BadMessageTerminate_RWH7"));
1635 GetProcess()->ReceivedBadMessage();
1639 QueueSyntheticGesture(
1640 SyntheticGesture::Create(*gesture_packet.gesture_params()),
1641 base::Bind(&RenderWidgetHostImpl::OnSyntheticGestureCompleted,
1642 weak_factory_.GetWeakPtr()));
1645 void RenderWidgetHostImpl::OnFocus() {
1646 // Only RenderViewHost can deal with that message.
1647 RecordAction(base::UserMetricsAction("BadMessageTerminate_RWH4"));
1648 GetProcess()->ReceivedBadMessage();
1651 void RenderWidgetHostImpl::OnBlur() {
1652 // Only RenderViewHost can deal with that message.
1653 RecordAction(base::UserMetricsAction("BadMessageTerminate_RWH5"));
1654 GetProcess()->ReceivedBadMessage();
1657 void RenderWidgetHostImpl::OnSetCursor(const WebCursor& cursor) {
1661 void RenderWidgetHostImpl::SetTouchEventEmulationEnabled(bool enabled) {
1663 if (!touch_emulator_)
1664 touch_emulator_.reset(new TouchEmulator(this));
1665 touch_emulator_->Enable();
1667 if (touch_emulator_)
1668 touch_emulator_->Disable();
1672 void RenderWidgetHostImpl::OnTextInputTypeChanged(
1673 ui::TextInputType type,
1674 ui::TextInputMode input_mode,
1675 bool can_compose_inline) {
1677 view_->TextInputTypeChanged(type, input_mode, can_compose_inline);
1680 #if defined(OS_MACOSX) || defined(USE_AURA)
1681 void RenderWidgetHostImpl::OnImeCompositionRangeChanged(
1682 const gfx::Range& range,
1683 const std::vector<gfx::Rect>& character_bounds) {
1685 view_->ImeCompositionRangeChanged(range, character_bounds);
1689 void RenderWidgetHostImpl::OnImeCancelComposition() {
1691 view_->ImeCancelComposition();
1694 void RenderWidgetHostImpl::OnLockMouse(bool user_gesture,
1695 bool last_unlocked_by_target,
1698 if (pending_mouse_lock_request_) {
1699 Send(new ViewMsg_LockMouse_ACK(routing_id_, false));
1701 } else if (IsMouseLocked()) {
1702 Send(new ViewMsg_LockMouse_ACK(routing_id_, true));
1706 pending_mouse_lock_request_ = true;
1707 if (privileged && allow_privileged_mouse_lock_) {
1708 // Directly approve to lock the mouse.
1709 GotResponseToLockMouseRequest(true);
1711 RequestToLockMouse(user_gesture, last_unlocked_by_target);
1715 void RenderWidgetHostImpl::OnUnlockMouse() {
1716 RejectMouseLockOrUnlockIfNecessary();
1719 void RenderWidgetHostImpl::OnShowDisambiguationPopup(
1720 const gfx::Rect& rect_pixels,
1721 const gfx::Size& size,
1722 const cc::SharedBitmapId& id) {
1723 DCHECK(!rect_pixels.IsEmpty());
1724 DCHECK(!size.IsEmpty());
1726 scoped_ptr<cc::SharedBitmap> bitmap =
1727 HostSharedBitmapManager::current()->GetSharedBitmapFromId(size, id);
1729 RecordAction(base::UserMetricsAction("BadMessageTerminate_RWH6"));
1730 GetProcess()->ReceivedBadMessage();
1734 DCHECK(bitmap->pixels());
1736 SkImageInfo info = SkImageInfo::MakeN32Premul(size.width(), size.height());
1737 SkBitmap zoomed_bitmap;
1738 zoomed_bitmap.installPixels(info, bitmap->pixels(), info.minRowBytes());
1740 #if defined(OS_ANDROID) || defined(TOOLKIT_VIEWS)
1741 // Note that |rect| is in coordinates of pixels relative to the window origin.
1742 // Aura-based systems will want to convert this to DIPs.
1744 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));
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
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) {
1769 #if defined(USE_AURA)
1771 reinterpret_cast<HWND>(view_->GetParentForWindowlessPlugin()));
1773 SetParent(hwnd, reinterpret_cast<HWND>(GetNativeViewId()));
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) {
1784 dummy_windows_for_activation_.erase(i);
1788 NOTREACHED() << "Unknown dummy window";
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)
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))
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);
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)
1832 return view_ ? view_->FilterInputEvent(event)
1833 : INPUT_EVENT_ACK_STATE_NOT_CONSUMED;
1836 void RenderWidgetHostImpl::IncrementInFlightEventCount() {
1837 StartHangMonitorTimeout(
1838 TimeDelta::FromMilliseconds(hung_renderer_delay_ms_));
1839 increment_in_flight_event_count();
1842 void RenderWidgetHostImpl::DecrementInFlightEventCount() {
1843 DCHECK_GE(in_flight_event_count_, 0);
1844 if (decrement_in_flight_event_count() <= 0) {
1845 // Cancel pending hung renderer checks since the renderer is responsive.
1846 StopHangMonitorTimeout();
1848 // The renderer is responsive, but there are in-flight events to wait for.
1849 RestartHangMonitorTimeout();
1853 void RenderWidgetHostImpl::OnHasTouchEventHandlers(bool has_handlers) {
1854 has_touch_handler_ = has_handlers;
1857 void RenderWidgetHostImpl::DidFlush() {
1858 if (synthetic_gesture_controller_)
1859 synthetic_gesture_controller_->OnDidFlushInput();
1861 view_->OnDidFlushInput();
1864 void RenderWidgetHostImpl::DidOverscroll(const DidOverscrollParams& params) {
1866 view_->DidOverscroll(params);
1869 void RenderWidgetHostImpl::OnKeyboardEventAck(
1870 const NativeWebKeyboardEvent& event,
1871 InputEventAckState ack_result) {
1872 #if defined(OS_MACOSX)
1873 if (!is_hidden() && view_ && view_->PostProcessEventForPluginIme(event))
1877 // We only send unprocessed key event upwards if we are not hidden,
1878 // because the user has moved away from us and no longer expect any effect
1879 // of this key event.
1880 const bool processed = (INPUT_EVENT_ACK_STATE_CONSUMED == ack_result);
1881 if (delegate_ && !processed && !is_hidden() && !event.skip_in_browser) {
1882 delegate_->HandleKeyboardEvent(event);
1884 // WARNING: This RenderWidgetHostImpl can be deallocated at this point
1885 // (i.e. in the case of Ctrl+W, where the call to
1886 // HandleKeyboardEvent destroys this RenderWidgetHostImpl).
1890 void RenderWidgetHostImpl::OnWheelEventAck(
1891 const MouseWheelEventWithLatencyInfo& wheel_event,
1892 InputEventAckState ack_result) {
1893 if (!wheel_event.latency.FindLatency(
1894 ui::INPUT_EVENT_LATENCY_RENDERING_SCHEDULED_COMPONENT, 0, NULL)) {
1895 // MouseWheelEvent latency ends when it is acked but does not cause any
1896 // rendering scheduled.
1897 ui::LatencyInfo latency = wheel_event.latency;
1898 latency.AddLatencyNumber(
1899 ui::INPUT_EVENT_LATENCY_TERMINATED_MOUSE_COMPONENT, 0, 0);
1902 if (!is_hidden() && view_) {
1903 if (ack_result != INPUT_EVENT_ACK_STATE_CONSUMED &&
1904 delegate_->HandleWheelEvent(wheel_event.event)) {
1905 ack_result = INPUT_EVENT_ACK_STATE_CONSUMED;
1907 view_->WheelEventAck(wheel_event.event, ack_result);
1911 void RenderWidgetHostImpl::OnGestureEventAck(
1912 const GestureEventWithLatencyInfo& event,
1913 InputEventAckState ack_result) {
1914 if (!event.latency.FindLatency(
1915 ui::INPUT_EVENT_LATENCY_RENDERING_SCHEDULED_COMPONENT, 0, NULL)) {
1916 // GestureEvent latency ends when it is acked but does not cause any
1917 // rendering scheduled.
1918 ui::LatencyInfo latency = event.latency;
1919 latency.AddLatencyNumber(
1920 ui::INPUT_EVENT_LATENCY_TERMINATED_GESTURE_COMPONENT, 0 ,0);
1923 if (ack_result != INPUT_EVENT_ACK_STATE_CONSUMED) {
1924 if (delegate_->HandleGestureEvent(event.event))
1925 ack_result = INPUT_EVENT_ACK_STATE_CONSUMED;
1929 view_->GestureEventAck(event.event, ack_result);
1932 void RenderWidgetHostImpl::OnTouchEventAck(
1933 const TouchEventWithLatencyInfo& event,
1934 InputEventAckState ack_result) {
1935 TouchEventWithLatencyInfo touch_event = event;
1936 touch_event.latency.AddLatencyNumber(
1937 ui::INPUT_EVENT_LATENCY_ACKED_TOUCH_COMPONENT, 0, 0);
1938 // TouchEvent latency ends at ack if it didn't cause any rendering.
1939 if (!touch_event.latency.FindLatency(
1940 ui::INPUT_EVENT_LATENCY_RENDERING_SCHEDULED_COMPONENT, 0, NULL)) {
1941 touch_event.latency.AddLatencyNumber(
1942 ui::INPUT_EVENT_LATENCY_TERMINATED_TOUCH_COMPONENT, 0, 0);
1944 ComputeTouchLatency(touch_event.latency);
1946 if (touch_emulator_ &&
1947 touch_emulator_->HandleTouchEventAck(event.event, ack_result)) {
1952 view_->ProcessAckedTouchEvent(touch_event, ack_result);
1955 void RenderWidgetHostImpl::OnUnexpectedEventAck(UnexpectedEventAckType type) {
1956 if (type == BAD_ACK_MESSAGE) {
1957 RecordAction(base::UserMetricsAction("BadMessageTerminate_RWH2"));
1958 process_->ReceivedBadMessage();
1959 } else if (type == UNEXPECTED_EVENT_TYPE) {
1960 suppress_next_char_events_ = false;
1964 void RenderWidgetHostImpl::OnSyntheticGestureCompleted(
1965 SyntheticGesture::Result result) {
1966 Send(new InputMsg_SyntheticGestureCompleted(GetRoutingID()));
1969 bool RenderWidgetHostImpl::IgnoreInputEvents() const {
1970 return ignore_input_events_ || process_->IgnoreInputEvents();
1973 bool RenderWidgetHostImpl::ShouldForwardTouchEvent() const {
1974 // It's important that the emulator sees a complete native touch stream,
1975 // allowing it to perform touch filtering as appropriate.
1976 // TODO(dgozman): Remove when touch stream forwarding issues resolved, see
1977 // crbug.com/375940.
1978 if (touch_emulator_ && touch_emulator_->enabled())
1981 return input_router_->ShouldForwardTouchEvent();
1984 void RenderWidgetHostImpl::StartUserGesture() {
1988 void RenderWidgetHostImpl::SetBackgroundOpaque(bool opaque) {
1989 Send(new ViewMsg_SetBackgroundOpaque(GetRoutingID(), opaque));
1992 void RenderWidgetHostImpl::SetEditCommandsForNextKeyEvent(
1993 const std::vector<EditCommand>& commands) {
1994 Send(new InputMsg_SetEditCommandsForNextKeyEvent(GetRoutingID(), commands));
1997 void RenderWidgetHostImpl::ExecuteEditCommand(const std::string& command,
1998 const std::string& value) {
1999 Send(new InputMsg_ExecuteEditCommand(GetRoutingID(), command, value));
2002 void RenderWidgetHostImpl::ScrollFocusedEditableNodeIntoRect(
2003 const gfx::Rect& rect) {
2004 Send(new InputMsg_ScrollFocusedEditableNodeIntoRect(GetRoutingID(), rect));
2007 void RenderWidgetHostImpl::MoveCaret(const gfx::Point& point) {
2008 Send(new InputMsg_MoveCaret(GetRoutingID(), point));
2011 bool RenderWidgetHostImpl::GotResponseToLockMouseRequest(bool allowed) {
2013 RejectMouseLockOrUnlockIfNecessary();
2016 if (!pending_mouse_lock_request_) {
2017 // This is possible, e.g., the plugin sends us an unlock request before
2018 // the user allows to lock to mouse.
2022 pending_mouse_lock_request_ = false;
2023 if (!view_ || !view_->HasFocus()|| !view_->LockMouse()) {
2024 Send(new ViewMsg_LockMouse_ACK(routing_id_, false));
2027 Send(new ViewMsg_LockMouse_ACK(routing_id_, true));
2034 void RenderWidgetHostImpl::AcknowledgeBufferPresent(
2035 int32 route_id, int gpu_host_id,
2036 const AcceleratedSurfaceMsg_BufferPresented_Params& params) {
2037 GpuProcessHostUIShim* ui_shim = GpuProcessHostUIShim::FromID(gpu_host_id);
2039 ui_shim->Send(new AcceleratedSurfaceMsg_BufferPresented(route_id,
2045 void RenderWidgetHostImpl::SendSwapCompositorFrameAck(
2047 uint32 output_surface_id,
2048 int renderer_host_id,
2049 const cc::CompositorFrameAck& ack) {
2050 RenderProcessHost* host = RenderProcessHost::FromID(renderer_host_id);
2053 host->Send(new ViewMsg_SwapCompositorFrameAck(
2054 route_id, output_surface_id, ack));
2058 void RenderWidgetHostImpl::SendReclaimCompositorResources(
2060 uint32 output_surface_id,
2061 int renderer_host_id,
2062 const cc::CompositorFrameAck& ack) {
2063 RenderProcessHost* host = RenderProcessHost::FromID(renderer_host_id);
2067 new ViewMsg_ReclaimCompositorResources(route_id, output_surface_id, ack));
2070 void RenderWidgetHostImpl::DelayedAutoResized() {
2071 gfx::Size new_size = new_auto_size_;
2072 // Clear the new_auto_size_ since the empty value is used as a flag to
2073 // indicate that no callback is in progress (i.e. without this line
2074 // DelayedAutoResized will not get called again).
2075 new_auto_size_.SetSize(0, 0);
2076 if (!should_auto_resize_)
2079 OnRenderAutoResized(new_size);
2082 void RenderWidgetHostImpl::DetachDelegate() {
2086 void RenderWidgetHostImpl::ComputeTouchLatency(
2087 const ui::LatencyInfo& latency_info) {
2088 ui::LatencyInfo::LatencyComponent ui_component;
2089 ui::LatencyInfo::LatencyComponent rwh_component;
2090 ui::LatencyInfo::LatencyComponent acked_component;
2092 if (!latency_info.FindLatency(ui::INPUT_EVENT_LATENCY_UI_COMPONENT,
2095 !latency_info.FindLatency(ui::INPUT_EVENT_LATENCY_BEGIN_RWH_COMPONENT,
2096 GetLatencyComponentId(),
2100 DCHECK(ui_component.event_count == 1);
2101 DCHECK(rwh_component.event_count == 1);
2103 base::TimeDelta ui_delta =
2104 rwh_component.event_time - ui_component.event_time;
2105 UMA_HISTOGRAM_CUSTOM_COUNTS(
2106 "Event.Latency.Browser.TouchUI",
2107 ui_delta.InMicroseconds(),
2112 if (latency_info.FindLatency(ui::INPUT_EVENT_LATENCY_ACKED_TOUCH_COMPONENT,
2114 &acked_component)) {
2115 DCHECK(acked_component.event_count == 1);
2116 base::TimeDelta acked_delta =
2117 acked_component.event_time - rwh_component.event_time;
2118 UMA_HISTOGRAM_CUSTOM_COUNTS(
2119 "Event.Latency.Browser.TouchAcked",
2120 acked_delta.InMicroseconds(),
2127 void RenderWidgetHostImpl::FrameSwapped(const ui::LatencyInfo& latency_info) {
2128 ui::LatencyInfo::LatencyComponent window_snapshot_component;
2129 if (latency_info.FindLatency(ui::WINDOW_OLD_SNAPSHOT_FRAME_NUMBER_COMPONENT,
2130 GetLatencyComponentId(),
2131 &window_snapshot_component)) {
2132 WindowOldSnapshotReachedScreen(
2133 static_cast<int>(window_snapshot_component.sequence_number));
2135 if (latency_info.FindLatency(ui::WINDOW_SNAPSHOT_FRAME_NUMBER_COMPONENT,
2136 GetLatencyComponentId(),
2137 &window_snapshot_component)) {
2138 int sequence_number = static_cast<int>(
2139 window_snapshot_component.sequence_number);
2140 #if defined(OS_MACOSX)
2141 // On Mac, when using CoreAnmation, there is a delay between when content
2142 // is drawn to the screen, and when the snapshot will actually pick up
2143 // that content. Insert a manual delay of 1/6th of a second (to simulate
2144 // 10 frames at 60 fps) before actually taking the snapshot.
2145 base::MessageLoop::current()->PostDelayedTask(
2147 base::Bind(&RenderWidgetHostImpl::WindowSnapshotReachedScreen,
2148 weak_factory_.GetWeakPtr(),
2150 base::TimeDelta::FromSecondsD(1. / 6));
2152 WindowSnapshotReachedScreen(sequence_number);
2156 ui::LatencyInfo::LatencyComponent swap_component;
2157 if (!latency_info.FindLatency(
2158 ui::INPUT_EVENT_LATENCY_TERMINATED_FRAME_SWAP_COMPONENT,
2163 ui::LatencyInfo::LatencyComponent tab_switch_component;
2164 if (latency_info.FindLatency(ui::TAB_SHOW_COMPONENT,
2165 GetLatencyComponentId(),
2166 &tab_switch_component)) {
2167 base::TimeDelta delta =
2168 swap_component.event_time - tab_switch_component.event_time;
2169 for (size_t i = 0; i < tab_switch_component.event_count; i++) {
2170 UMA_HISTOGRAM_TIMES("MPArch.RWH_TabSwitchPaintDuration", delta);
2174 ui::LatencyInfo::LatencyComponent rwh_component;
2175 if (!latency_info.FindLatency(ui::INPUT_EVENT_LATENCY_BEGIN_RWH_COMPONENT,
2176 GetLatencyComponentId(),
2181 ui::LatencyInfo::LatencyComponent original_component;
2182 if (latency_info.FindLatency(
2183 ui::INPUT_EVENT_LATENCY_SCROLL_UPDATE_ORIGINAL_COMPONENT,
2184 GetLatencyComponentId(),
2185 &original_component)) {
2186 // This UMA metric tracks the time from when the original touch event is
2187 // created (averaged if there are multiple) to when the scroll gesture
2188 // results in final frame swap.
2189 base::TimeDelta delta =
2190 swap_component.event_time - original_component.event_time;
2191 for (size_t i = 0; i < original_component.event_count; i++) {
2192 UMA_HISTOGRAM_CUSTOM_COUNTS(
2193 "Event.Latency.TouchToScrollUpdateSwap",
2194 delta.InMicroseconds(),
2202 void RenderWidgetHostImpl::DidReceiveRendererFrame() {
2203 view_->DidReceiveRendererFrame();
2206 void RenderWidgetHostImpl::WindowSnapshotAsyncCallback(
2209 gfx::Size snapshot_size,
2210 scoped_refptr<base::RefCountedBytes> png_data) {
2211 if (!png_data.get()) {
2212 std::vector<unsigned char> png_vector;
2213 Send(new ViewMsg_WindowSnapshotCompleted(
2214 routing_id, snapshot_id, gfx::Size(), png_vector));
2218 Send(new ViewMsg_WindowSnapshotCompleted(
2219 routing_id, snapshot_id, snapshot_size, png_data->data()));
2222 void RenderWidgetHostImpl::WindowOldSnapshotReachedScreen(int snapshot_id) {
2223 DCHECK(base::MessageLoopForUI::IsCurrent());
2225 std::vector<unsigned char> png;
2227 // This feature is behind the kEnableGpuBenchmarking command line switch
2228 // because it poses security concerns and should only be used for testing.
2229 const base::CommandLine& command_line =
2230 *base::CommandLine::ForCurrentProcess();
2231 if (!command_line.HasSwitch(cc::switches::kEnableGpuBenchmarking)) {
2232 Send(new ViewMsg_WindowSnapshotCompleted(
2233 GetRoutingID(), snapshot_id, gfx::Size(), png));
2237 gfx::Rect view_bounds = GetView()->GetViewBounds();
2238 gfx::Rect snapshot_bounds(view_bounds.size());
2239 gfx::Size snapshot_size = snapshot_bounds.size();
2241 if (ui::GrabViewSnapshot(
2242 GetView()->GetNativeView(), &png, snapshot_bounds)) {
2243 Send(new ViewMsg_WindowSnapshotCompleted(
2244 GetRoutingID(), snapshot_id, snapshot_size, png));
2248 ui::GrabViewSnapshotAsync(
2249 GetView()->GetNativeView(),
2251 base::ThreadTaskRunnerHandle::Get(),
2252 base::Bind(&RenderWidgetHostImpl::WindowSnapshotAsyncCallback,
2253 weak_factory_.GetWeakPtr(),
2259 void RenderWidgetHostImpl::WindowSnapshotReachedScreen(int snapshot_id) {
2260 DCHECK(base::MessageLoopForUI::IsCurrent());
2262 gfx::Rect view_bounds = GetView()->GetViewBounds();
2263 gfx::Rect snapshot_bounds(view_bounds.size());
2265 std::vector<unsigned char> png;
2266 if (ui::GrabViewSnapshot(
2267 GetView()->GetNativeView(), &png, snapshot_bounds)) {
2268 OnSnapshotDataReceived(snapshot_id, &png.front(), png.size());
2272 ui::GrabViewSnapshotAsync(
2273 GetView()->GetNativeView(),
2275 base::ThreadTaskRunnerHandle::Get(),
2276 base::Bind(&RenderWidgetHostImpl::OnSnapshotDataReceivedAsync,
2277 weak_factory_.GetWeakPtr(),
2281 void RenderWidgetHostImpl::OnSnapshotDataReceived(int snapshot_id,
2282 const unsigned char* data,
2284 // Any pending snapshots with a lower ID than the one received are considered
2285 // to be implicitly complete, and returned the same snapshot data.
2286 PendingSnapshotMap::iterator it = pending_browser_snapshots_.begin();
2287 while(it != pending_browser_snapshots_.end()) {
2288 if (it->first <= snapshot_id) {
2289 it->second.Run(data, size);
2290 pending_browser_snapshots_.erase(it++);
2297 void RenderWidgetHostImpl::OnSnapshotDataReceivedAsync(
2299 scoped_refptr<base::RefCountedBytes> png_data) {
2301 OnSnapshotDataReceived(snapshot_id, png_data->front(), png_data->size());
2303 OnSnapshotDataReceived(snapshot_id, NULL, 0);
2307 void RenderWidgetHostImpl::CompositorFrameDrawn(
2308 const std::vector<ui::LatencyInfo>& latency_info) {
2309 for (size_t i = 0; i < latency_info.size(); i++) {
2310 std::set<RenderWidgetHostImpl*> rwhi_set;
2311 for (ui::LatencyInfo::LatencyMap::const_iterator b =
2312 latency_info[i].latency_components.begin();
2313 b != latency_info[i].latency_components.end();
2315 if (b->first.first == ui::INPUT_EVENT_LATENCY_BEGIN_RWH_COMPONENT ||
2316 b->first.first == ui::WINDOW_SNAPSHOT_FRAME_NUMBER_COMPONENT ||
2317 b->first.first == ui::WINDOW_OLD_SNAPSHOT_FRAME_NUMBER_COMPONENT ||
2318 b->first.first == ui::TAB_SHOW_COMPONENT) {
2319 // Matches with GetLatencyComponentId
2320 int routing_id = b->first.second & 0xffffffff;
2321 int process_id = (b->first.second >> 32) & 0xffffffff;
2322 RenderWidgetHost* rwh =
2323 RenderWidgetHost::FromID(process_id, routing_id);
2327 RenderWidgetHostImpl* rwhi = RenderWidgetHostImpl::From(rwh);
2328 if (rwhi_set.insert(rwhi).second)
2329 rwhi->FrameSwapped(latency_info[i]);
2335 void RenderWidgetHostImpl::AddLatencyInfoComponentIds(
2336 ui::LatencyInfo* latency_info) {
2337 ui::LatencyInfo::LatencyMap new_components;
2338 ui::LatencyInfo::LatencyMap::iterator lc =
2339 latency_info->latency_components.begin();
2340 while (lc != latency_info->latency_components.end()) {
2341 ui::LatencyComponentType component_type = lc->first.first;
2342 if (component_type == ui::WINDOW_SNAPSHOT_FRAME_NUMBER_COMPONENT ||
2343 component_type == ui::WINDOW_OLD_SNAPSHOT_FRAME_NUMBER_COMPONENT) {
2344 // Generate a new component entry with the correct component ID
2345 ui::LatencyInfo::LatencyMap::key_type key =
2346 std::make_pair(component_type, GetLatencyComponentId());
2347 new_components[key] = lc->second;
2349 // Remove the old entry
2350 latency_info->latency_components.erase(lc++);
2356 // Add newly generated components into the latency info
2357 for (lc = new_components.begin(); lc != new_components.end(); ++lc) {
2358 latency_info->latency_components[lc->first] = lc->second;
2362 BrowserAccessibilityManager*
2363 RenderWidgetHostImpl::GetRootBrowserAccessibilityManager() {
2364 return delegate_ ? delegate_->GetRootBrowserAccessibilityManager() : NULL;
2367 BrowserAccessibilityManager*
2368 RenderWidgetHostImpl::GetOrCreateRootBrowserAccessibilityManager() {
2370 delegate_->GetOrCreateRootBrowserAccessibilityManager() : NULL;
2374 gfx::NativeViewAccessible
2375 RenderWidgetHostImpl::GetParentNativeViewAccessible() {
2376 return delegate_ ? delegate_->GetParentNativeViewAccessible() : NULL;
2380 SkColorType RenderWidgetHostImpl::PreferredReadbackFormat() {
2382 return view_->PreferredReadbackFormat();
2383 return kN32_SkColorType;
2386 } // namespace content