[blink-in-js] Migrate resources required for blink-in-js to grd - part 2
[chromium-blink-merge.git] / content / browser / renderer_host / render_widget_host_impl.cc
blob2c57a2b78d543dafaff3170cf9d2447cc2ce5d62
1 // Copyright (c) 2012 The Chromium Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
5 #include "content/browser/renderer_host/render_widget_host_impl.h"
7 #include <math.h>
8 #include <set>
9 #include <utility>
11 #include "base/auto_reset.h"
12 #include "base/bind.h"
13 #include "base/command_line.h"
14 #include "base/containers/hash_tables.h"
15 #include "base/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"
73 #if defined(OS_WIN)
74 #include "content/common/plugin_constants_win.h"
75 #endif
77 using base::Time;
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;
87 namespace content {
88 namespace {
90 bool g_check_for_pending_resize_ack = true;
92 typedef std::pair<int32, int32> RenderWidgetHostID;
93 typedef base::hash_map<RenderWidgetHostID, RenderWidgetHostImpl*>
94 RoutingIDWidgetMap;
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;
111 return view_flags;
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 {
118 public:
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);
137 ++current_index_;
139 return host;
142 private:
143 std::vector<RenderWidgetHostID> hosts_;
144 size_t current_index_;
146 DISALLOW_COPY_AND_ASSIGN(RenderWidgetHostIteratorImpl);
149 } // namespace
151 ///////////////////////////////////////////////////////////////////////////////
152 // RenderWidgetHostImpl
154 RenderWidgetHostImpl::RenderWidgetHostImpl(RenderWidgetHostDelegate* delegate,
155 RenderProcessHost* process,
156 int routing_id,
157 bool hidden)
158 : view_(NULL),
159 renderer_initialized_(false),
160 hung_renderer_delay_ms_(kHungRendererDelayMs),
161 delegate_(delegate),
162 process_(process),
163 routing_id_(routing_id),
164 surface_id_(0),
165 is_loading_(false),
166 is_hidden_(hidden),
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 weak_factory_(this),
188 last_input_number_(static_cast<int64>(GetProcess()->GetID()) << 32),
189 next_browser_snapshot_id_(1) {
190 CHECK(delegate_);
191 if (routing_id_ == MSG_ROUTING_NONE) {
192 routing_id_ = process_->GetNextRoutingID();
193 surface_id_ = GpuSurfaceTracker::Get()->AddSurfaceForRenderer(
194 process_->GetID(),
195 routing_id_);
196 } else {
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(
205 process_->GetID(),
206 routing_id_);
207 DCHECK(surface_id_);
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.
218 if (!hidden)
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() {
238 if (view_weak_)
239 view_weak_->RenderWidgetHostGone();
240 SetView(NULL);
242 GpuSurfaceTracker::Get()->RemoveSurface(surface_id_);
243 surface_id_ = 0;
245 process_->RemoveRoute(routing_id_);
246 g_routing_id_widget_map.Get().erase(
247 RenderWidgetHostID(process_->GetID(), routing_id_));
249 if (delegate_)
250 delegate_->RenderWidgetDeleted(this);
253 // static
254 RenderWidgetHost* RenderWidgetHost::FromID(
255 int32 process_id,
256 int32 routing_id) {
257 return RenderWidgetHostImpl::FromID(process_id, routing_id);
260 // static
261 RenderWidgetHostImpl* RenderWidgetHostImpl::FromID(
262 int32 process_id,
263 int32 routing_id) {
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;
271 // static
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();
277 ++it) {
278 RenderWidgetHost* widget = it->second;
280 if (!widget->IsRenderView()) {
281 hosts->Add(widget);
282 continue;
285 // Add only active RenderViewHosts.
286 RenderViewHost* rvh = RenderViewHost::From(widget);
287 if (RenderViewHostImpl::IsRVHStateActive(
288 static_cast<RenderViewHostImpl*>(rvh)->rvh_state()))
289 hosts->Add(widget);
292 return scoped_ptr<RenderWidgetHostIterator>(hosts);
295 // static
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();
302 ++it) {
303 hosts->Add(it->second);
306 return scoped_ptr<RenderWidgetHostIterator>(hosts);
309 // static
310 RenderWidgetHostImpl* RenderWidgetHostImpl::From(RenderWidgetHost* rwh) {
311 return rwh->AsRenderWidgetHostImpl();
314 void RenderWidgetHostImpl::SetView(RenderWidgetHostViewBase* view) {
315 if (view)
316 view_weak_ = view->GetWeakPtr();
317 else
318 view_weak_.reset();
319 view_ = view;
321 GpuSurfaceTracker::Get()->SetSurfaceHandle(
322 surface_id_, GetCompositingSurface());
324 synthetic_gesture_controller_.reset();
327 RenderProcessHost* RenderWidgetHostImpl::GetProcess() const {
328 return process_;
331 int RenderWidgetHostImpl::GetRoutingID() const {
332 return routing_id_;
335 RenderWidgetHostView* RenderWidgetHostImpl::GetView() const {
336 return view_;
339 RenderWidgetHostImpl* RenderWidgetHostImpl::AsRenderWidgetHostImpl() {
340 return this;
343 gfx::NativeViewId RenderWidgetHostImpl::GetNativeViewId() const {
344 if (view_)
345 return view_->GetNativeViewId();
346 return 0;
349 gfx::GLSurfaceHandle RenderWidgetHostImpl::GetCompositingSurface() {
350 if (view_)
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_)
367 return;
369 if (is_hidden_) {
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.
372 return;
375 if (!view_)
376 return;
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_));
382 if (delegate_)
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() {
398 if (view_)
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_);
414 WasResized();
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_));
423 DCHECK(rv);
426 Destroy();
429 bool RenderWidgetHostImpl::IsLoading() const {
430 return is_loading_;
433 bool RenderWidgetHostImpl::IsRenderView() const {
434 return false;
437 bool RenderWidgetHostImpl::OnMessageReceived(const IPC::Message &msg) {
438 bool handled = true;
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_TextInputStateChanged,
459 OnTextInputStateChanged)
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)
467 #if defined(OS_WIN)
468 IPC_MESSAGE_HANDLER(ViewHostMsg_WindowlessPluginDummyWindowCreated,
469 OnWindowlessPluginDummyWindowCreated)
470 IPC_MESSAGE_HANDLER(ViewHostMsg_WindowlessPluginDummyWindowDestroyed,
471 OnWindowlessPluginDummyWindowDestroyed)
472 #endif
473 #if defined(OS_MACOSX) || defined(USE_AURA)
474 IPC_MESSAGE_HANDLER(InputHostMsg_ImeCompositionRangeChanged,
475 OnImeCompositionRangeChanged)
476 #endif
477 IPC_MESSAGE_UNHANDLED(handled = false)
478 IPC_END_MESSAGE_MAP()
480 if (!handled && input_router_ && input_router_->OnMessageReceived(msg))
481 return true;
483 if (!handled && view_ && view_->OnMessageReceived(msg))
484 return true;
486 return handled;
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;
498 if (!view_)
499 return;
500 view_->SetIsLoading(is_loading);
503 void RenderWidgetHostImpl::WasHidden() {
504 if (is_hidden_)
505 return;
507 is_hidden_ = true;
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) {
527 if (!is_hidden_)
528 return;
529 is_hidden_ = false;
531 SendScreenRects();
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
550 // 3. WasHidden
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
553 // is.
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.
561 WasResized();
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_) {
569 return;
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)
595 return;
597 if (!screen_info_) {
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;
617 } else {
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() {
627 Focus();
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
637 // request later.
638 if (IsMouseLocked())
639 view_->UnlockMouse();
641 if (touch_emulator_)
642 touch_emulator_->CancelTouch();
644 Send(new InputMsg_SetFocus(routing_id_, false));
647 void RenderWidgetHostImpl::LostCapture() {
648 if (touch_emulator_)
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.
667 SetView(NULL);
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) {
675 if (view_) {
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);
682 return;
685 callback.Run(false, SkBitmap());
688 bool RenderWidgetHostImpl::CanCopyFromBackingStore() {
689 if (view_)
690 return view_->IsSurfaceAvailableForCopy();
691 return false;
694 #if defined(OS_ANDROID)
695 void RenderWidgetHostImpl::LockBackingStore() {
696 if (view_)
697 view_->LockCompositingSurface();
700 void RenderWidgetHostImpl::UnlockBackingStore() {
701 if (view_)
702 view_->UnlockCompositingSurface();
704 #endif
706 #if defined(OS_MACOSX)
707 void RenderWidgetHostImpl::PauseForPendingResizeOrRepaints() {
708 TRACE_EVENT0("browser",
709 "RenderWidgetHostImpl::PauseForPendingResizeOrRepaints");
711 if (!CanPauseForPendingResizeOrRepaints())
712 return;
714 WaitForSurface();
717 bool RenderWidgetHostImpl::CanPauseForPendingResizeOrRepaints() {
718 // Do not pause if the view is hidden.
719 if (is_hidden())
720 return false;
722 // Do not pause if there is not a paint or resize already coming.
723 if (!repaint_ack_pending_ && !resize_ack_pending_)
724 return false;
726 return true;
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;
737 if (!view_)
738 return;
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())
748 return;
749 view_size = view_rect.size();
752 TRACE_EVENT2("renderer_host",
753 "RenderWidgetHostImpl::WaitForBackingStore",
754 "width",
755 base::IntToString(view_size.width()),
756 "height",
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))
773 return;
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;
787 do {
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.
793 IPC::Message msg;
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
802 // correct size.
803 if (view_->HasAcceleratedSurface(view_size))
804 return;
805 } else {
806 TRACE_EVENT0("renderer_host", "WaitForSurface::Timeout");
807 break;
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));
817 #endif
819 bool RenderWidgetHostImpl::ScheduleComposite() {
820 if (is_hidden_ || current_size_.IsEmpty() || repaint_ack_pending_ ||
821 resize_ack_pending_) {
822 return false;
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_));
831 return true;
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);
861 ui::LatencyInfo latency_info =
862 CreateRWHLatencyInfoIfNotExist(&ui_latency, mouse_event.type);
864 for (size_t i = 0; i < mouse_event_callbacks_.size(); ++i) {
865 if (mouse_event_callbacks_[i].Run(mouse_event))
866 return;
869 if (IgnoreInputEvents())
870 return;
872 if (touch_emulator_ && touch_emulator_->HandleMouseEvent(mouse_event))
873 return;
875 input_router_->SendMouseEvent(MouseEventWithLatencyInfo(mouse_event,
876 latency_info));
879 void RenderWidgetHostImpl::OnPointerEventActivate() {
882 void RenderWidgetHostImpl::ForwardWheelEvent(
883 const WebMouseWheelEvent& wheel_event) {
884 ForwardWheelEventWithLatencyInfo(wheel_event, ui::LatencyInfo());
887 void RenderWidgetHostImpl::ForwardWheelEventWithLatencyInfo(
888 const blink::WebMouseWheelEvent& wheel_event,
889 const ui::LatencyInfo& ui_latency) {
890 TRACE_EVENT0("input", "RenderWidgetHostImpl::ForwardWheelEvent");
892 ui::LatencyInfo latency_info =
893 CreateRWHLatencyInfoIfNotExist(&ui_latency, wheel_event.type);
895 if (IgnoreInputEvents())
896 return;
898 if (touch_emulator_ && touch_emulator_->HandleMouseWheelEvent(wheel_event))
899 return;
901 input_router_->SendWheelEvent(MouseWheelEventWithLatencyInfo(wheel_event,
902 latency_info));
905 void RenderWidgetHostImpl::ForwardGestureEvent(
906 const blink::WebGestureEvent& gesture_event) {
907 ForwardGestureEventWithLatencyInfo(gesture_event, ui::LatencyInfo());
910 void RenderWidgetHostImpl::ForwardGestureEventWithLatencyInfo(
911 const blink::WebGestureEvent& gesture_event,
912 const ui::LatencyInfo& ui_latency) {
913 TRACE_EVENT0("input", "RenderWidgetHostImpl::ForwardGestureEvent");
914 // Early out if necessary, prior to performing latency logic.
915 if (IgnoreInputEvents())
916 return;
918 if (delegate_->PreHandleGestureEvent(gesture_event))
919 return;
921 ui::LatencyInfo latency_info =
922 CreateRWHLatencyInfoIfNotExist(&ui_latency, gesture_event.type);
924 if (gesture_event.type == blink::WebInputEvent::GestureScrollUpdate) {
925 latency_info.AddLatencyNumber(
926 ui::INPUT_EVENT_LATENCY_SCROLL_UPDATE_RWH_COMPONENT,
927 GetLatencyComponentId(),
928 ++last_input_number_);
930 // Make a copy of the INPUT_EVENT_LATENCY_ORIGINAL_COMPONENT with a
931 // different name INPUT_EVENT_LATENCY_SCROLL_UPDATE_ORIGINAL_COMPONENT.
932 // So we can track the latency specifically for scroll update events.
933 ui::LatencyInfo::LatencyComponent original_component;
934 if (latency_info.FindLatency(ui::INPUT_EVENT_LATENCY_ORIGINAL_COMPONENT,
936 &original_component)) {
937 latency_info.AddLatencyNumberWithTimestamp(
938 ui::INPUT_EVENT_LATENCY_SCROLL_UPDATE_ORIGINAL_COMPONENT,
939 GetLatencyComponentId(),
940 original_component.sequence_number,
941 original_component.event_time,
942 original_component.event_count);
946 GestureEventWithLatencyInfo gesture_with_latency(gesture_event, latency_info);
947 input_router_->SendGestureEvent(gesture_with_latency);
950 void RenderWidgetHostImpl::ForwardEmulatedTouchEvent(
951 const blink::WebTouchEvent& touch_event) {
952 TRACE_EVENT0("input", "RenderWidgetHostImpl::ForwardEmulatedTouchEvent");
953 ui::LatencyInfo latency_info =
954 CreateRWHLatencyInfoIfNotExist(NULL, touch_event.type);
955 TouchEventWithLatencyInfo touch_with_latency(touch_event, latency_info);
956 input_router_->SendTouchEvent(touch_with_latency);
959 void RenderWidgetHostImpl::ForwardTouchEventWithLatencyInfo(
960 const blink::WebTouchEvent& touch_event,
961 const ui::LatencyInfo& ui_latency) {
962 TRACE_EVENT0("input", "RenderWidgetHostImpl::ForwardTouchEvent");
964 // Always forward TouchEvents for touch stream consistency. They will be
965 // ignored if appropriate in FilterInputEvent().
967 ui::LatencyInfo latency_info =
968 CreateRWHLatencyInfoIfNotExist(&ui_latency, touch_event.type);
969 TouchEventWithLatencyInfo touch_with_latency(touch_event, latency_info);
971 if (touch_emulator_ &&
972 touch_emulator_->HandleTouchEvent(touch_with_latency.event)) {
973 if (view_) {
974 view_->ProcessAckedTouchEvent(
975 touch_with_latency, INPUT_EVENT_ACK_STATE_CONSUMED);
977 return;
980 input_router_->SendTouchEvent(touch_with_latency);
983 void RenderWidgetHostImpl::ForwardKeyboardEvent(
984 const NativeWebKeyboardEvent& key_event) {
985 TRACE_EVENT0("input", "RenderWidgetHostImpl::ForwardKeyboardEvent");
986 if (IgnoreInputEvents())
987 return;
989 if (!process_->HasConnection())
990 return;
992 // First, let keypress listeners take a shot at handling the event. If a
993 // listener handles the event, it should not be propagated to the renderer.
994 if (KeyPressListenersHandleEvent(key_event)) {
995 // Some keypresses that are accepted by the listener might have follow up
996 // char events, which should be ignored.
997 if (key_event.type == WebKeyboardEvent::RawKeyDown)
998 suppress_next_char_events_ = true;
999 return;
1002 if (key_event.type == WebKeyboardEvent::Char &&
1003 (key_event.windowsKeyCode == ui::VKEY_RETURN ||
1004 key_event.windowsKeyCode == ui::VKEY_SPACE)) {
1005 OnUserGesture();
1008 // Double check the type to make sure caller hasn't sent us nonsense that
1009 // will mess up our key queue.
1010 if (!WebInputEvent::isKeyboardEventType(key_event.type))
1011 return;
1013 if (suppress_next_char_events_) {
1014 // If preceding RawKeyDown event was handled by the browser, then we need
1015 // suppress all Char events generated by it. Please note that, one
1016 // RawKeyDown event may generate multiple Char events, so we can't reset
1017 // |suppress_next_char_events_| until we get a KeyUp or a RawKeyDown.
1018 if (key_event.type == WebKeyboardEvent::Char)
1019 return;
1020 // We get a KeyUp or a RawKeyDown event.
1021 suppress_next_char_events_ = false;
1024 bool is_shortcut = false;
1026 // Only pre-handle the key event if it's not handled by the input method.
1027 if (delegate_ && !key_event.skip_in_browser) {
1028 // We need to set |suppress_next_char_events_| to true if
1029 // PreHandleKeyboardEvent() returns true, but |this| may already be
1030 // destroyed at that time. So set |suppress_next_char_events_| true here,
1031 // then revert it afterwards when necessary.
1032 if (key_event.type == WebKeyboardEvent::RawKeyDown)
1033 suppress_next_char_events_ = true;
1035 // Tab switching/closing accelerators aren't sent to the renderer to avoid
1036 // a hung/malicious renderer from interfering.
1037 if (delegate_->PreHandleKeyboardEvent(key_event, &is_shortcut))
1038 return;
1040 if (key_event.type == WebKeyboardEvent::RawKeyDown)
1041 suppress_next_char_events_ = false;
1044 if (touch_emulator_ && touch_emulator_->HandleKeyboardEvent(key_event))
1045 return;
1047 input_router_->SendKeyboardEvent(
1048 key_event,
1049 CreateRWHLatencyInfoIfNotExist(NULL, key_event.type),
1050 is_shortcut);
1053 void RenderWidgetHostImpl::QueueSyntheticGesture(
1054 scoped_ptr<SyntheticGesture> synthetic_gesture,
1055 const base::Callback<void(SyntheticGesture::Result)>& on_complete) {
1056 if (!synthetic_gesture_controller_ && view_) {
1057 synthetic_gesture_controller_.reset(
1058 new SyntheticGestureController(
1059 view_->CreateSyntheticGestureTarget().Pass()));
1061 if (synthetic_gesture_controller_) {
1062 synthetic_gesture_controller_->QueueSyntheticGesture(
1063 synthetic_gesture.Pass(), on_complete);
1067 void RenderWidgetHostImpl::SetCursor(const WebCursor& cursor) {
1068 if (!view_)
1069 return;
1070 view_->UpdateCursor(cursor);
1073 void RenderWidgetHostImpl::ShowContextMenuAtPoint(const gfx::Point& point) {
1074 Send(new ViewMsg_ShowContextMenu(
1075 GetRoutingID(), ui::MENU_SOURCE_MOUSE, point));
1078 void RenderWidgetHostImpl::SendCursorVisibilityState(bool is_visible) {
1079 Send(new InputMsg_CursorVisibilityChange(GetRoutingID(), is_visible));
1082 int64 RenderWidgetHostImpl::GetLatencyComponentId() {
1083 return GetRoutingID() | (static_cast<int64>(GetProcess()->GetID()) << 32);
1086 // static
1087 void RenderWidgetHostImpl::DisableResizeAckCheckForTesting() {
1088 g_check_for_pending_resize_ack = false;
1091 ui::LatencyInfo RenderWidgetHostImpl::CreateRWHLatencyInfoIfNotExist(
1092 const ui::LatencyInfo* original, WebInputEvent::Type type) {
1093 ui::LatencyInfo info;
1094 if (original)
1095 info = *original;
1096 // In Aura, gesture event will already carry its original touch event's
1097 // INPUT_EVENT_LATENCY_RWH_COMPONENT.
1098 if (!info.FindLatency(ui::INPUT_EVENT_LATENCY_BEGIN_RWH_COMPONENT,
1099 GetLatencyComponentId(),
1100 NULL)) {
1101 info.AddLatencyNumber(ui::INPUT_EVENT_LATENCY_BEGIN_RWH_COMPONENT,
1102 GetLatencyComponentId(),
1103 ++last_input_number_);
1104 info.TraceEventType(WebInputEventTraits::GetName(type));
1106 return info;
1110 void RenderWidgetHostImpl::AddKeyPressEventCallback(
1111 const KeyPressEventCallback& callback) {
1112 key_press_event_callbacks_.push_back(callback);
1115 void RenderWidgetHostImpl::RemoveKeyPressEventCallback(
1116 const KeyPressEventCallback& callback) {
1117 for (size_t i = 0; i < key_press_event_callbacks_.size(); ++i) {
1118 if (key_press_event_callbacks_[i].Equals(callback)) {
1119 key_press_event_callbacks_.erase(
1120 key_press_event_callbacks_.begin() + i);
1121 return;
1126 void RenderWidgetHostImpl::AddMouseEventCallback(
1127 const MouseEventCallback& callback) {
1128 mouse_event_callbacks_.push_back(callback);
1131 void RenderWidgetHostImpl::RemoveMouseEventCallback(
1132 const MouseEventCallback& callback) {
1133 for (size_t i = 0; i < mouse_event_callbacks_.size(); ++i) {
1134 if (mouse_event_callbacks_[i].Equals(callback)) {
1135 mouse_event_callbacks_.erase(mouse_event_callbacks_.begin() + i);
1136 return;
1141 void RenderWidgetHostImpl::GetWebScreenInfo(blink::WebScreenInfo* result) {
1142 TRACE_EVENT0("renderer_host", "RenderWidgetHostImpl::GetWebScreenInfo");
1143 if (view_)
1144 view_->GetScreenInfo(result);
1145 else
1146 RenderWidgetHostViewBase::GetDefaultScreenInfo(result);
1147 screen_info_out_of_date_ = false;
1150 const NativeWebKeyboardEvent*
1151 RenderWidgetHostImpl::GetLastKeyboardEvent() const {
1152 return input_router_->GetLastKeyboardEvent();
1155 void RenderWidgetHostImpl::NotifyScreenInfoChanged() {
1156 // The resize message (which may not happen immediately) will carry with it
1157 // the screen info as well as the new size (if the screen has changed scale
1158 // factor).
1159 InvalidateScreenInfo();
1160 WasResized();
1163 void RenderWidgetHostImpl::InvalidateScreenInfo() {
1164 screen_info_out_of_date_ = true;
1165 screen_info_.reset();
1168 void RenderWidgetHostImpl::GetSnapshotFromBrowser(
1169 const base::Callback<void(const unsigned char*,size_t)> callback) {
1170 int id = next_browser_snapshot_id_++;
1171 pending_browser_snapshots_.insert(std::make_pair(id, callback));
1172 Send(new ViewMsg_ForceRedraw(GetRoutingID(), id));
1175 void RenderWidgetHostImpl::OnSelectionChanged(const base::string16& text,
1176 size_t offset,
1177 const gfx::Range& range) {
1178 if (view_)
1179 view_->SelectionChanged(text, offset, range);
1182 void RenderWidgetHostImpl::OnSelectionBoundsChanged(
1183 const ViewHostMsg_SelectionBounds_Params& params) {
1184 if (view_) {
1185 view_->SelectionBoundsChanged(params);
1189 void RenderWidgetHostImpl::UpdateVSyncParameters(base::TimeTicks timebase,
1190 base::TimeDelta interval) {
1191 Send(new ViewMsg_UpdateVSyncParameters(GetRoutingID(), timebase, interval));
1194 void RenderWidgetHostImpl::RendererExited(base::TerminationStatus status,
1195 int exit_code) {
1196 // Clearing this flag causes us to re-create the renderer when recovering
1197 // from a crashed renderer.
1198 renderer_initialized_ = false;
1200 waiting_for_screen_rects_ack_ = false;
1202 // Must reset these to ensure that keyboard events work with a new renderer.
1203 suppress_next_char_events_ = false;
1205 // Reset some fields in preparation for recovering from a crash.
1206 ResetSizeAndRepaintPendingFlags();
1207 current_size_.SetSize(0, 0);
1208 // After the renderer crashes, the view is destroyed and so the
1209 // RenderWidgetHost cannot track its visibility anymore. We assume such
1210 // RenderWidgetHost to be visible for the sake of internal accounting - be
1211 // careful about changing this - see http://crbug.com/401859.
1213 // We need to at least make sure that the RenderProcessHost is notified about
1214 // the |is_hidden_| change, so that the renderer will have correct visibility
1215 // set when respawned.
1216 if (is_hidden_) {
1217 process_->WidgetRestored();
1218 is_hidden_ = false;
1221 // Reset this to ensure the hung renderer mechanism is working properly.
1222 in_flight_event_count_ = 0;
1224 if (view_) {
1225 GpuSurfaceTracker::Get()->SetSurfaceHandle(surface_id_,
1226 gfx::GLSurfaceHandle());
1227 view_->RenderProcessGone(status, exit_code);
1228 view_ = NULL; // The View should be deleted by RenderProcessGone.
1229 view_weak_.reset();
1232 // Reconstruct the input router to ensure that it has fresh state for a new
1233 // renderer. Otherwise it may be stuck waiting for the old renderer to ack an
1234 // event. (In particular, the above call to view_->RenderProcessGone will
1235 // destroy the aura window, which may dispatch a synthetic mouse move.)
1236 input_router_.reset(new InputRouterImpl(
1237 process_, this, this, routing_id_, GetInputRouterConfigForPlatform()));
1239 synthetic_gesture_controller_.reset();
1242 void RenderWidgetHostImpl::UpdateTextDirection(WebTextDirection direction) {
1243 text_direction_updated_ = true;
1244 text_direction_ = direction;
1247 void RenderWidgetHostImpl::CancelUpdateTextDirection() {
1248 if (text_direction_updated_)
1249 text_direction_canceled_ = true;
1252 void RenderWidgetHostImpl::NotifyTextDirection() {
1253 if (text_direction_updated_) {
1254 if (!text_direction_canceled_)
1255 Send(new ViewMsg_SetTextDirection(GetRoutingID(), text_direction_));
1256 text_direction_updated_ = false;
1257 text_direction_canceled_ = false;
1261 void RenderWidgetHostImpl::SetInputMethodActive(bool activate) {
1262 input_method_active_ = activate;
1263 Send(new ViewMsg_SetInputMethodActive(GetRoutingID(), activate));
1266 void RenderWidgetHostImpl::CandidateWindowShown() {
1267 Send(new ViewMsg_CandidateWindowShown(GetRoutingID()));
1270 void RenderWidgetHostImpl::CandidateWindowUpdated() {
1271 Send(new ViewMsg_CandidateWindowUpdated(GetRoutingID()));
1274 void RenderWidgetHostImpl::CandidateWindowHidden() {
1275 Send(new ViewMsg_CandidateWindowHidden(GetRoutingID()));
1278 void RenderWidgetHostImpl::ImeSetComposition(
1279 const base::string16& text,
1280 const std::vector<blink::WebCompositionUnderline>& underlines,
1281 int selection_start,
1282 int selection_end) {
1283 Send(new InputMsg_ImeSetComposition(
1284 GetRoutingID(), text, underlines, selection_start, selection_end));
1287 void RenderWidgetHostImpl::ImeConfirmComposition(
1288 const base::string16& text,
1289 const gfx::Range& replacement_range,
1290 bool keep_selection) {
1291 Send(new InputMsg_ImeConfirmComposition(
1292 GetRoutingID(), text, replacement_range, keep_selection));
1295 void RenderWidgetHostImpl::ImeCancelComposition() {
1296 Send(new InputMsg_ImeSetComposition(GetRoutingID(), base::string16(),
1297 std::vector<blink::WebCompositionUnderline>(), 0, 0));
1300 gfx::Rect RenderWidgetHostImpl::GetRootWindowResizerRect() const {
1301 return gfx::Rect();
1304 void RenderWidgetHostImpl::RequestToLockMouse(bool user_gesture,
1305 bool last_unlocked_by_target) {
1306 // Directly reject to lock the mouse. Subclass can override this method to
1307 // decide whether to allow mouse lock or not.
1308 GotResponseToLockMouseRequest(false);
1311 void RenderWidgetHostImpl::RejectMouseLockOrUnlockIfNecessary() {
1312 DCHECK(!pending_mouse_lock_request_ || !IsMouseLocked());
1313 if (pending_mouse_lock_request_) {
1314 pending_mouse_lock_request_ = false;
1315 Send(new ViewMsg_LockMouse_ACK(routing_id_, false));
1316 } else if (IsMouseLocked()) {
1317 view_->UnlockMouse();
1321 bool RenderWidgetHostImpl::IsMouseLocked() const {
1322 return view_ ? view_->IsMouseLocked() : false;
1325 bool RenderWidgetHostImpl::IsFullscreen() const {
1326 return false;
1329 void RenderWidgetHostImpl::SetShouldAutoResize(bool enable) {
1330 should_auto_resize_ = enable;
1333 void RenderWidgetHostImpl::Destroy() {
1334 NotificationService::current()->Notify(
1335 NOTIFICATION_RENDER_WIDGET_HOST_DESTROYED,
1336 Source<RenderWidgetHost>(this),
1337 NotificationService::NoDetails());
1339 // Tell the view to die.
1340 // Note that in the process of the view shutting down, it can call a ton
1341 // of other messages on us. So if you do any other deinitialization here,
1342 // do it after this call to view_->Destroy().
1343 if (view_)
1344 view_->Destroy();
1346 delete this;
1349 void RenderWidgetHostImpl::RendererIsUnresponsive() {
1350 NotificationService::current()->Notify(
1351 NOTIFICATION_RENDER_WIDGET_HOST_HANG,
1352 Source<RenderWidgetHost>(this),
1353 NotificationService::NoDetails());
1354 is_unresponsive_ = true;
1355 NotifyRendererUnresponsive();
1358 void RenderWidgetHostImpl::RendererIsResponsive() {
1359 if (is_unresponsive_) {
1360 is_unresponsive_ = false;
1361 NotifyRendererResponsive();
1365 void RenderWidgetHostImpl::OnRenderViewReady() {
1366 SendScreenRects();
1367 WasResized();
1370 void RenderWidgetHostImpl::OnRenderProcessGone(int status, int exit_code) {
1371 // TODO(evanm): This synchronously ends up calling "delete this".
1372 // Is that really what we want in response to this message? I'm matching
1373 // previous behavior of the code here.
1374 Destroy();
1377 void RenderWidgetHostImpl::OnClose() {
1378 Shutdown();
1381 void RenderWidgetHostImpl::OnSetTooltipText(
1382 const base::string16& tooltip_text,
1383 WebTextDirection text_direction_hint) {
1384 // First, add directionality marks around tooltip text if necessary.
1385 // A naive solution would be to simply always wrap the text. However, on
1386 // windows, Unicode directional embedding characters can't be displayed on
1387 // systems that lack RTL fonts and are instead displayed as empty squares.
1389 // To get around this we only wrap the string when we deem it necessary i.e.
1390 // when the locale direction is different than the tooltip direction hint.
1392 // Currently, we use element's directionality as the tooltip direction hint.
1393 // An alternate solution would be to set the overall directionality based on
1394 // trying to detect the directionality from the tooltip text rather than the
1395 // element direction. One could argue that would be a preferable solution
1396 // but we use the current approach to match Fx & IE's behavior.
1397 base::string16 wrapped_tooltip_text = tooltip_text;
1398 if (!tooltip_text.empty()) {
1399 if (text_direction_hint == blink::WebTextDirectionLeftToRight) {
1400 // Force the tooltip to have LTR directionality.
1401 wrapped_tooltip_text =
1402 base::i18n::GetDisplayStringInLTRDirectionality(wrapped_tooltip_text);
1403 } else if (text_direction_hint == blink::WebTextDirectionRightToLeft &&
1404 !base::i18n::IsRTL()) {
1405 // Force the tooltip to have RTL directionality.
1406 base::i18n::WrapStringWithRTLFormatting(&wrapped_tooltip_text);
1409 if (GetView())
1410 view_->SetTooltipText(wrapped_tooltip_text);
1413 void RenderWidgetHostImpl::OnUpdateScreenRectsAck() {
1414 waiting_for_screen_rects_ack_ = false;
1415 if (!view_)
1416 return;
1418 if (view_->GetViewBounds() == last_view_screen_rect_ &&
1419 view_->GetBoundsInRootWindow() == last_window_screen_rect_) {
1420 return;
1423 SendScreenRects();
1426 void RenderWidgetHostImpl::OnRequestMove(const gfx::Rect& pos) {
1427 if (view_) {
1428 view_->SetBounds(pos);
1429 Send(new ViewMsg_Move_ACK(routing_id_));
1433 bool RenderWidgetHostImpl::OnSwapCompositorFrame(
1434 const IPC::Message& message) {
1435 // This trace event is used in
1436 // chrome/browser/extensions/api/cast_streaming/performance_test.cc
1437 TRACE_EVENT0("test_fps",
1438 TRACE_DISABLED_BY_DEFAULT("OnSwapCompositorFrame"));
1439 ViewHostMsg_SwapCompositorFrame::Param param;
1440 if (!ViewHostMsg_SwapCompositorFrame::Read(&message, &param))
1441 return false;
1442 scoped_ptr<cc::CompositorFrame> frame(new cc::CompositorFrame);
1443 uint32 output_surface_id = param.a;
1444 param.b.AssignTo(frame.get());
1445 std::vector<IPC::Message> messages_to_deliver_with_frame;
1446 messages_to_deliver_with_frame.swap(param.c);
1448 for (size_t i = 0; i < frame->metadata.latency_info.size(); i++)
1449 AddLatencyInfoComponentIds(&frame->metadata.latency_info[i]);
1451 input_router_->OnViewUpdated(
1452 GetInputRouterViewFlagsFromCompositorFrameMetadata(frame->metadata));
1454 if (view_) {
1455 view_->OnSwapCompositorFrame(output_surface_id, frame.Pass());
1456 view_->DidReceiveRendererFrame();
1457 } else {
1458 cc::CompositorFrameAck ack;
1459 if (frame->gl_frame_data) {
1460 ack.gl_frame_data = frame->gl_frame_data.Pass();
1461 ack.gl_frame_data->sync_point = 0;
1462 } else if (frame->delegated_frame_data) {
1463 cc::TransferableResource::ReturnResources(
1464 frame->delegated_frame_data->resource_list,
1465 &ack.resources);
1466 } else if (frame->software_frame_data) {
1467 ack.last_software_frame_id = frame->software_frame_data->id;
1469 SendSwapCompositorFrameAck(routing_id_, output_surface_id,
1470 process_->GetID(), ack);
1473 RenderProcessHost* rph = GetProcess();
1474 for (std::vector<IPC::Message>::const_iterator i =
1475 messages_to_deliver_with_frame.begin();
1476 i != messages_to_deliver_with_frame.end();
1477 ++i) {
1478 rph->OnMessageReceived(*i);
1479 if (i->dispatch_error())
1480 rph->OnBadMessageReceived(*i);
1482 messages_to_deliver_with_frame.clear();
1484 return true;
1487 void RenderWidgetHostImpl::OnFlingingStopped() {
1488 if (view_)
1489 view_->DidStopFlinging();
1492 void RenderWidgetHostImpl::OnUpdateRect(
1493 const ViewHostMsg_UpdateRect_Params& params) {
1494 TRACE_EVENT0("renderer_host", "RenderWidgetHostImpl::OnUpdateRect");
1495 TimeTicks paint_start = TimeTicks::Now();
1497 // Update our knowledge of the RenderWidget's size.
1498 current_size_ = params.view_size;
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(
1530 FROM_HERE,
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.
1554 if (view_)
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
1564 // us more data.
1565 if (is_hidden_)
1566 return;
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);
1571 if (is_resize_ack)
1572 WasResized();
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 (!base::CommandLine::ForCurrentProcess()->HasSwitch(
1584 cc::switches::kEnableGpuBenchmarking)) {
1585 RecordAction(base::UserMetricsAction("BadMessageTerminate_RWH7"));
1586 GetProcess()->ReceivedBadMessage();
1587 return;
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) {
1609 SetCursor(cursor);
1612 void RenderWidgetHostImpl::SetTouchEventEmulationEnabled(bool enabled) {
1613 if (enabled) {
1614 if (!touch_emulator_)
1615 touch_emulator_.reset(new TouchEmulator(this));
1616 touch_emulator_->Enable();
1617 } else {
1618 if (touch_emulator_)
1619 touch_emulator_->Disable();
1623 void RenderWidgetHostImpl::OnTextInputStateChanged(
1624 const ViewHostMsg_TextInputState_Params& params) {
1625 if (view_)
1626 view_->TextInputStateChanged(params);
1629 #if defined(OS_MACOSX) || defined(USE_AURA)
1630 void RenderWidgetHostImpl::OnImeCompositionRangeChanged(
1631 const gfx::Range& range,
1632 const std::vector<gfx::Rect>& character_bounds) {
1633 if (view_)
1634 view_->ImeCompositionRangeChanged(range, character_bounds);
1636 #endif
1638 void RenderWidgetHostImpl::OnImeCancelComposition() {
1639 if (view_)
1640 view_->ImeCancelComposition();
1643 void RenderWidgetHostImpl::OnLockMouse(bool user_gesture,
1644 bool last_unlocked_by_target,
1645 bool privileged) {
1647 if (pending_mouse_lock_request_) {
1648 Send(new ViewMsg_LockMouse_ACK(routing_id_, false));
1649 return;
1650 } else if (IsMouseLocked()) {
1651 Send(new ViewMsg_LockMouse_ACK(routing_id_, true));
1652 return;
1655 pending_mouse_lock_request_ = true;
1656 if (privileged && allow_privileged_mouse_lock_) {
1657 // Directly approve to lock the mouse.
1658 GotResponseToLockMouseRequest(true);
1659 } else {
1660 RequestToLockMouse(user_gesture, last_unlocked_by_target);
1664 void RenderWidgetHostImpl::OnUnlockMouse() {
1665 RejectMouseLockOrUnlockIfNecessary();
1668 void RenderWidgetHostImpl::OnShowDisambiguationPopup(
1669 const gfx::Rect& rect,
1670 const gfx::Size& size,
1671 const cc::SharedBitmapId& id) {
1672 DCHECK(!rect.IsEmpty());
1673 DCHECK(!size.IsEmpty());
1675 scoped_ptr<cc::SharedBitmap> bitmap =
1676 HostSharedBitmapManager::current()->GetSharedBitmapFromId(size, id);
1677 if (!bitmap) {
1678 RecordAction(base::UserMetricsAction("BadMessageTerminate_RWH6"));
1679 GetProcess()->ReceivedBadMessage();
1680 return;
1683 DCHECK(bitmap->pixels());
1685 SkImageInfo info = SkImageInfo::MakeN32Premul(size.width(), size.height());
1686 SkBitmap zoomed_bitmap;
1687 zoomed_bitmap.installPixels(info, bitmap->pixels(), info.minRowBytes());
1689 #if defined(OS_ANDROID)
1690 if (view_)
1691 view_->ShowDisambiguationPopup(rect, zoomed_bitmap);
1692 #else
1693 NOTIMPLEMENTED();
1694 #endif
1696 zoomed_bitmap.setPixels(0);
1697 Send(new ViewMsg_ReleaseDisambiguationPopupBitmap(GetRoutingID(), id));
1700 #if defined(OS_WIN)
1701 void RenderWidgetHostImpl::OnWindowlessPluginDummyWindowCreated(
1702 gfx::NativeViewId dummy_activation_window) {
1703 HWND hwnd = reinterpret_cast<HWND>(dummy_activation_window);
1705 // This may happen as a result of a race condition when the plugin is going
1706 // away.
1707 wchar_t window_title[MAX_PATH + 1] = {0};
1708 if (!IsWindow(hwnd) ||
1709 !GetWindowText(hwnd, window_title, arraysize(window_title)) ||
1710 lstrcmpiW(window_title, kDummyActivationWindowName) != 0) {
1711 return;
1714 #if defined(USE_AURA)
1715 SetParent(hwnd,
1716 reinterpret_cast<HWND>(view_->GetParentForWindowlessPlugin()));
1717 #else
1718 SetParent(hwnd, reinterpret_cast<HWND>(GetNativeViewId()));
1719 #endif
1720 dummy_windows_for_activation_.push_back(hwnd);
1723 void RenderWidgetHostImpl::OnWindowlessPluginDummyWindowDestroyed(
1724 gfx::NativeViewId dummy_activation_window) {
1725 HWND hwnd = reinterpret_cast<HWND>(dummy_activation_window);
1726 std::list<HWND>::iterator i = dummy_windows_for_activation_.begin();
1727 for (; i != dummy_windows_for_activation_.end(); ++i) {
1728 if ((*i) == hwnd) {
1729 dummy_windows_for_activation_.erase(i);
1730 return;
1733 NOTREACHED() << "Unknown dummy window";
1735 #endif
1737 void RenderWidgetHostImpl::SetIgnoreInputEvents(bool ignore_input_events) {
1738 ignore_input_events_ = ignore_input_events;
1741 bool RenderWidgetHostImpl::KeyPressListenersHandleEvent(
1742 const NativeWebKeyboardEvent& event) {
1743 if (event.skip_in_browser || event.type != WebKeyboardEvent::RawKeyDown)
1744 return false;
1746 for (size_t i = 0; i < key_press_event_callbacks_.size(); i++) {
1747 size_t original_size = key_press_event_callbacks_.size();
1748 if (key_press_event_callbacks_[i].Run(event))
1749 return true;
1751 // Check whether the callback that just ran removed itself, in which case
1752 // the iterator needs to be decremented to properly account for the removal.
1753 size_t current_size = key_press_event_callbacks_.size();
1754 if (current_size != original_size) {
1755 DCHECK_EQ(original_size - 1, current_size);
1756 --i;
1760 return false;
1763 InputEventAckState RenderWidgetHostImpl::FilterInputEvent(
1764 const blink::WebInputEvent& event, const ui::LatencyInfo& latency_info) {
1765 // Don't ignore touch cancel events, since they may be sent while input
1766 // events are being ignored in order to keep the renderer from getting
1767 // confused about how many touches are active.
1768 if (IgnoreInputEvents() && event.type != WebInputEvent::TouchCancel)
1769 return INPUT_EVENT_ACK_STATE_NO_CONSUMER_EXISTS;
1771 if (!process_->HasConnection())
1772 return INPUT_EVENT_ACK_STATE_UNKNOWN;
1774 if (event.type == WebInputEvent::MouseDown)
1775 OnUserGesture();
1777 return view_ ? view_->FilterInputEvent(event)
1778 : INPUT_EVENT_ACK_STATE_NOT_CONSUMED;
1781 void RenderWidgetHostImpl::IncrementInFlightEventCount() {
1782 StartHangMonitorTimeout(
1783 TimeDelta::FromMilliseconds(hung_renderer_delay_ms_));
1784 increment_in_flight_event_count();
1787 void RenderWidgetHostImpl::DecrementInFlightEventCount() {
1788 DCHECK_GE(in_flight_event_count_, 0);
1789 if (decrement_in_flight_event_count() <= 0) {
1790 // Cancel pending hung renderer checks since the renderer is responsive.
1791 StopHangMonitorTimeout();
1792 } else {
1793 // The renderer is responsive, but there are in-flight events to wait for.
1794 RestartHangMonitorTimeout();
1798 void RenderWidgetHostImpl::OnHasTouchEventHandlers(bool has_handlers) {
1799 has_touch_handler_ = has_handlers;
1802 void RenderWidgetHostImpl::DidFlush() {
1803 if (synthetic_gesture_controller_)
1804 synthetic_gesture_controller_->OnDidFlushInput();
1805 if (view_)
1806 view_->OnDidFlushInput();
1809 void RenderWidgetHostImpl::DidOverscroll(const DidOverscrollParams& params) {
1810 if (view_)
1811 view_->DidOverscroll(params);
1814 void RenderWidgetHostImpl::OnKeyboardEventAck(
1815 const NativeWebKeyboardEvent& event,
1816 InputEventAckState ack_result) {
1817 #if defined(OS_MACOSX)
1818 if (!is_hidden() && view_ && view_->PostProcessEventForPluginIme(event))
1819 return;
1820 #endif
1822 // We only send unprocessed key event upwards if we are not hidden,
1823 // because the user has moved away from us and no longer expect any effect
1824 // of this key event.
1825 const bool processed = (INPUT_EVENT_ACK_STATE_CONSUMED == ack_result);
1826 if (delegate_ && !processed && !is_hidden() && !event.skip_in_browser) {
1827 delegate_->HandleKeyboardEvent(event);
1829 // WARNING: This RenderWidgetHostImpl can be deallocated at this point
1830 // (i.e. in the case of Ctrl+W, where the call to
1831 // HandleKeyboardEvent destroys this RenderWidgetHostImpl).
1835 void RenderWidgetHostImpl::OnWheelEventAck(
1836 const MouseWheelEventWithLatencyInfo& wheel_event,
1837 InputEventAckState ack_result) {
1838 if (!wheel_event.latency.FindLatency(
1839 ui::INPUT_EVENT_LATENCY_RENDERING_SCHEDULED_COMPONENT, 0, NULL)) {
1840 // MouseWheelEvent latency ends when it is acked but does not cause any
1841 // rendering scheduled.
1842 ui::LatencyInfo latency = wheel_event.latency;
1843 latency.AddLatencyNumber(
1844 ui::INPUT_EVENT_LATENCY_TERMINATED_MOUSE_COMPONENT, 0, 0);
1847 if (!is_hidden() && view_) {
1848 if (ack_result != INPUT_EVENT_ACK_STATE_CONSUMED &&
1849 delegate_->HandleWheelEvent(wheel_event.event)) {
1850 ack_result = INPUT_EVENT_ACK_STATE_CONSUMED;
1852 view_->WheelEventAck(wheel_event.event, ack_result);
1856 void RenderWidgetHostImpl::OnGestureEventAck(
1857 const GestureEventWithLatencyInfo& event,
1858 InputEventAckState ack_result) {
1859 if (!event.latency.FindLatency(
1860 ui::INPUT_EVENT_LATENCY_RENDERING_SCHEDULED_COMPONENT, 0, NULL)) {
1861 // GestureEvent latency ends when it is acked but does not cause any
1862 // rendering scheduled.
1863 ui::LatencyInfo latency = event.latency;
1864 latency.AddLatencyNumber(
1865 ui::INPUT_EVENT_LATENCY_TERMINATED_GESTURE_COMPONENT, 0 ,0);
1868 if (ack_result != INPUT_EVENT_ACK_STATE_CONSUMED) {
1869 if (delegate_->HandleGestureEvent(event.event))
1870 ack_result = INPUT_EVENT_ACK_STATE_CONSUMED;
1873 if (view_)
1874 view_->GestureEventAck(event.event, ack_result);
1877 void RenderWidgetHostImpl::OnTouchEventAck(
1878 const TouchEventWithLatencyInfo& event,
1879 InputEventAckState ack_result) {
1880 TouchEventWithLatencyInfo touch_event = event;
1881 touch_event.latency.AddLatencyNumber(
1882 ui::INPUT_EVENT_LATENCY_ACKED_TOUCH_COMPONENT, 0, 0);
1883 // TouchEvent latency ends at ack if it didn't cause any rendering.
1884 if (!touch_event.latency.FindLatency(
1885 ui::INPUT_EVENT_LATENCY_RENDERING_SCHEDULED_COMPONENT, 0, NULL)) {
1886 touch_event.latency.AddLatencyNumber(
1887 ui::INPUT_EVENT_LATENCY_TERMINATED_TOUCH_COMPONENT, 0, 0);
1889 ComputeTouchLatency(touch_event.latency);
1891 if (touch_emulator_ &&
1892 touch_emulator_->HandleTouchEventAck(event.event, ack_result)) {
1893 return;
1896 if (view_)
1897 view_->ProcessAckedTouchEvent(touch_event, ack_result);
1900 void RenderWidgetHostImpl::OnUnexpectedEventAck(UnexpectedEventAckType type) {
1901 if (type == BAD_ACK_MESSAGE) {
1902 RecordAction(base::UserMetricsAction("BadMessageTerminate_RWH2"));
1903 process_->ReceivedBadMessage();
1904 } else if (type == UNEXPECTED_EVENT_TYPE) {
1905 suppress_next_char_events_ = false;
1909 void RenderWidgetHostImpl::OnSyntheticGestureCompleted(
1910 SyntheticGesture::Result result) {
1911 Send(new InputMsg_SyntheticGestureCompleted(GetRoutingID()));
1914 bool RenderWidgetHostImpl::IgnoreInputEvents() const {
1915 return ignore_input_events_ || process_->IgnoreInputEvents();
1918 bool RenderWidgetHostImpl::ShouldForwardTouchEvent() const {
1919 // It's important that the emulator sees a complete native touch stream,
1920 // allowing it to perform touch filtering as appropriate.
1921 // TODO(dgozman): Remove when touch stream forwarding issues resolved, see
1922 // crbug.com/375940.
1923 if (touch_emulator_ && touch_emulator_->enabled())
1924 return true;
1926 return input_router_->ShouldForwardTouchEvent();
1929 void RenderWidgetHostImpl::StartUserGesture() {
1930 OnUserGesture();
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::ExecuteEditCommand(const std::string& command,
1943 const std::string& value) {
1944 Send(new InputMsg_ExecuteEditCommand(GetRoutingID(), command, value));
1947 void RenderWidgetHostImpl::ScrollFocusedEditableNodeIntoRect(
1948 const gfx::Rect& rect) {
1949 Send(new InputMsg_ScrollFocusedEditableNodeIntoRect(GetRoutingID(), rect));
1952 void RenderWidgetHostImpl::MoveCaret(const gfx::Point& point) {
1953 Send(new InputMsg_MoveCaret(GetRoutingID(), point));
1956 bool RenderWidgetHostImpl::GotResponseToLockMouseRequest(bool allowed) {
1957 if (!allowed) {
1958 RejectMouseLockOrUnlockIfNecessary();
1959 return false;
1960 } else {
1961 if (!pending_mouse_lock_request_) {
1962 // This is possible, e.g., the plugin sends us an unlock request before
1963 // the user allows to lock to mouse.
1964 return false;
1967 pending_mouse_lock_request_ = false;
1968 if (!view_ || !view_->HasFocus()|| !view_->LockMouse()) {
1969 Send(new ViewMsg_LockMouse_ACK(routing_id_, false));
1970 return false;
1971 } else {
1972 Send(new ViewMsg_LockMouse_ACK(routing_id_, true));
1973 return true;
1978 // static
1979 void RenderWidgetHostImpl::AcknowledgeBufferPresent(
1980 int32 route_id, int gpu_host_id,
1981 const AcceleratedSurfaceMsg_BufferPresented_Params& params) {
1982 GpuProcessHostUIShim* ui_shim = GpuProcessHostUIShim::FromID(gpu_host_id);
1983 if (ui_shim) {
1984 ui_shim->Send(new AcceleratedSurfaceMsg_BufferPresented(route_id,
1985 params));
1989 // static
1990 void RenderWidgetHostImpl::SendSwapCompositorFrameAck(
1991 int32 route_id,
1992 uint32 output_surface_id,
1993 int renderer_host_id,
1994 const cc::CompositorFrameAck& ack) {
1995 RenderProcessHost* host = RenderProcessHost::FromID(renderer_host_id);
1996 if (!host)
1997 return;
1998 host->Send(new ViewMsg_SwapCompositorFrameAck(
1999 route_id, output_surface_id, ack));
2002 // static
2003 void RenderWidgetHostImpl::SendReclaimCompositorResources(
2004 int32 route_id,
2005 uint32 output_surface_id,
2006 int renderer_host_id,
2007 const cc::CompositorFrameAck& ack) {
2008 RenderProcessHost* host = RenderProcessHost::FromID(renderer_host_id);
2009 if (!host)
2010 return;
2011 host->Send(
2012 new ViewMsg_ReclaimCompositorResources(route_id, output_surface_id, ack));
2015 void RenderWidgetHostImpl::DelayedAutoResized() {
2016 gfx::Size new_size = new_auto_size_;
2017 // Clear the new_auto_size_ since the empty value is used as a flag to
2018 // indicate that no callback is in progress (i.e. without this line
2019 // DelayedAutoResized will not get called again).
2020 new_auto_size_.SetSize(0, 0);
2021 if (!should_auto_resize_)
2022 return;
2024 OnRenderAutoResized(new_size);
2027 void RenderWidgetHostImpl::DetachDelegate() {
2028 delegate_ = NULL;
2031 void RenderWidgetHostImpl::ComputeTouchLatency(
2032 const ui::LatencyInfo& latency_info) {
2033 ui::LatencyInfo::LatencyComponent ui_component;
2034 ui::LatencyInfo::LatencyComponent rwh_component;
2035 ui::LatencyInfo::LatencyComponent acked_component;
2037 if (!latency_info.FindLatency(ui::INPUT_EVENT_LATENCY_UI_COMPONENT,
2039 &ui_component) ||
2040 !latency_info.FindLatency(ui::INPUT_EVENT_LATENCY_BEGIN_RWH_COMPONENT,
2041 GetLatencyComponentId(),
2042 &rwh_component))
2043 return;
2045 DCHECK(ui_component.event_count == 1);
2046 DCHECK(rwh_component.event_count == 1);
2048 base::TimeDelta ui_delta =
2049 rwh_component.event_time - ui_component.event_time;
2050 UMA_HISTOGRAM_CUSTOM_COUNTS(
2051 "Event.Latency.Browser.TouchUI",
2052 ui_delta.InMicroseconds(),
2054 20000,
2055 100);
2057 if (latency_info.FindLatency(ui::INPUT_EVENT_LATENCY_ACKED_TOUCH_COMPONENT,
2059 &acked_component)) {
2060 DCHECK(acked_component.event_count == 1);
2061 base::TimeDelta acked_delta =
2062 acked_component.event_time - rwh_component.event_time;
2063 UMA_HISTOGRAM_CUSTOM_COUNTS(
2064 "Event.Latency.Browser.TouchAcked",
2065 acked_delta.InMicroseconds(),
2067 1000000,
2068 100);
2072 void RenderWidgetHostImpl::FrameSwapped(const ui::LatencyInfo& latency_info) {
2073 ui::LatencyInfo::LatencyComponent window_snapshot_component;
2074 if (latency_info.FindLatency(ui::WINDOW_OLD_SNAPSHOT_FRAME_NUMBER_COMPONENT,
2075 GetLatencyComponentId(),
2076 &window_snapshot_component)) {
2077 WindowOldSnapshotReachedScreen(
2078 static_cast<int>(window_snapshot_component.sequence_number));
2080 if (latency_info.FindLatency(ui::WINDOW_SNAPSHOT_FRAME_NUMBER_COMPONENT,
2081 GetLatencyComponentId(),
2082 &window_snapshot_component)) {
2083 int sequence_number = static_cast<int>(
2084 window_snapshot_component.sequence_number);
2085 #if defined(OS_MACOSX)
2086 // On Mac, when using CoreAnmation, there is a delay between when content
2087 // is drawn to the screen, and when the snapshot will actually pick up
2088 // that content. Insert a manual delay of 1/6th of a second (to simulate
2089 // 10 frames at 60 fps) before actually taking the snapshot.
2090 base::MessageLoop::current()->PostDelayedTask(
2091 FROM_HERE,
2092 base::Bind(&RenderWidgetHostImpl::WindowSnapshotReachedScreen,
2093 weak_factory_.GetWeakPtr(),
2094 sequence_number),
2095 base::TimeDelta::FromSecondsD(1. / 6));
2096 #else
2097 WindowSnapshotReachedScreen(sequence_number);
2098 #endif
2101 ui::LatencyInfo::LatencyComponent swap_component;
2102 if (!latency_info.FindLatency(
2103 ui::INPUT_EVENT_LATENCY_TERMINATED_FRAME_SWAP_COMPONENT,
2105 &swap_component)) {
2106 return;
2108 ui::LatencyInfo::LatencyComponent tab_switch_component;
2109 if (latency_info.FindLatency(ui::TAB_SHOW_COMPONENT,
2110 GetLatencyComponentId(),
2111 &tab_switch_component)) {
2112 base::TimeDelta delta =
2113 swap_component.event_time - tab_switch_component.event_time;
2114 for (size_t i = 0; i < tab_switch_component.event_count; i++) {
2115 UMA_HISTOGRAM_TIMES("MPArch.RWH_TabSwitchPaintDuration", delta);
2119 ui::LatencyInfo::LatencyComponent rwh_component;
2120 if (!latency_info.FindLatency(ui::INPUT_EVENT_LATENCY_BEGIN_RWH_COMPONENT,
2121 GetLatencyComponentId(),
2122 &rwh_component)) {
2123 return;
2126 ui::LatencyInfo::LatencyComponent original_component;
2127 if (latency_info.FindLatency(
2128 ui::INPUT_EVENT_LATENCY_SCROLL_UPDATE_ORIGINAL_COMPONENT,
2129 GetLatencyComponentId(),
2130 &original_component)) {
2131 // This UMA metric tracks the time from when the original touch event is
2132 // created (averaged if there are multiple) to when the scroll gesture
2133 // results in final frame swap.
2134 base::TimeDelta delta =
2135 swap_component.event_time - original_component.event_time;
2136 for (size_t i = 0; i < original_component.event_count; i++) {
2137 UMA_HISTOGRAM_CUSTOM_COUNTS(
2138 "Event.Latency.TouchToScrollUpdateSwap",
2139 delta.InMicroseconds(),
2141 1000000,
2142 100);
2147 void RenderWidgetHostImpl::DidReceiveRendererFrame() {
2148 view_->DidReceiveRendererFrame();
2151 void RenderWidgetHostImpl::WindowSnapshotAsyncCallback(
2152 int routing_id,
2153 int snapshot_id,
2154 gfx::Size snapshot_size,
2155 scoped_refptr<base::RefCountedBytes> png_data) {
2156 if (!png_data.get()) {
2157 std::vector<unsigned char> png_vector;
2158 Send(new ViewMsg_WindowSnapshotCompleted(
2159 routing_id, snapshot_id, gfx::Size(), png_vector));
2160 return;
2163 Send(new ViewMsg_WindowSnapshotCompleted(
2164 routing_id, snapshot_id, snapshot_size, png_data->data()));
2167 void RenderWidgetHostImpl::WindowOldSnapshotReachedScreen(int snapshot_id) {
2168 DCHECK(base::MessageLoopForUI::IsCurrent());
2170 std::vector<unsigned char> png;
2172 // This feature is behind the kEnableGpuBenchmarking command line switch
2173 // because it poses security concerns and should only be used for testing.
2174 const base::CommandLine& command_line =
2175 *base::CommandLine::ForCurrentProcess();
2176 if (!command_line.HasSwitch(cc::switches::kEnableGpuBenchmarking)) {
2177 Send(new ViewMsg_WindowSnapshotCompleted(
2178 GetRoutingID(), snapshot_id, gfx::Size(), png));
2179 return;
2182 gfx::Rect view_bounds = GetView()->GetViewBounds();
2183 gfx::Rect snapshot_bounds(view_bounds.size());
2184 gfx::Size snapshot_size = snapshot_bounds.size();
2186 if (ui::GrabViewSnapshot(
2187 GetView()->GetNativeView(), &png, snapshot_bounds)) {
2188 Send(new ViewMsg_WindowSnapshotCompleted(
2189 GetRoutingID(), snapshot_id, snapshot_size, png));
2190 return;
2193 ui::GrabViewSnapshotAsync(
2194 GetView()->GetNativeView(),
2195 snapshot_bounds,
2196 base::ThreadTaskRunnerHandle::Get(),
2197 base::Bind(&RenderWidgetHostImpl::WindowSnapshotAsyncCallback,
2198 weak_factory_.GetWeakPtr(),
2199 GetRoutingID(),
2200 snapshot_id,
2201 snapshot_size));
2204 void RenderWidgetHostImpl::WindowSnapshotReachedScreen(int snapshot_id) {
2205 DCHECK(base::MessageLoopForUI::IsCurrent());
2207 gfx::Rect view_bounds = GetView()->GetViewBounds();
2208 gfx::Rect snapshot_bounds(view_bounds.size());
2210 std::vector<unsigned char> png;
2211 if (ui::GrabViewSnapshot(
2212 GetView()->GetNativeView(), &png, snapshot_bounds)) {
2213 OnSnapshotDataReceived(snapshot_id, &png.front(), png.size());
2214 return;
2217 ui::GrabViewSnapshotAsync(
2218 GetView()->GetNativeView(),
2219 snapshot_bounds,
2220 base::ThreadTaskRunnerHandle::Get(),
2221 base::Bind(&RenderWidgetHostImpl::OnSnapshotDataReceivedAsync,
2222 weak_factory_.GetWeakPtr(),
2223 snapshot_id));
2226 void RenderWidgetHostImpl::OnSnapshotDataReceived(int snapshot_id,
2227 const unsigned char* data,
2228 size_t size) {
2229 // Any pending snapshots with a lower ID than the one received are considered
2230 // to be implicitly complete, and returned the same snapshot data.
2231 PendingSnapshotMap::iterator it = pending_browser_snapshots_.begin();
2232 while(it != pending_browser_snapshots_.end()) {
2233 if (it->first <= snapshot_id) {
2234 it->second.Run(data, size);
2235 pending_browser_snapshots_.erase(it++);
2236 } else {
2237 ++it;
2242 void RenderWidgetHostImpl::OnSnapshotDataReceivedAsync(
2243 int snapshot_id,
2244 scoped_refptr<base::RefCountedBytes> png_data) {
2245 if (png_data.get())
2246 OnSnapshotDataReceived(snapshot_id, png_data->front(), png_data->size());
2247 else
2248 OnSnapshotDataReceived(snapshot_id, NULL, 0);
2251 // static
2252 void RenderWidgetHostImpl::CompositorFrameDrawn(
2253 const std::vector<ui::LatencyInfo>& latency_info) {
2254 for (size_t i = 0; i < latency_info.size(); i++) {
2255 std::set<RenderWidgetHostImpl*> rwhi_set;
2256 for (ui::LatencyInfo::LatencyMap::const_iterator b =
2257 latency_info[i].latency_components.begin();
2258 b != latency_info[i].latency_components.end();
2259 ++b) {
2260 if (b->first.first == ui::INPUT_EVENT_LATENCY_BEGIN_RWH_COMPONENT ||
2261 b->first.first == ui::WINDOW_SNAPSHOT_FRAME_NUMBER_COMPONENT ||
2262 b->first.first == ui::WINDOW_OLD_SNAPSHOT_FRAME_NUMBER_COMPONENT ||
2263 b->first.first == ui::TAB_SHOW_COMPONENT) {
2264 // Matches with GetLatencyComponentId
2265 int routing_id = b->first.second & 0xffffffff;
2266 int process_id = (b->first.second >> 32) & 0xffffffff;
2267 RenderWidgetHost* rwh =
2268 RenderWidgetHost::FromID(process_id, routing_id);
2269 if (!rwh) {
2270 continue;
2272 RenderWidgetHostImpl* rwhi = RenderWidgetHostImpl::From(rwh);
2273 if (rwhi_set.insert(rwhi).second)
2274 rwhi->FrameSwapped(latency_info[i]);
2280 void RenderWidgetHostImpl::AddLatencyInfoComponentIds(
2281 ui::LatencyInfo* latency_info) {
2282 ui::LatencyInfo::LatencyMap new_components;
2283 ui::LatencyInfo::LatencyMap::iterator lc =
2284 latency_info->latency_components.begin();
2285 while (lc != latency_info->latency_components.end()) {
2286 ui::LatencyComponentType component_type = lc->first.first;
2287 if (component_type == ui::WINDOW_SNAPSHOT_FRAME_NUMBER_COMPONENT ||
2288 component_type == ui::WINDOW_OLD_SNAPSHOT_FRAME_NUMBER_COMPONENT) {
2289 // Generate a new component entry with the correct component ID
2290 ui::LatencyInfo::LatencyMap::key_type key =
2291 std::make_pair(component_type, GetLatencyComponentId());
2292 new_components[key] = lc->second;
2294 // Remove the old entry
2295 latency_info->latency_components.erase(lc++);
2296 } else {
2297 ++lc;
2301 // Add newly generated components into the latency info
2302 for (lc = new_components.begin(); lc != new_components.end(); ++lc) {
2303 latency_info->latency_components[lc->first] = lc->second;
2307 BrowserAccessibilityManager*
2308 RenderWidgetHostImpl::GetRootBrowserAccessibilityManager() {
2309 return delegate_ ? delegate_->GetRootBrowserAccessibilityManager() : NULL;
2312 BrowserAccessibilityManager*
2313 RenderWidgetHostImpl::GetOrCreateRootBrowserAccessibilityManager() {
2314 return delegate_ ?
2315 delegate_->GetOrCreateRootBrowserAccessibilityManager() : NULL;
2318 #if defined(OS_WIN)
2319 gfx::NativeViewAccessible
2320 RenderWidgetHostImpl::GetParentNativeViewAccessible() {
2321 return delegate_ ? delegate_->GetParentNativeViewAccessible() : NULL;
2323 #endif
2325 SkColorType RenderWidgetHostImpl::PreferredReadbackFormat() {
2326 if (view_)
2327 return view_->PreferredReadbackFormat();
2328 return kN32_SkColorType;
2331 } // namespace content