Simplify ChildProcessLauncher
[chromium-blink-merge.git] / content / browser / renderer_host / render_widget_host_impl.cc
blob4aef7b88dc79b682aec8f90e772414d16e13c585
1 // Copyright (c) 2012 The Chromium Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
5 #include "content/browser/renderer_host/render_widget_host_impl.h"
7 #include <math.h>
8 #include <set>
9 #include <utility>
11 #include "base/auto_reset.h"
12 #include "base/bind.h"
13 #include "base/command_line.h"
14 #include "base/containers/hash_tables.h"
15 #include "base/i18n/rtl.h"
16 #include "base/lazy_instance.h"
17 #include "base/message_loop/message_loop.h"
18 #include "base/metrics/field_trial.h"
19 #include "base/metrics/histogram.h"
20 #include "base/strings/string_number_conversions.h"
21 #include "base/strings/utf_string_conversions.h"
22 #include "base/thread_task_runner_handle.h"
23 #include "base/trace_event/trace_event.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/bad_message.h"
30 #include "content/browser/browser_plugin/browser_plugin_guest.h"
31 #include "content/browser/gpu/compositor_util.h"
32 #include "content/browser/gpu/gpu_process_host.h"
33 #include "content/browser/gpu/gpu_process_host_ui_shim.h"
34 #include "content/browser/gpu/gpu_surface_tracker.h"
35 #include "content/browser/renderer_host/dip_util.h"
36 #include "content/browser/renderer_host/frame_metadata_util.h"
37 #include "content/browser/renderer_host/input/input_router_config_helper.h"
38 #include "content/browser/renderer_host/input/input_router_impl.h"
39 #include "content/browser/renderer_host/input/synthetic_gesture.h"
40 #include "content/browser/renderer_host/input/synthetic_gesture_controller.h"
41 #include "content/browser/renderer_host/input/synthetic_gesture_target.h"
42 #include "content/browser/renderer_host/input/timeout_monitor.h"
43 #include "content/browser/renderer_host/input/touch_emulator.h"
44 #include "content/browser/renderer_host/render_process_host_impl.h"
45 #include "content/browser/renderer_host/render_view_host_impl.h"
46 #include "content/browser/renderer_host/render_widget_helper.h"
47 #include "content/browser/renderer_host/render_widget_host_delegate.h"
48 #include "content/browser/renderer_host/render_widget_host_view_base.h"
49 #include "content/browser/renderer_host/render_widget_resize_helper.h"
50 #include "content/common/content_constants_internal.h"
51 #include "content/common/cursors/webcursor.h"
52 #include "content/common/frame_messages.h"
53 #include "content/common/gpu/gpu_messages.h"
54 #include "content/common/host_shared_bitmap_manager.h"
55 #include "content/common/input_messages.h"
56 #include "content/common/view_messages.h"
57 #include "content/public/browser/native_web_keyboard_event.h"
58 #include "content/public/browser/notification_service.h"
59 #include "content/public/browser/notification_types.h"
60 #include "content/public/browser/render_widget_host_iterator.h"
61 #include "content/public/common/content_constants.h"
62 #include "content/public/common/content_switches.h"
63 #include "content/public/common/result_codes.h"
64 #include "content/public/common/web_preferences.h"
65 #include "gpu/GLES2/gl2extchromium.h"
66 #include "gpu/command_buffer/service/gpu_switches.h"
67 #include "skia/ext/image_operations.h"
68 #include "skia/ext/platform_canvas.h"
69 #include "third_party/WebKit/public/web/WebCompositionUnderline.h"
70 #include "ui/events/event.h"
71 #include "ui/events/keycodes/keyboard_codes.h"
72 #include "ui/gfx/geometry/size_conversions.h"
73 #include "ui/gfx/geometry/vector2d_conversions.h"
74 #include "ui/gfx/skbitmap_operations.h"
75 #include "ui/snapshot/snapshot.h"
77 #if defined(OS_WIN)
78 #include "content/common/plugin_constants_win.h"
79 #endif
81 using base::Time;
82 using base::TimeDelta;
83 using base::TimeTicks;
84 using blink::WebGestureEvent;
85 using blink::WebInputEvent;
86 using blink::WebKeyboardEvent;
87 using blink::WebMouseEvent;
88 using blink::WebMouseWheelEvent;
89 using blink::WebTextDirection;
91 namespace content {
92 namespace {
94 bool g_check_for_pending_resize_ack = true;
96 typedef std::pair<int32, int32> RenderWidgetHostID;
97 typedef base::hash_map<RenderWidgetHostID, RenderWidgetHostImpl*>
98 RoutingIDWidgetMap;
99 base::LazyInstance<RoutingIDWidgetMap> g_routing_id_widget_map =
100 LAZY_INSTANCE_INITIALIZER;
102 int GetInputRouterViewFlagsFromCompositorFrameMetadata(
103 const cc::CompositorFrameMetadata metadata) {
104 int view_flags = InputRouter::VIEW_FLAGS_NONE;
106 if (metadata.min_page_scale_factor == metadata.max_page_scale_factor)
107 view_flags |= InputRouter::FIXED_PAGE_SCALE;
109 const float window_width_dip = std::ceil(
110 metadata.page_scale_factor * metadata.scrollable_viewport_size.width());
111 const float content_width_css = metadata.root_layer_size.width();
112 if (content_width_css <= window_width_dip)
113 view_flags |= InputRouter::MOBILE_VIEWPORT;
115 return view_flags;
118 // Implements the RenderWidgetHostIterator interface. It keeps a list of
119 // RenderWidgetHosts, and makes sure it returns a live RenderWidgetHost at each
120 // iteration (or NULL if there isn't any left).
121 class RenderWidgetHostIteratorImpl : public RenderWidgetHostIterator {
122 public:
123 RenderWidgetHostIteratorImpl()
124 : current_index_(0) {
127 ~RenderWidgetHostIteratorImpl() override {}
129 void Add(RenderWidgetHost* host) {
130 hosts_.push_back(RenderWidgetHostID(host->GetProcess()->GetID(),
131 host->GetRoutingID()));
134 // RenderWidgetHostIterator:
135 RenderWidgetHost* GetNextHost() override {
136 RenderWidgetHost* host = NULL;
137 while (current_index_ < hosts_.size() && !host) {
138 RenderWidgetHostID id = hosts_[current_index_];
139 host = RenderWidgetHost::FromID(id.first, id.second);
140 ++current_index_;
142 return host;
145 private:
146 std::vector<RenderWidgetHostID> hosts_;
147 size_t current_index_;
149 DISALLOW_COPY_AND_ASSIGN(RenderWidgetHostIteratorImpl);
152 } // namespace
154 ///////////////////////////////////////////////////////////////////////////////
155 // RenderWidgetHostImpl
157 RenderWidgetHostImpl::RenderWidgetHostImpl(RenderWidgetHostDelegate* delegate,
158 RenderProcessHost* process,
159 int routing_id,
160 bool hidden)
161 : view_(NULL),
162 renderer_initialized_(false),
163 hung_renderer_delay_(
164 base::TimeDelta::FromMilliseconds(kHungRendererDelayMs)),
165 delegate_(delegate),
166 process_(process),
167 routing_id_(routing_id),
168 surface_id_(0),
169 is_loading_(false),
170 is_hidden_(hidden),
171 repaint_ack_pending_(false),
172 resize_ack_pending_(false),
173 screen_info_out_of_date_(false),
174 auto_resize_enabled_(false),
175 waiting_for_screen_rects_ack_(false),
176 needs_repainting_on_restore_(false),
177 is_unresponsive_(false),
178 in_flight_event_count_(0),
179 in_get_backing_store_(false),
180 ignore_input_events_(false),
181 input_method_active_(false),
182 text_direction_updated_(false),
183 text_direction_(blink::WebTextDirectionLeftToRight),
184 text_direction_canceled_(false),
185 suppress_next_char_events_(false),
186 pending_mouse_lock_request_(false),
187 allow_privileged_mouse_lock_(false),
188 has_touch_handler_(false),
189 next_browser_snapshot_id_(1),
190 owned_by_render_frame_host_(false),
191 is_focused_(false),
192 weak_factory_(this) {
193 CHECK(delegate_);
194 if (routing_id_ == MSG_ROUTING_NONE) {
195 routing_id_ = process_->GetNextRoutingID();
196 surface_id_ = GpuSurfaceTracker::Get()->AddSurfaceForRenderer(
197 process_->GetID(),
198 routing_id_);
199 } else {
200 // TODO(piman): This is a O(N) lookup, where we could forward the
201 // information from the RenderWidgetHelper. The problem is that doing so
202 // currently leaks outside of content all the way to chrome classes, and
203 // would be a layering violation. Since we don't expect more than a few
204 // hundreds of RWH, this seems acceptable. Revisit if performance become a
205 // problem, for example by tracking in the RenderWidgetHelper the routing id
206 // (and surface id) that have been created, but whose RWH haven't yet.
207 surface_id_ = GpuSurfaceTracker::Get()->LookupSurfaceForRenderer(
208 process_->GetID(),
209 routing_id_);
210 DCHECK(surface_id_);
213 std::pair<RoutingIDWidgetMap::iterator, bool> result =
214 g_routing_id_widget_map.Get().insert(std::make_pair(
215 RenderWidgetHostID(process->GetID(), routing_id_), this));
216 CHECK(result.second) << "Inserting a duplicate item!";
217 process_->AddRoute(routing_id_, this);
219 // If we're initially visible, tell the process host that we're alive.
220 // Otherwise we'll notify the process host when we are first shown.
221 if (!hidden)
222 process_->WidgetRestored();
224 latency_tracker_.Initialize(routing_id_, GetProcess()->GetID());
226 input_router_.reset(new InputRouterImpl(
227 process_, this, this, routing_id_, GetInputRouterConfigForPlatform()));
229 touch_emulator_.reset();
231 RenderViewHostImpl* rvh = static_cast<RenderViewHostImpl*>(
232 IsRenderView() ? RenderViewHost::From(this) : NULL);
233 if (BrowserPluginGuest::IsGuest(rvh) ||
234 !base::CommandLine::ForCurrentProcess()->HasSwitch(
235 switches::kDisableHangMonitor)) {
236 hang_monitor_timeout_.reset(new TimeoutMonitor(
237 base::Bind(&RenderWidgetHostImpl::RendererIsUnresponsive,
238 weak_factory_.GetWeakPtr())));
242 RenderWidgetHostImpl::~RenderWidgetHostImpl() {
243 if (view_weak_)
244 view_weak_->RenderWidgetHostGone();
245 SetView(NULL);
247 GpuSurfaceTracker::Get()->RemoveSurface(surface_id_);
248 surface_id_ = 0;
250 process_->RemoveRoute(routing_id_);
251 g_routing_id_widget_map.Get().erase(
252 RenderWidgetHostID(process_->GetID(), routing_id_));
254 if (delegate_)
255 delegate_->RenderWidgetDeleted(this);
258 // static
259 RenderWidgetHost* RenderWidgetHost::FromID(
260 int32 process_id,
261 int32 routing_id) {
262 return RenderWidgetHostImpl::FromID(process_id, routing_id);
265 // static
266 RenderWidgetHostImpl* RenderWidgetHostImpl::FromID(
267 int32 process_id,
268 int32 routing_id) {
269 DCHECK_CURRENTLY_ON(BrowserThread::UI);
270 RoutingIDWidgetMap* widgets = g_routing_id_widget_map.Pointer();
271 RoutingIDWidgetMap::iterator it = widgets->find(
272 RenderWidgetHostID(process_id, routing_id));
273 return it == widgets->end() ? NULL : it->second;
276 // static
277 scoped_ptr<RenderWidgetHostIterator> RenderWidgetHost::GetRenderWidgetHosts() {
278 RenderWidgetHostIteratorImpl* hosts = new RenderWidgetHostIteratorImpl();
279 RoutingIDWidgetMap* widgets = g_routing_id_widget_map.Pointer();
280 for (RoutingIDWidgetMap::const_iterator it = widgets->begin();
281 it != widgets->end();
282 ++it) {
283 RenderWidgetHost* widget = it->second;
285 if (!widget->IsRenderView()) {
286 hosts->Add(widget);
287 continue;
290 // Add only active RenderViewHosts.
291 RenderViewHost* rvh = RenderViewHost::From(widget);
292 if (static_cast<RenderViewHostImpl*>(rvh)->is_active())
293 hosts->Add(widget);
296 return scoped_ptr<RenderWidgetHostIterator>(hosts);
299 // static
300 scoped_ptr<RenderWidgetHostIterator>
301 RenderWidgetHostImpl::GetAllRenderWidgetHosts() {
302 RenderWidgetHostIteratorImpl* hosts = new RenderWidgetHostIteratorImpl();
303 RoutingIDWidgetMap* widgets = g_routing_id_widget_map.Pointer();
304 for (RoutingIDWidgetMap::const_iterator it = widgets->begin();
305 it != widgets->end();
306 ++it) {
307 hosts->Add(it->second);
310 return scoped_ptr<RenderWidgetHostIterator>(hosts);
313 // static
314 RenderWidgetHostImpl* RenderWidgetHostImpl::From(RenderWidgetHost* rwh) {
315 return rwh->AsRenderWidgetHostImpl();
318 void RenderWidgetHostImpl::SetView(RenderWidgetHostViewBase* view) {
319 if (view)
320 view_weak_ = view->GetWeakPtr();
321 else
322 view_weak_.reset();
323 view_ = view;
325 GpuSurfaceTracker::Get()->SetSurfaceHandle(
326 surface_id_, GetCompositingSurface());
328 synthetic_gesture_controller_.reset();
331 RenderProcessHost* RenderWidgetHostImpl::GetProcess() const {
332 return process_;
335 int RenderWidgetHostImpl::GetRoutingID() const {
336 return routing_id_;
339 RenderWidgetHostView* RenderWidgetHostImpl::GetView() const {
340 return view_;
343 RenderWidgetHostImpl* RenderWidgetHostImpl::AsRenderWidgetHostImpl() {
344 return this;
347 gfx::NativeViewId RenderWidgetHostImpl::GetNativeViewId() const {
348 if (view_)
349 return view_->GetNativeViewId();
350 return 0;
353 gfx::GLSurfaceHandle RenderWidgetHostImpl::GetCompositingSurface() {
354 if (view_)
355 return view_->GetCompositingSurface();
356 return gfx::GLSurfaceHandle();
359 void RenderWidgetHostImpl::ResetSizeAndRepaintPendingFlags() {
360 resize_ack_pending_ = false;
361 if (repaint_ack_pending_) {
362 TRACE_EVENT_ASYNC_END0(
363 "renderer_host", "RenderWidgetHostImpl::repaint_ack_pending_", this);
365 repaint_ack_pending_ = false;
366 if (old_resize_params_)
367 old_resize_params_->new_size = gfx::Size();
370 void RenderWidgetHostImpl::SendScreenRects() {
371 if (!renderer_initialized_ || waiting_for_screen_rects_ack_)
372 return;
374 if (is_hidden_) {
375 // On GTK, this comes in for backgrounded tabs. Ignore, to match what
376 // happens on Win & Mac, and when the view is shown it'll call this again.
377 return;
380 if (!view_)
381 return;
383 last_view_screen_rect_ = view_->GetViewBounds();
384 last_window_screen_rect_ = view_->GetBoundsInRootWindow();
385 Send(new ViewMsg_UpdateScreenRects(
386 GetRoutingID(), last_view_screen_rect_, last_window_screen_rect_));
387 if (delegate_)
388 delegate_->DidSendScreenRects(this);
389 waiting_for_screen_rects_ack_ = true;
392 void RenderWidgetHostImpl::SuppressNextCharEvents() {
393 suppress_next_char_events_ = true;
396 void RenderWidgetHostImpl::FlushInput() {
397 input_router_->RequestNotificationWhenFlushed();
398 if (synthetic_gesture_controller_)
399 synthetic_gesture_controller_->Flush(base::TimeTicks::Now());
402 void RenderWidgetHostImpl::SetNeedsFlush() {
403 if (view_)
404 view_->OnSetNeedsFlushInput();
407 void RenderWidgetHostImpl::Init() {
408 DCHECK(process_->HasConnection());
410 renderer_initialized_ = true;
412 GpuSurfaceTracker::Get()->SetSurfaceHandle(
413 surface_id_, GetCompositingSurface());
415 // Send the ack along with the information on placement.
416 Send(new ViewMsg_CreatingNew_ACK(routing_id_));
417 GetProcess()->ResumeRequestsForView(routing_id_);
419 WasResized();
422 void RenderWidgetHostImpl::InitForFrame() {
423 DCHECK(process_->HasConnection());
424 renderer_initialized_ = true;
427 void RenderWidgetHostImpl::Shutdown() {
428 RejectMouseLockOrUnlockIfNecessary();
430 if (process_->HasConnection()) {
431 // Tell the renderer object to close.
432 bool rv = Send(new ViewMsg_Close(routing_id_));
433 DCHECK(rv);
436 Destroy();
439 bool RenderWidgetHostImpl::IsLoading() const {
440 return is_loading_;
443 bool RenderWidgetHostImpl::IsRenderView() const {
444 return false;
447 bool RenderWidgetHostImpl::OnMessageReceived(const IPC::Message &msg) {
448 bool handled = true;
449 IPC_BEGIN_MESSAGE_MAP(RenderWidgetHostImpl, msg)
450 IPC_MESSAGE_HANDLER(FrameHostMsg_RenderProcessGone, OnRenderProcessGone)
451 IPC_MESSAGE_HANDLER(InputHostMsg_QueueSyntheticGesture,
452 OnQueueSyntheticGesture)
453 IPC_MESSAGE_HANDLER(InputHostMsg_ImeCancelComposition,
454 OnImeCancelComposition)
455 IPC_MESSAGE_HANDLER(ViewHostMsg_RenderViewReady, OnRenderViewReady)
456 IPC_MESSAGE_HANDLER(ViewHostMsg_Close, OnClose)
457 IPC_MESSAGE_HANDLER(ViewHostMsg_UpdateScreenRects_ACK,
458 OnUpdateScreenRectsAck)
459 IPC_MESSAGE_HANDLER(ViewHostMsg_RequestMove, OnRequestMove)
460 IPC_MESSAGE_HANDLER(ViewHostMsg_SetTooltipText, OnSetTooltipText)
461 IPC_MESSAGE_HANDLER_GENERIC(ViewHostMsg_SwapCompositorFrame,
462 OnSwapCompositorFrame(msg))
463 IPC_MESSAGE_HANDLER(ViewHostMsg_UpdateRect, OnUpdateRect)
464 IPC_MESSAGE_HANDLER(ViewHostMsg_Focus, OnFocus)
465 IPC_MESSAGE_HANDLER(ViewHostMsg_Blur, OnBlur)
466 IPC_MESSAGE_HANDLER(ViewHostMsg_SetCursor, OnSetCursor)
467 IPC_MESSAGE_HANDLER(ViewHostMsg_TextInputTypeChanged,
468 OnTextInputTypeChanged)
469 IPC_MESSAGE_HANDLER(ViewHostMsg_LockMouse, OnLockMouse)
470 IPC_MESSAGE_HANDLER(ViewHostMsg_UnlockMouse, OnUnlockMouse)
471 IPC_MESSAGE_HANDLER(ViewHostMsg_ShowDisambiguationPopup,
472 OnShowDisambiguationPopup)
473 IPC_MESSAGE_HANDLER(ViewHostMsg_SelectionChanged, OnSelectionChanged)
474 IPC_MESSAGE_HANDLER(ViewHostMsg_SelectionBoundsChanged,
475 OnSelectionBoundsChanged)
476 #if defined(OS_WIN)
477 IPC_MESSAGE_HANDLER(ViewHostMsg_WindowlessPluginDummyWindowCreated,
478 OnWindowlessPluginDummyWindowCreated)
479 IPC_MESSAGE_HANDLER(ViewHostMsg_WindowlessPluginDummyWindowDestroyed,
480 OnWindowlessPluginDummyWindowDestroyed)
481 #endif
482 IPC_MESSAGE_HANDLER(InputHostMsg_ImeCompositionRangeChanged,
483 OnImeCompositionRangeChanged)
484 IPC_MESSAGE_UNHANDLED(handled = false)
485 IPC_END_MESSAGE_MAP()
487 if (!handled && input_router_ && input_router_->OnMessageReceived(msg))
488 return true;
490 if (!handled && view_ && view_->OnMessageReceived(msg))
491 return true;
493 return handled;
496 bool RenderWidgetHostImpl::Send(IPC::Message* msg) {
497 if (IPC_MESSAGE_ID_CLASS(msg->type()) == InputMsgStart)
498 return input_router_->SendInput(make_scoped_ptr(msg));
500 return process_->Send(msg);
503 void RenderWidgetHostImpl::SetIsLoading(bool is_loading) {
504 is_loading_ = is_loading;
505 if (!view_)
506 return;
507 view_->SetIsLoading(is_loading);
510 void RenderWidgetHostImpl::WasHidden() {
511 if (is_hidden_)
512 return;
514 TRACE_EVENT0("renderer_host", "RenderWidgetHostImpl::WasHidden");
515 is_hidden_ = true;
517 // Don't bother reporting hung state when we aren't active.
518 StopHangMonitorTimeout();
520 // If we have a renderer, then inform it that we are being hidden so it can
521 // reduce its resource utilization.
522 Send(new ViewMsg_WasHidden(routing_id_));
524 // Tell the RenderProcessHost we were hidden.
525 process_->WidgetHidden();
527 bool is_visible = false;
528 NotificationService::current()->Notify(
529 NOTIFICATION_RENDER_WIDGET_VISIBILITY_CHANGED,
530 Source<RenderWidgetHost>(this),
531 Details<bool>(&is_visible));
534 void RenderWidgetHostImpl::WasShown(const ui::LatencyInfo& latency_info) {
535 if (!is_hidden_)
536 return;
538 TRACE_EVENT0("renderer_host", "RenderWidgetHostImpl::WasShown");
539 is_hidden_ = false;
541 SendScreenRects();
543 // When hidden, timeout monitoring for input events is disabled. Restore it
544 // now to ensure consistent hang detection.
545 if (in_flight_event_count_)
546 RestartHangMonitorTimeout();
548 // Always repaint on restore.
549 bool needs_repainting = true;
550 needs_repainting_on_restore_ = false;
551 Send(new ViewMsg_WasShown(routing_id_, needs_repainting, latency_info));
553 process_->WidgetRestored();
555 bool is_visible = true;
556 NotificationService::current()->Notify(
557 NOTIFICATION_RENDER_WIDGET_VISIBILITY_CHANGED,
558 Source<RenderWidgetHost>(this),
559 Details<bool>(&is_visible));
561 // It's possible for our size to be out of sync with the renderer. The
562 // following is one case that leads to this:
563 // 1. WasResized -> Send ViewMsg_Resize to render
564 // 2. WasResized -> do nothing as resize_ack_pending_ is true
565 // 3. WasHidden
566 // 4. OnUpdateRect from (1) processed. Does NOT invoke WasResized as view
567 // is hidden. Now renderer/browser out of sync with what they think size
568 // is.
569 // By invoking WasResized the renderer is updated as necessary. WasResized
570 // does nothing if the sizes are already in sync.
572 // TODO: ideally ViewMsg_WasShown would take a size. This way, the renderer
573 // could handle both the restore and resize at once. This isn't that big a
574 // deal as RenderWidget::WasShown delays updating, so that the resize from
575 // WasResized is usually processed before the renderer is painted.
576 WasResized();
579 bool RenderWidgetHostImpl::GetResizeParams(
580 ViewMsg_Resize_Params* resize_params) {
581 *resize_params = ViewMsg_Resize_Params();
583 if (!screen_info_) {
584 screen_info_.reset(new blink::WebScreenInfo);
585 GetWebScreenInfo(screen_info_.get());
587 resize_params->screen_info = *screen_info_;
588 resize_params->resizer_rect = GetRootWindowResizerRect();
590 if (view_) {
591 resize_params->new_size = view_->GetRequestedRendererSize();
592 resize_params->physical_backing_size = view_->GetPhysicalBackingSize();
593 resize_params->top_controls_height = view_->GetTopControlsHeight();
594 resize_params->top_controls_shrink_blink_size =
595 view_->DoTopControlsShrinkBlinkSize();
596 resize_params->visible_viewport_size = view_->GetVisibleViewportSize();
597 resize_params->is_fullscreen = IsFullscreen();
600 const bool size_changed =
601 !old_resize_params_ ||
602 old_resize_params_->new_size != resize_params->new_size ||
603 (old_resize_params_->physical_backing_size.IsEmpty() &&
604 !resize_params->physical_backing_size.IsEmpty());
605 bool dirty =
606 size_changed || screen_info_out_of_date_ ||
607 old_resize_params_->physical_backing_size !=
608 resize_params->physical_backing_size ||
609 old_resize_params_->is_fullscreen != resize_params->is_fullscreen ||
610 old_resize_params_->top_controls_height !=
611 resize_params->top_controls_height ||
612 old_resize_params_->top_controls_shrink_blink_size !=
613 resize_params->top_controls_shrink_blink_size ||
614 old_resize_params_->visible_viewport_size !=
615 resize_params->visible_viewport_size;
617 // We don't expect to receive an ACK when the requested size or the physical
618 // backing size is empty, or when the main viewport size didn't change.
619 resize_params->needs_resize_ack =
620 g_check_for_pending_resize_ack && !resize_params->new_size.IsEmpty() &&
621 !resize_params->physical_backing_size.IsEmpty() && size_changed;
623 return dirty;
626 void RenderWidgetHostImpl::SetInitialRenderSizeParams(
627 const ViewMsg_Resize_Params& resize_params) {
628 resize_ack_pending_ = resize_params.needs_resize_ack;
630 old_resize_params_ =
631 make_scoped_ptr(new ViewMsg_Resize_Params(resize_params));
634 void RenderWidgetHostImpl::WasResized() {
635 // Skip if the |delegate_| has already been detached because
636 // it's web contents is being deleted.
637 if (resize_ack_pending_ || !process_->HasConnection() || !view_ ||
638 !renderer_initialized_ || auto_resize_enabled_ || !delegate_) {
639 return;
642 scoped_ptr<ViewMsg_Resize_Params> params(new ViewMsg_Resize_Params);
643 if (!GetResizeParams(params.get()))
644 return;
646 bool width_changed =
647 !old_resize_params_ ||
648 old_resize_params_->new_size.width() != params->new_size.width();
649 if (Send(new ViewMsg_Resize(routing_id_, *params))) {
650 resize_ack_pending_ = params->needs_resize_ack;
651 old_resize_params_.swap(params);
654 if (delegate_)
655 delegate_->RenderWidgetWasResized(this, width_changed);
658 void RenderWidgetHostImpl::ResizeRectChanged(const gfx::Rect& new_rect) {
659 Send(new ViewMsg_ChangeResizeRect(routing_id_, new_rect));
662 void RenderWidgetHostImpl::GotFocus() {
663 Focus();
664 if (delegate_)
665 delegate_->RenderWidgetGotFocus(this);
668 void RenderWidgetHostImpl::Focus() {
669 is_focused_ = true;
671 Send(new InputMsg_SetFocus(routing_id_, true));
674 void RenderWidgetHostImpl::Blur() {
675 is_focused_ = false;
677 // If there is a pending mouse lock request, we don't want to reject it at
678 // this point. The user can switch focus back to this view and approve the
679 // request later.
680 if (IsMouseLocked())
681 view_->UnlockMouse();
683 if (touch_emulator_)
684 touch_emulator_->CancelTouch();
686 Send(new InputMsg_SetFocus(routing_id_, false));
689 void RenderWidgetHostImpl::LostCapture() {
690 if (touch_emulator_)
691 touch_emulator_->CancelTouch();
693 Send(new InputMsg_MouseCaptureLost(routing_id_));
696 void RenderWidgetHostImpl::SetActive(bool active) {
697 Send(new ViewMsg_SetActive(routing_id_, active));
700 void RenderWidgetHostImpl::LostMouseLock() {
701 Send(new ViewMsg_MouseLockLost(routing_id_));
704 void RenderWidgetHostImpl::ViewDestroyed() {
705 RejectMouseLockOrUnlockIfNecessary();
707 // TODO(evanm): tracking this may no longer be necessary;
708 // eliminate this function if so.
709 SetView(NULL);
712 void RenderWidgetHostImpl::CopyFromBackingStore(
713 const gfx::Rect& src_subrect,
714 const gfx::Size& accelerated_dst_size,
715 ReadbackRequestCallback& callback,
716 const SkColorType color_type) {
717 if (view_) {
718 TRACE_EVENT0("browser",
719 "RenderWidgetHostImpl::CopyFromBackingStore::FromCompositingSurface");
720 gfx::Rect accelerated_copy_rect = src_subrect.IsEmpty() ?
721 gfx::Rect(view_->GetViewBounds().size()) : src_subrect;
722 view_->CopyFromCompositingSurface(
723 accelerated_copy_rect, accelerated_dst_size, callback, color_type);
724 return;
727 callback.Run(SkBitmap(), content::READBACK_FAILED);
730 bool RenderWidgetHostImpl::CanCopyFromBackingStore() {
731 if (view_)
732 return view_->IsSurfaceAvailableForCopy();
733 return false;
736 #if defined(OS_ANDROID)
737 void RenderWidgetHostImpl::LockBackingStore() {
738 if (view_)
739 view_->LockCompositingSurface();
742 void RenderWidgetHostImpl::UnlockBackingStore() {
743 if (view_)
744 view_->UnlockCompositingSurface();
746 #endif
748 #if defined(OS_MACOSX)
749 void RenderWidgetHostImpl::PauseForPendingResizeOrRepaints() {
750 TRACE_EVENT0("browser",
751 "RenderWidgetHostImpl::PauseForPendingResizeOrRepaints");
753 if (!CanPauseForPendingResizeOrRepaints())
754 return;
756 WaitForSurface();
759 bool RenderWidgetHostImpl::CanPauseForPendingResizeOrRepaints() {
760 // Do not pause if the view is hidden.
761 if (is_hidden())
762 return false;
764 // Do not pause if there is not a paint or resize already coming.
765 if (!repaint_ack_pending_ && !resize_ack_pending_)
766 return false;
768 return true;
771 void RenderWidgetHostImpl::WaitForSurface() {
772 // How long to (synchronously) wait for the renderer to respond with a
773 // new frame when our current frame doesn't exist or is the wrong size.
774 // This timeout impacts the "choppiness" of our window resize.
775 const int kPaintMsgTimeoutMS = 50;
777 if (!view_)
778 return;
780 // The view_size will be current_size_ for auto-sized views and otherwise the
781 // size of the view_. (For auto-sized views, current_size_ is updated during
782 // UpdateRect messages.)
783 gfx::Size view_size = current_size_;
784 if (!auto_resize_enabled_) {
785 // Get the desired size from the current view bounds.
786 gfx::Rect view_rect = view_->GetViewBounds();
787 if (view_rect.IsEmpty())
788 return;
789 view_size = view_rect.size();
792 TRACE_EVENT2("renderer_host",
793 "RenderWidgetHostImpl::WaitForSurface",
794 "width",
795 base::IntToString(view_size.width()),
796 "height",
797 base::IntToString(view_size.height()));
799 // We should not be asked to paint while we are hidden. If we are hidden,
800 // then it means that our consumer failed to call WasShown.
801 DCHECK(!is_hidden_) << "WaitForSurface called while hidden!";
803 // We should never be called recursively; this can theoretically lead to
804 // infinite recursion and almost certainly leads to lower performance.
805 DCHECK(!in_get_backing_store_) << "WaitForSurface called recursively!";
806 base::AutoReset<bool> auto_reset_in_get_backing_store(
807 &in_get_backing_store_, true);
809 // We might have a surface that we can use already.
810 if (view_->HasAcceleratedSurface(view_size))
811 return;
813 // Request that the renderer produce a frame of the right size, if it
814 // hasn't been requested already.
815 if (!repaint_ack_pending_ && !resize_ack_pending_) {
816 repaint_start_time_ = TimeTicks::Now();
817 repaint_ack_pending_ = true;
818 TRACE_EVENT_ASYNC_BEGIN0(
819 "renderer_host", "RenderWidgetHostImpl::repaint_ack_pending_", this);
820 Send(new ViewMsg_Repaint(routing_id_, view_size));
823 // Pump a nested message loop until we time out or get a frame of the right
824 // size.
825 TimeTicks start_time = TimeTicks::Now();
826 TimeDelta time_left = TimeDelta::FromMilliseconds(kPaintMsgTimeoutMS);
827 TimeTicks timeout_time = start_time + time_left;
828 while (1) {
829 TRACE_EVENT0("renderer_host", "WaitForSurface::WaitForSingleTaskToRun");
830 if (RenderWidgetResizeHelper::Get()->WaitForSingleTaskToRun(time_left)) {
831 // For auto-resized views, current_size_ determines the view_size and it
832 // may have changed during the handling of an UpdateRect message.
833 if (auto_resize_enabled_)
834 view_size = current_size_;
835 if (view_->HasAcceleratedSurface(view_size))
836 break;
838 time_left = timeout_time - TimeTicks::Now();
839 if (time_left <= TimeDelta::FromSeconds(0)) {
840 TRACE_EVENT0("renderer_host", "WaitForSurface::Timeout");
841 break;
845 UMA_HISTOGRAM_CUSTOM_TIMES("OSX.RendererHost.SurfaceWaitTime",
846 TimeTicks::Now() - start_time,
847 TimeDelta::FromMilliseconds(1),
848 TimeDelta::FromMilliseconds(200), 50);
850 #endif
852 bool RenderWidgetHostImpl::ScheduleComposite() {
853 if (is_hidden_ || current_size_.IsEmpty() || repaint_ack_pending_ ||
854 resize_ack_pending_) {
855 return false;
858 // Send out a request to the renderer to paint the view if required.
859 repaint_start_time_ = TimeTicks::Now();
860 repaint_ack_pending_ = true;
861 TRACE_EVENT_ASYNC_BEGIN0(
862 "renderer_host", "RenderWidgetHostImpl::repaint_ack_pending_", this);
863 Send(new ViewMsg_Repaint(routing_id_, current_size_));
864 return true;
867 void RenderWidgetHostImpl::StartHangMonitorTimeout(base::TimeDelta delay) {
868 if (hang_monitor_timeout_)
869 hang_monitor_timeout_->Start(delay);
872 void RenderWidgetHostImpl::RestartHangMonitorTimeout() {
873 if (hang_monitor_timeout_)
874 hang_monitor_timeout_->Restart(hung_renderer_delay_);
877 void RenderWidgetHostImpl::StopHangMonitorTimeout() {
878 if (hang_monitor_timeout_)
879 hang_monitor_timeout_->Stop();
880 RendererIsResponsive();
883 void RenderWidgetHostImpl::ForwardMouseEvent(const WebMouseEvent& mouse_event) {
884 ForwardMouseEventWithLatencyInfo(mouse_event, ui::LatencyInfo());
887 void RenderWidgetHostImpl::ForwardMouseEventWithLatencyInfo(
888 const blink::WebMouseEvent& mouse_event,
889 const ui::LatencyInfo& ui_latency) {
890 TRACE_EVENT2("input", "RenderWidgetHostImpl::ForwardMouseEvent",
891 "x", mouse_event.x, "y", mouse_event.y);
893 for (size_t i = 0; i < mouse_event_callbacks_.size(); ++i) {
894 if (mouse_event_callbacks_[i].Run(mouse_event))
895 return;
898 if (IgnoreInputEvents())
899 return;
901 if (touch_emulator_ && touch_emulator_->HandleMouseEvent(mouse_event))
902 return;
904 MouseEventWithLatencyInfo mouse_with_latency(mouse_event, ui_latency);
905 latency_tracker_.OnInputEvent(mouse_event, &mouse_with_latency.latency);
906 input_router_->SendMouseEvent(mouse_with_latency);
908 // Pass mouse state to gpu service if the subscribe uniform
909 // extension is enabled.
910 if (process_->SubscribeUniformEnabled()) {
911 gpu::ValueState state;
912 state.int_value[0] = mouse_event.x;
913 state.int_value[1] = mouse_event.y;
914 // TODO(orglofch) Separate the mapping of pending value states to the
915 // Gpu Service to be per RWH not per process
916 process_->SendUpdateValueState(GL_MOUSE_POSITION_CHROMIUM, state);
920 void RenderWidgetHostImpl::OnPointerEventActivate() {
923 void RenderWidgetHostImpl::ForwardWheelEvent(
924 const WebMouseWheelEvent& wheel_event) {
925 ForwardWheelEventWithLatencyInfo(wheel_event, ui::LatencyInfo());
928 void RenderWidgetHostImpl::ForwardWheelEventWithLatencyInfo(
929 const blink::WebMouseWheelEvent& wheel_event,
930 const ui::LatencyInfo& ui_latency) {
931 TRACE_EVENT0("input", "RenderWidgetHostImpl::ForwardWheelEvent");
933 if (IgnoreInputEvents())
934 return;
936 if (touch_emulator_ && touch_emulator_->HandleMouseWheelEvent(wheel_event))
937 return;
939 MouseWheelEventWithLatencyInfo wheel_with_latency(wheel_event, ui_latency);
940 latency_tracker_.OnInputEvent(wheel_event, &wheel_with_latency.latency);
941 input_router_->SendWheelEvent(wheel_with_latency);
944 void RenderWidgetHostImpl::ForwardGestureEvent(
945 const blink::WebGestureEvent& gesture_event) {
946 ForwardGestureEventWithLatencyInfo(gesture_event, ui::LatencyInfo());
949 void RenderWidgetHostImpl::ForwardGestureEventWithLatencyInfo(
950 const blink::WebGestureEvent& gesture_event,
951 const ui::LatencyInfo& ui_latency) {
952 TRACE_EVENT0("input", "RenderWidgetHostImpl::ForwardGestureEvent");
953 // Early out if necessary, prior to performing latency logic.
954 if (IgnoreInputEvents())
955 return;
957 if (delegate_->PreHandleGestureEvent(gesture_event))
958 return;
960 GestureEventWithLatencyInfo gesture_with_latency(gesture_event, ui_latency);
961 latency_tracker_.OnInputEvent(gesture_event, &gesture_with_latency.latency);
962 input_router_->SendGestureEvent(gesture_with_latency);
965 void RenderWidgetHostImpl::ForwardEmulatedTouchEvent(
966 const blink::WebTouchEvent& touch_event) {
967 TRACE_EVENT0("input", "RenderWidgetHostImpl::ForwardEmulatedTouchEvent");
969 TouchEventWithLatencyInfo touch_with_latency(touch_event);
970 latency_tracker_.OnInputEvent(touch_event, &touch_with_latency.latency);
971 input_router_->SendTouchEvent(touch_with_latency);
974 void RenderWidgetHostImpl::ForwardTouchEventWithLatencyInfo(
975 const blink::WebTouchEvent& touch_event,
976 const ui::LatencyInfo& ui_latency) {
977 TRACE_EVENT0("input", "RenderWidgetHostImpl::ForwardTouchEvent");
979 // Always forward TouchEvents for touch stream consistency. They will be
980 // ignored if appropriate in FilterInputEvent().
982 TouchEventWithLatencyInfo touch_with_latency(touch_event, ui_latency);
983 if (touch_emulator_ &&
984 touch_emulator_->HandleTouchEvent(touch_with_latency.event)) {
985 if (view_) {
986 view_->ProcessAckedTouchEvent(
987 touch_with_latency, INPUT_EVENT_ACK_STATE_CONSUMED);
989 return;
992 latency_tracker_.OnInputEvent(touch_event, &touch_with_latency.latency);
993 input_router_->SendTouchEvent(touch_with_latency);
996 void RenderWidgetHostImpl::ForwardKeyboardEvent(
997 const NativeWebKeyboardEvent& key_event) {
998 TRACE_EVENT0("input", "RenderWidgetHostImpl::ForwardKeyboardEvent");
999 if (IgnoreInputEvents())
1000 return;
1002 if (!process_->HasConnection())
1003 return;
1005 // First, let keypress listeners take a shot at handling the event. If a
1006 // listener handles the event, it should not be propagated to the renderer.
1007 if (KeyPressListenersHandleEvent(key_event)) {
1008 // Some keypresses that are accepted by the listener might have follow up
1009 // char events, which should be ignored.
1010 if (key_event.type == WebKeyboardEvent::RawKeyDown)
1011 suppress_next_char_events_ = true;
1012 return;
1015 if (key_event.type == WebKeyboardEvent::Char &&
1016 (key_event.windowsKeyCode == ui::VKEY_RETURN ||
1017 key_event.windowsKeyCode == ui::VKEY_SPACE)) {
1018 OnUserGesture();
1021 // Double check the type to make sure caller hasn't sent us nonsense that
1022 // will mess up our key queue.
1023 if (!WebInputEvent::isKeyboardEventType(key_event.type))
1024 return;
1026 if (suppress_next_char_events_) {
1027 // If preceding RawKeyDown event was handled by the browser, then we need
1028 // suppress all Char events generated by it. Please note that, one
1029 // RawKeyDown event may generate multiple Char events, so we can't reset
1030 // |suppress_next_char_events_| until we get a KeyUp or a RawKeyDown.
1031 if (key_event.type == WebKeyboardEvent::Char)
1032 return;
1033 // We get a KeyUp or a RawKeyDown event.
1034 suppress_next_char_events_ = false;
1037 bool is_shortcut = false;
1039 // Only pre-handle the key event if it's not handled by the input method.
1040 if (delegate_ && !key_event.skip_in_browser) {
1041 // We need to set |suppress_next_char_events_| to true if
1042 // PreHandleKeyboardEvent() returns true, but |this| may already be
1043 // destroyed at that time. So set |suppress_next_char_events_| true here,
1044 // then revert it afterwards when necessary.
1045 if (key_event.type == WebKeyboardEvent::RawKeyDown)
1046 suppress_next_char_events_ = true;
1048 // Tab switching/closing accelerators aren't sent to the renderer to avoid
1049 // a hung/malicious renderer from interfering.
1050 if (delegate_->PreHandleKeyboardEvent(key_event, &is_shortcut))
1051 return;
1053 if (key_event.type == WebKeyboardEvent::RawKeyDown)
1054 suppress_next_char_events_ = false;
1057 if (touch_emulator_ && touch_emulator_->HandleKeyboardEvent(key_event))
1058 return;
1060 ui::LatencyInfo latency;
1061 latency_tracker_.OnInputEvent(key_event, &latency);
1062 input_router_->SendKeyboardEvent(key_event, latency, is_shortcut);
1065 void RenderWidgetHostImpl::QueueSyntheticGesture(
1066 scoped_ptr<SyntheticGesture> synthetic_gesture,
1067 const base::Callback<void(SyntheticGesture::Result)>& on_complete) {
1068 if (!synthetic_gesture_controller_ && view_) {
1069 synthetic_gesture_controller_.reset(
1070 new SyntheticGestureController(
1071 view_->CreateSyntheticGestureTarget().Pass()));
1073 if (synthetic_gesture_controller_) {
1074 synthetic_gesture_controller_->QueueSyntheticGesture(
1075 synthetic_gesture.Pass(), on_complete);
1079 void RenderWidgetHostImpl::SetCursor(const WebCursor& cursor) {
1080 if (!view_)
1081 return;
1082 view_->UpdateCursor(cursor);
1085 void RenderWidgetHostImpl::ShowContextMenuAtPoint(const gfx::Point& point) {
1086 Send(new ViewMsg_ShowContextMenu(
1087 GetRoutingID(), ui::MENU_SOURCE_MOUSE, point));
1090 void RenderWidgetHostImpl::SendCursorVisibilityState(bool is_visible) {
1091 Send(new InputMsg_CursorVisibilityChange(GetRoutingID(), is_visible));
1094 int64 RenderWidgetHostImpl::GetLatencyComponentId() const {
1095 return latency_tracker_.latency_component_id();
1098 // static
1099 void RenderWidgetHostImpl::DisableResizeAckCheckForTesting() {
1100 g_check_for_pending_resize_ack = false;
1103 void RenderWidgetHostImpl::AddKeyPressEventCallback(
1104 const KeyPressEventCallback& callback) {
1105 key_press_event_callbacks_.push_back(callback);
1108 void RenderWidgetHostImpl::RemoveKeyPressEventCallback(
1109 const KeyPressEventCallback& callback) {
1110 for (size_t i = 0; i < key_press_event_callbacks_.size(); ++i) {
1111 if (key_press_event_callbacks_[i].Equals(callback)) {
1112 key_press_event_callbacks_.erase(
1113 key_press_event_callbacks_.begin() + i);
1114 return;
1119 void RenderWidgetHostImpl::AddMouseEventCallback(
1120 const MouseEventCallback& callback) {
1121 mouse_event_callbacks_.push_back(callback);
1124 void RenderWidgetHostImpl::RemoveMouseEventCallback(
1125 const MouseEventCallback& callback) {
1126 for (size_t i = 0; i < mouse_event_callbacks_.size(); ++i) {
1127 if (mouse_event_callbacks_[i].Equals(callback)) {
1128 mouse_event_callbacks_.erase(mouse_event_callbacks_.begin() + i);
1129 return;
1134 void RenderWidgetHostImpl::GetWebScreenInfo(blink::WebScreenInfo* result) {
1135 TRACE_EVENT0("renderer_host", "RenderWidgetHostImpl::GetWebScreenInfo");
1136 if (view_)
1137 view_->GetScreenInfo(result);
1138 else
1139 RenderWidgetHostViewBase::GetDefaultScreenInfo(result);
1140 latency_tracker_.set_device_scale_factor(result->deviceScaleFactor);
1141 screen_info_out_of_date_ = false;
1144 const NativeWebKeyboardEvent*
1145 RenderWidgetHostImpl::GetLastKeyboardEvent() const {
1146 return input_router_->GetLastKeyboardEvent();
1149 void RenderWidgetHostImpl::NotifyScreenInfoChanged() {
1150 if (delegate_)
1151 delegate_->ScreenInfoChanged();
1153 // The resize message (which may not happen immediately) will carry with it
1154 // the screen info as well as the new size (if the screen has changed scale
1155 // factor).
1156 InvalidateScreenInfo();
1157 WasResized();
1160 void RenderWidgetHostImpl::InvalidateScreenInfo() {
1161 screen_info_out_of_date_ = true;
1162 screen_info_.reset();
1165 void RenderWidgetHostImpl::GetSnapshotFromBrowser(
1166 const base::Callback<void(const unsigned char*,size_t)> callback) {
1167 int id = next_browser_snapshot_id_++;
1168 pending_browser_snapshots_.insert(std::make_pair(id, callback));
1169 Send(new ViewMsg_ForceRedraw(GetRoutingID(), id));
1172 void RenderWidgetHostImpl::OnSelectionChanged(const base::string16& text,
1173 size_t offset,
1174 const gfx::Range& range) {
1175 if (view_)
1176 view_->SelectionChanged(text, offset, range);
1179 void RenderWidgetHostImpl::OnSelectionBoundsChanged(
1180 const ViewHostMsg_SelectionBounds_Params& params) {
1181 if (view_) {
1182 view_->SelectionBoundsChanged(params);
1186 void RenderWidgetHostImpl::UpdateVSyncParameters(base::TimeTicks timebase,
1187 base::TimeDelta interval) {
1188 Send(new ViewMsg_UpdateVSyncParameters(GetRoutingID(), timebase, interval));
1191 void RenderWidgetHostImpl::RendererExited(base::TerminationStatus status,
1192 int exit_code) {
1193 // Clearing this flag causes us to re-create the renderer when recovering
1194 // from a crashed renderer.
1195 renderer_initialized_ = false;
1197 waiting_for_screen_rects_ack_ = false;
1199 // Must reset these to ensure that keyboard events work with a new renderer.
1200 suppress_next_char_events_ = false;
1202 // Reset some fields in preparation for recovering from a crash.
1203 ResetSizeAndRepaintPendingFlags();
1204 current_size_.SetSize(0, 0);
1205 // After the renderer crashes, the view is destroyed and so the
1206 // RenderWidgetHost cannot track its visibility anymore. We assume such
1207 // RenderWidgetHost to be visible for the sake of internal accounting - be
1208 // careful about changing this - see http://crbug.com/401859.
1210 // We need to at least make sure that the RenderProcessHost is notified about
1211 // the |is_hidden_| change, so that the renderer will have correct visibility
1212 // set when respawned.
1213 if (is_hidden_) {
1214 process_->WidgetRestored();
1215 is_hidden_ = false;
1218 // Reset this to ensure the hung renderer mechanism is working properly.
1219 in_flight_event_count_ = 0;
1220 StopHangMonitorTimeout();
1222 if (view_) {
1223 GpuSurfaceTracker::Get()->SetSurfaceHandle(surface_id_,
1224 gfx::GLSurfaceHandle());
1225 view_->RenderProcessGone(status, exit_code);
1226 view_ = NULL; // The View should be deleted by RenderProcessGone.
1227 view_weak_.reset();
1230 // Reconstruct the input router to ensure that it has fresh state for a new
1231 // renderer. Otherwise it may be stuck waiting for the old renderer to ack an
1232 // event. (In particular, the above call to view_->RenderProcessGone will
1233 // destroy the aura window, which may dispatch a synthetic mouse move.)
1234 input_router_.reset(new InputRouterImpl(
1235 process_, this, this, routing_id_, GetInputRouterConfigForPlatform()));
1237 synthetic_gesture_controller_.reset();
1240 void RenderWidgetHostImpl::UpdateTextDirection(WebTextDirection direction) {
1241 text_direction_updated_ = true;
1242 text_direction_ = direction;
1245 void RenderWidgetHostImpl::CancelUpdateTextDirection() {
1246 if (text_direction_updated_)
1247 text_direction_canceled_ = true;
1250 void RenderWidgetHostImpl::NotifyTextDirection() {
1251 if (text_direction_updated_) {
1252 if (!text_direction_canceled_)
1253 Send(new ViewMsg_SetTextDirection(GetRoutingID(), text_direction_));
1254 text_direction_updated_ = false;
1255 text_direction_canceled_ = false;
1259 void RenderWidgetHostImpl::SetInputMethodActive(bool activate) {
1260 input_method_active_ = activate;
1261 Send(new ViewMsg_SetInputMethodActive(GetRoutingID(), activate));
1264 void RenderWidgetHostImpl::CandidateWindowShown() {
1265 Send(new ViewMsg_CandidateWindowShown(GetRoutingID()));
1268 void RenderWidgetHostImpl::CandidateWindowUpdated() {
1269 Send(new ViewMsg_CandidateWindowUpdated(GetRoutingID()));
1272 void RenderWidgetHostImpl::CandidateWindowHidden() {
1273 Send(new ViewMsg_CandidateWindowHidden(GetRoutingID()));
1276 void RenderWidgetHostImpl::ImeSetComposition(
1277 const base::string16& text,
1278 const std::vector<blink::WebCompositionUnderline>& underlines,
1279 int selection_start,
1280 int selection_end) {
1281 Send(new InputMsg_ImeSetComposition(
1282 GetRoutingID(), text, underlines, selection_start, selection_end));
1285 void RenderWidgetHostImpl::ImeConfirmComposition(
1286 const base::string16& text,
1287 const gfx::Range& replacement_range,
1288 bool keep_selection) {
1289 Send(new InputMsg_ImeConfirmComposition(
1290 GetRoutingID(), text, replacement_range, keep_selection));
1293 void RenderWidgetHostImpl::ImeCancelComposition() {
1294 Send(new InputMsg_ImeSetComposition(GetRoutingID(), base::string16(),
1295 std::vector<blink::WebCompositionUnderline>(), 0, 0));
1298 gfx::Rect RenderWidgetHostImpl::GetRootWindowResizerRect() const {
1299 return gfx::Rect();
1302 void RenderWidgetHostImpl::RequestToLockMouse(bool user_gesture,
1303 bool last_unlocked_by_target) {
1304 // Directly reject to lock the mouse. Subclass can override this method to
1305 // decide whether to allow mouse lock or not.
1306 GotResponseToLockMouseRequest(false);
1309 void RenderWidgetHostImpl::RejectMouseLockOrUnlockIfNecessary() {
1310 DCHECK(!pending_mouse_lock_request_ || !IsMouseLocked());
1311 if (pending_mouse_lock_request_) {
1312 pending_mouse_lock_request_ = false;
1313 Send(new ViewMsg_LockMouse_ACK(routing_id_, false));
1314 } else if (IsMouseLocked()) {
1315 view_->UnlockMouse();
1319 bool RenderWidgetHostImpl::IsMouseLocked() const {
1320 return view_ ? view_->IsMouseLocked() : false;
1323 bool RenderWidgetHostImpl::IsFullscreen() const {
1324 return false;
1327 void RenderWidgetHostImpl::SetAutoResize(bool enable,
1328 const gfx::Size& min_size,
1329 const gfx::Size& max_size) {
1330 auto_resize_enabled_ = enable;
1331 min_size_for_auto_resize_ = min_size;
1332 max_size_for_auto_resize_ = max_size;
1335 void RenderWidgetHostImpl::Cleanup() {
1336 if (view_) {
1337 view_->Destroy();
1338 view_ = nullptr;
1342 void RenderWidgetHostImpl::Destroy() {
1343 NotificationService::current()->Notify(
1344 NOTIFICATION_RENDER_WIDGET_HOST_DESTROYED,
1345 Source<RenderWidgetHost>(this),
1346 NotificationService::NoDetails());
1348 // Tell the view to die.
1349 // Note that in the process of the view shutting down, it can call a ton
1350 // of other messages on us. So if you do any other deinitialization here,
1351 // do it after this call to view_->Destroy().
1352 if (view_) {
1353 view_->Destroy();
1354 view_ = nullptr;
1357 delete this;
1360 void RenderWidgetHostImpl::RendererIsUnresponsive() {
1361 NotificationService::current()->Notify(
1362 NOTIFICATION_RENDER_WIDGET_HOST_HANG,
1363 Source<RenderWidgetHost>(this),
1364 NotificationService::NoDetails());
1365 is_unresponsive_ = true;
1366 NotifyRendererUnresponsive();
1369 void RenderWidgetHostImpl::RendererIsResponsive() {
1370 if (is_unresponsive_) {
1371 is_unresponsive_ = false;
1372 NotifyRendererResponsive();
1376 void RenderWidgetHostImpl::OnRenderViewReady() {
1377 SendScreenRects();
1378 WasResized();
1381 void RenderWidgetHostImpl::OnRenderProcessGone(int status, int exit_code) {
1382 // RenderFrameHost owns a RenderWidgetHost when it needs one, in which case
1383 // it handles destruction.
1384 if (!owned_by_render_frame_host_) {
1385 // TODO(evanm): This synchronously ends up calling "delete this".
1386 // Is that really what we want in response to this message? I'm matching
1387 // previous behavior of the code here.
1388 Destroy();
1389 } else {
1390 RendererExited(static_cast<base::TerminationStatus>(status), exit_code);
1394 void RenderWidgetHostImpl::OnClose() {
1395 Shutdown();
1398 void RenderWidgetHostImpl::OnSetTooltipText(
1399 const base::string16& tooltip_text,
1400 WebTextDirection text_direction_hint) {
1401 // First, add directionality marks around tooltip text if necessary.
1402 // A naive solution would be to simply always wrap the text. However, on
1403 // windows, Unicode directional embedding characters can't be displayed on
1404 // systems that lack RTL fonts and are instead displayed as empty squares.
1406 // To get around this we only wrap the string when we deem it necessary i.e.
1407 // when the locale direction is different than the tooltip direction hint.
1409 // Currently, we use element's directionality as the tooltip direction hint.
1410 // An alternate solution would be to set the overall directionality based on
1411 // trying to detect the directionality from the tooltip text rather than the
1412 // element direction. One could argue that would be a preferable solution
1413 // but we use the current approach to match Fx & IE's behavior.
1414 base::string16 wrapped_tooltip_text = tooltip_text;
1415 if (!tooltip_text.empty()) {
1416 if (text_direction_hint == blink::WebTextDirectionLeftToRight) {
1417 // Force the tooltip to have LTR directionality.
1418 wrapped_tooltip_text =
1419 base::i18n::GetDisplayStringInLTRDirectionality(wrapped_tooltip_text);
1420 } else if (text_direction_hint == blink::WebTextDirectionRightToLeft &&
1421 !base::i18n::IsRTL()) {
1422 // Force the tooltip to have RTL directionality.
1423 base::i18n::WrapStringWithRTLFormatting(&wrapped_tooltip_text);
1426 if (GetView())
1427 view_->SetTooltipText(wrapped_tooltip_text);
1430 void RenderWidgetHostImpl::OnUpdateScreenRectsAck() {
1431 waiting_for_screen_rects_ack_ = false;
1432 if (!view_)
1433 return;
1435 if (view_->GetViewBounds() == last_view_screen_rect_ &&
1436 view_->GetBoundsInRootWindow() == last_window_screen_rect_) {
1437 return;
1440 SendScreenRects();
1443 void RenderWidgetHostImpl::OnRequestMove(const gfx::Rect& pos) {
1444 if (view_) {
1445 view_->SetBounds(pos);
1446 Send(new ViewMsg_Move_ACK(routing_id_));
1450 bool RenderWidgetHostImpl::OnSwapCompositorFrame(
1451 const IPC::Message& message) {
1452 // This trace event is used in
1453 // chrome/browser/extensions/api/cast_streaming/performance_test.cc
1454 TRACE_EVENT0("test_fps,benchmark", "OnSwapCompositorFrame");
1455 ViewHostMsg_SwapCompositorFrame::Param param;
1456 if (!ViewHostMsg_SwapCompositorFrame::Read(&message, &param))
1457 return false;
1458 scoped_ptr<cc::CompositorFrame> frame(new cc::CompositorFrame);
1459 uint32 output_surface_id = get<0>(param);
1460 get<1>(param).AssignTo(frame.get());
1461 std::vector<IPC::Message> messages_to_deliver_with_frame;
1462 messages_to_deliver_with_frame.swap(get<2>(param));
1464 latency_tracker_.OnSwapCompositorFrame(&frame->metadata.latency_info);
1466 input_router_->OnViewUpdated(
1467 GetInputRouterViewFlagsFromCompositorFrameMetadata(frame->metadata));
1469 if (touch_emulator_) {
1470 touch_emulator_->SetDoubleTapSupportForPageEnabled(
1471 !IsMobileOptimizedFrame(frame->metadata));
1474 if (view_) {
1475 view_->OnSwapCompositorFrame(output_surface_id, frame.Pass());
1476 view_->DidReceiveRendererFrame();
1477 } else {
1478 cc::CompositorFrameAck ack;
1479 if (frame->gl_frame_data) {
1480 ack.gl_frame_data = frame->gl_frame_data.Pass();
1481 ack.gl_frame_data->sync_point = 0;
1482 } else if (frame->delegated_frame_data) {
1483 cc::TransferableResource::ReturnResources(
1484 frame->delegated_frame_data->resource_list,
1485 &ack.resources);
1486 } else if (frame->software_frame_data) {
1487 ack.last_software_frame_id = frame->software_frame_data->id;
1489 SendSwapCompositorFrameAck(routing_id_, output_surface_id,
1490 process_->GetID(), ack);
1493 RenderProcessHost* rph = GetProcess();
1494 for (std::vector<IPC::Message>::const_iterator i =
1495 messages_to_deliver_with_frame.begin();
1496 i != messages_to_deliver_with_frame.end();
1497 ++i) {
1498 rph->OnMessageReceived(*i);
1499 if (i->dispatch_error())
1500 rph->OnBadMessageReceived(*i);
1502 messages_to_deliver_with_frame.clear();
1504 return true;
1507 void RenderWidgetHostImpl::OnUpdateRect(
1508 const ViewHostMsg_UpdateRect_Params& params) {
1509 TRACE_EVENT0("renderer_host", "RenderWidgetHostImpl::OnUpdateRect");
1510 TimeTicks paint_start = TimeTicks::Now();
1512 // Update our knowledge of the RenderWidget's size.
1513 current_size_ = params.view_size;
1515 bool is_resize_ack =
1516 ViewHostMsg_UpdateRect_Flags::is_resize_ack(params.flags);
1518 // resize_ack_pending_ needs to be cleared before we call DidPaintRect, since
1519 // that will end up reaching GetBackingStore.
1520 if (is_resize_ack) {
1521 DCHECK(!g_check_for_pending_resize_ack || resize_ack_pending_);
1522 resize_ack_pending_ = false;
1525 bool is_repaint_ack =
1526 ViewHostMsg_UpdateRect_Flags::is_repaint_ack(params.flags);
1527 if (is_repaint_ack) {
1528 DCHECK(repaint_ack_pending_);
1529 TRACE_EVENT_ASYNC_END0(
1530 "renderer_host", "RenderWidgetHostImpl::repaint_ack_pending_", this);
1531 repaint_ack_pending_ = false;
1532 TimeDelta delta = TimeTicks::Now() - repaint_start_time_;
1533 UMA_HISTOGRAM_TIMES("MPArch.RWH_RepaintDelta", delta);
1536 DCHECK(!params.view_size.IsEmpty());
1538 DidUpdateBackingStore(params, paint_start);
1540 if (auto_resize_enabled_) {
1541 bool post_callback = new_auto_size_.IsEmpty();
1542 new_auto_size_ = params.view_size;
1543 if (post_callback) {
1544 base::MessageLoop::current()->PostTask(
1545 FROM_HERE,
1546 base::Bind(&RenderWidgetHostImpl::DelayedAutoResized,
1547 weak_factory_.GetWeakPtr()));
1551 // Log the time delta for processing a paint message. On platforms that don't
1552 // support asynchronous painting, this is equivalent to
1553 // MPArch.RWH_TotalPaintTime.
1554 TimeDelta delta = TimeTicks::Now() - paint_start;
1555 UMA_HISTOGRAM_TIMES("MPArch.RWH_OnMsgUpdateRect", delta);
1558 void RenderWidgetHostImpl::DidUpdateBackingStore(
1559 const ViewHostMsg_UpdateRect_Params& params,
1560 const TimeTicks& paint_start) {
1561 TRACE_EVENT0("renderer_host", "RenderWidgetHostImpl::DidUpdateBackingStore");
1562 TimeTicks update_start = TimeTicks::Now();
1564 // Move the plugins if the view hasn't already been destroyed. Plugin moves
1565 // will not be re-issued, so must move them now, regardless of whether we
1566 // paint or not. MovePluginWindows attempts to move the plugin windows and
1567 // in the process could dispatch other window messages which could cause the
1568 // view to be destroyed.
1569 if (view_)
1570 view_->MovePluginWindows(params.plugin_window_moves);
1572 NotificationService::current()->Notify(
1573 NOTIFICATION_RENDER_WIDGET_HOST_DID_UPDATE_BACKING_STORE,
1574 Source<RenderWidgetHost>(this),
1575 NotificationService::NoDetails());
1577 // We don't need to update the view if the view is hidden. We must do this
1578 // early return after the ACK is sent, however, or the renderer will not send
1579 // us more data.
1580 if (is_hidden_)
1581 return;
1583 // If we got a resize ack, then perhaps we have another resize to send?
1584 bool is_resize_ack =
1585 ViewHostMsg_UpdateRect_Flags::is_resize_ack(params.flags);
1586 if (is_resize_ack)
1587 WasResized();
1589 // Log the time delta for processing a paint message.
1590 TimeTicks now = TimeTicks::Now();
1591 TimeDelta delta = now - update_start;
1592 UMA_HISTOGRAM_TIMES("MPArch.RWH_DidUpdateBackingStore", delta);
1595 void RenderWidgetHostImpl::OnQueueSyntheticGesture(
1596 const SyntheticGesturePacket& gesture_packet) {
1597 // Only allow untrustworthy gestures if explicitly enabled.
1598 if (!base::CommandLine::ForCurrentProcess()->HasSwitch(
1599 cc::switches::kEnableGpuBenchmarking)) {
1600 bad_message::ReceivedBadMessage(GetProcess(),
1601 bad_message::RWH_SYNTHETIC_GESTURE);
1602 return;
1605 QueueSyntheticGesture(
1606 SyntheticGesture::Create(*gesture_packet.gesture_params()),
1607 base::Bind(&RenderWidgetHostImpl::OnSyntheticGestureCompleted,
1608 weak_factory_.GetWeakPtr()));
1611 void RenderWidgetHostImpl::OnFocus() {
1612 // Only RenderViewHost can deal with that message.
1613 bad_message::ReceivedBadMessage(GetProcess(), bad_message::RWH_FOCUS);
1616 void RenderWidgetHostImpl::OnBlur() {
1617 // Only RenderViewHost can deal with that message.
1618 bad_message::ReceivedBadMessage(GetProcess(), bad_message::RWH_BLUR);
1621 void RenderWidgetHostImpl::OnSetCursor(const WebCursor& cursor) {
1622 SetCursor(cursor);
1625 void RenderWidgetHostImpl::SetTouchEventEmulationEnabled(
1626 bool enabled, ui::GestureProviderConfigType config_type) {
1627 if (enabled) {
1628 if (!touch_emulator_)
1629 touch_emulator_.reset(new TouchEmulator(this));
1630 touch_emulator_->Enable(config_type);
1631 } else {
1632 if (touch_emulator_)
1633 touch_emulator_->Disable();
1637 void RenderWidgetHostImpl::OnTextInputTypeChanged(
1638 ui::TextInputType type,
1639 ui::TextInputMode input_mode,
1640 bool can_compose_inline,
1641 int flags) {
1642 if (view_)
1643 view_->TextInputTypeChanged(type, input_mode, can_compose_inline, flags);
1646 void RenderWidgetHostImpl::OnImeCompositionRangeChanged(
1647 const gfx::Range& range,
1648 const std::vector<gfx::Rect>& character_bounds) {
1649 if (view_)
1650 view_->ImeCompositionRangeChanged(range, character_bounds);
1653 void RenderWidgetHostImpl::OnImeCancelComposition() {
1654 if (view_)
1655 view_->ImeCancelComposition();
1658 void RenderWidgetHostImpl::OnLockMouse(bool user_gesture,
1659 bool last_unlocked_by_target,
1660 bool privileged) {
1662 if (pending_mouse_lock_request_) {
1663 Send(new ViewMsg_LockMouse_ACK(routing_id_, false));
1664 return;
1665 } else if (IsMouseLocked()) {
1666 Send(new ViewMsg_LockMouse_ACK(routing_id_, true));
1667 return;
1670 pending_mouse_lock_request_ = true;
1671 if (privileged && allow_privileged_mouse_lock_) {
1672 // Directly approve to lock the mouse.
1673 GotResponseToLockMouseRequest(true);
1674 } else {
1675 RequestToLockMouse(user_gesture, last_unlocked_by_target);
1679 void RenderWidgetHostImpl::OnUnlockMouse() {
1680 RejectMouseLockOrUnlockIfNecessary();
1683 void RenderWidgetHostImpl::OnShowDisambiguationPopup(
1684 const gfx::Rect& rect_pixels,
1685 const gfx::Size& size,
1686 const cc::SharedBitmapId& id) {
1687 DCHECK(!rect_pixels.IsEmpty());
1688 DCHECK(!size.IsEmpty());
1690 scoped_ptr<cc::SharedBitmap> bitmap =
1691 HostSharedBitmapManager::current()->GetSharedBitmapFromId(size, id);
1692 if (!bitmap) {
1693 bad_message::ReceivedBadMessage(GetProcess(),
1694 bad_message::RWH_SHARED_BITMAP);
1695 return;
1698 DCHECK(bitmap->pixels());
1700 SkImageInfo info = SkImageInfo::MakeN32Premul(size.width(), size.height());
1701 SkBitmap zoomed_bitmap;
1702 zoomed_bitmap.installPixels(info, bitmap->pixels(), info.minRowBytes());
1704 // Note that |rect| is in coordinates of pixels relative to the window origin.
1705 // Aura-based systems will want to convert this to DIPs.
1706 if (view_)
1707 view_->ShowDisambiguationPopup(rect_pixels, zoomed_bitmap);
1709 // It is assumed that the disambiguation popup will make a copy of the
1710 // provided zoomed image, so we delete this one.
1711 zoomed_bitmap.setPixels(0);
1712 Send(new ViewMsg_ReleaseDisambiguationPopupBitmap(GetRoutingID(), id));
1715 #if defined(OS_WIN)
1716 void RenderWidgetHostImpl::OnWindowlessPluginDummyWindowCreated(
1717 gfx::NativeViewId dummy_activation_window) {
1718 HWND hwnd = reinterpret_cast<HWND>(dummy_activation_window);
1720 // This may happen as a result of a race condition when the plugin is going
1721 // away.
1722 wchar_t window_title[MAX_PATH + 1] = {0};
1723 if (!IsWindow(hwnd) ||
1724 !GetWindowText(hwnd, window_title, arraysize(window_title)) ||
1725 lstrcmpiW(window_title, kDummyActivationWindowName) != 0) {
1726 return;
1729 #if defined(USE_AURA)
1730 SetParent(hwnd,
1731 reinterpret_cast<HWND>(view_->GetParentForWindowlessPlugin()));
1732 #else
1733 SetParent(hwnd, reinterpret_cast<HWND>(GetNativeViewId()));
1734 #endif
1735 dummy_windows_for_activation_.push_back(hwnd);
1738 void RenderWidgetHostImpl::OnWindowlessPluginDummyWindowDestroyed(
1739 gfx::NativeViewId dummy_activation_window) {
1740 HWND hwnd = reinterpret_cast<HWND>(dummy_activation_window);
1741 std::list<HWND>::iterator i = dummy_windows_for_activation_.begin();
1742 for (; i != dummy_windows_for_activation_.end(); ++i) {
1743 if ((*i) == hwnd) {
1744 dummy_windows_for_activation_.erase(i);
1745 return;
1748 NOTREACHED() << "Unknown dummy window";
1750 #endif
1752 void RenderWidgetHostImpl::SetIgnoreInputEvents(bool ignore_input_events) {
1753 ignore_input_events_ = ignore_input_events;
1756 bool RenderWidgetHostImpl::KeyPressListenersHandleEvent(
1757 const NativeWebKeyboardEvent& event) {
1758 if (event.skip_in_browser || event.type != WebKeyboardEvent::RawKeyDown)
1759 return false;
1761 for (size_t i = 0; i < key_press_event_callbacks_.size(); i++) {
1762 size_t original_size = key_press_event_callbacks_.size();
1763 if (key_press_event_callbacks_[i].Run(event))
1764 return true;
1766 // Check whether the callback that just ran removed itself, in which case
1767 // the iterator needs to be decremented to properly account for the removal.
1768 size_t current_size = key_press_event_callbacks_.size();
1769 if (current_size != original_size) {
1770 DCHECK_EQ(original_size - 1, current_size);
1771 --i;
1775 return false;
1778 InputEventAckState RenderWidgetHostImpl::FilterInputEvent(
1779 const blink::WebInputEvent& event, const ui::LatencyInfo& latency_info) {
1780 // Don't ignore touch cancel events, since they may be sent while input
1781 // events are being ignored in order to keep the renderer from getting
1782 // confused about how many touches are active.
1783 if (IgnoreInputEvents() && event.type != WebInputEvent::TouchCancel)
1784 return INPUT_EVENT_ACK_STATE_NO_CONSUMER_EXISTS;
1786 if (!process_->HasConnection())
1787 return INPUT_EVENT_ACK_STATE_UNKNOWN;
1789 if (event.type == WebInputEvent::MouseDown)
1790 OnUserGesture();
1792 return view_ ? view_->FilterInputEvent(event)
1793 : INPUT_EVENT_ACK_STATE_NOT_CONSUMED;
1796 void RenderWidgetHostImpl::IncrementInFlightEventCount() {
1797 increment_in_flight_event_count();
1798 if (!is_hidden_)
1799 StartHangMonitorTimeout(hung_renderer_delay_);
1802 void RenderWidgetHostImpl::DecrementInFlightEventCount() {
1803 if (decrement_in_flight_event_count() <= 0) {
1804 // Cancel pending hung renderer checks since the renderer is responsive.
1805 StopHangMonitorTimeout();
1806 } else {
1807 // The renderer is responsive, but there are in-flight events to wait for.
1808 if (!is_hidden_)
1809 RestartHangMonitorTimeout();
1813 void RenderWidgetHostImpl::OnHasTouchEventHandlers(bool has_handlers) {
1814 has_touch_handler_ = has_handlers;
1817 void RenderWidgetHostImpl::DidFlush() {
1818 if (synthetic_gesture_controller_)
1819 synthetic_gesture_controller_->OnDidFlushInput();
1822 void RenderWidgetHostImpl::DidOverscroll(const DidOverscrollParams& params) {
1823 if (view_)
1824 view_->DidOverscroll(params);
1827 void RenderWidgetHostImpl::DidStopFlinging() {
1828 if (view_)
1829 view_->DidStopFlinging();
1832 void RenderWidgetHostImpl::OnKeyboardEventAck(
1833 const NativeWebKeyboardEvent& event,
1834 InputEventAckState ack_result) {
1835 #if defined(OS_MACOSX)
1836 if (!is_hidden() && view_ && view_->PostProcessEventForPluginIme(event))
1837 return;
1838 #endif
1840 // We only send unprocessed key event upwards if we are not hidden,
1841 // because the user has moved away from us and no longer expect any effect
1842 // of this key event.
1843 const bool processed = (INPUT_EVENT_ACK_STATE_CONSUMED == ack_result);
1844 if (delegate_ && !processed && !is_hidden() && !event.skip_in_browser) {
1845 delegate_->HandleKeyboardEvent(event);
1847 // WARNING: This RenderWidgetHostImpl can be deallocated at this point
1848 // (i.e. in the case of Ctrl+W, where the call to
1849 // HandleKeyboardEvent destroys this RenderWidgetHostImpl).
1853 void RenderWidgetHostImpl::OnWheelEventAck(
1854 const MouseWheelEventWithLatencyInfo& wheel_event,
1855 InputEventAckState ack_result) {
1856 latency_tracker_.OnInputEventAck(wheel_event.event, &wheel_event.latency);
1858 if (!is_hidden() && view_) {
1859 if (ack_result != INPUT_EVENT_ACK_STATE_CONSUMED &&
1860 delegate_->HandleWheelEvent(wheel_event.event)) {
1861 ack_result = INPUT_EVENT_ACK_STATE_CONSUMED;
1863 view_->WheelEventAck(wheel_event.event, ack_result);
1867 void RenderWidgetHostImpl::OnGestureEventAck(
1868 const GestureEventWithLatencyInfo& event,
1869 InputEventAckState ack_result) {
1870 latency_tracker_.OnInputEventAck(event.event, &event.latency);
1872 if (view_)
1873 view_->GestureEventAck(event.event, ack_result);
1876 void RenderWidgetHostImpl::OnTouchEventAck(
1877 const TouchEventWithLatencyInfo& event,
1878 InputEventAckState ack_result) {
1879 latency_tracker_.OnInputEventAck(event.event, &event.latency);
1881 if (touch_emulator_ &&
1882 touch_emulator_->HandleTouchEventAck(event.event, ack_result)) {
1883 return;
1886 if (view_)
1887 view_->ProcessAckedTouchEvent(event, ack_result);
1890 void RenderWidgetHostImpl::OnUnexpectedEventAck(UnexpectedEventAckType type) {
1891 if (type == BAD_ACK_MESSAGE) {
1892 bad_message::ReceivedBadMessage(process_, bad_message::RWH_BAD_ACK_MESSAGE);
1893 } else if (type == UNEXPECTED_EVENT_TYPE) {
1894 suppress_next_char_events_ = false;
1898 void RenderWidgetHostImpl::OnSyntheticGestureCompleted(
1899 SyntheticGesture::Result result) {
1900 Send(new InputMsg_SyntheticGestureCompleted(GetRoutingID()));
1903 bool RenderWidgetHostImpl::IgnoreInputEvents() const {
1904 return ignore_input_events_ || process_->IgnoreInputEvents();
1907 void RenderWidgetHostImpl::StartUserGesture() {
1908 OnUserGesture();
1911 void RenderWidgetHostImpl::SetBackgroundOpaque(bool opaque) {
1912 Send(new ViewMsg_SetBackgroundOpaque(GetRoutingID(), opaque));
1915 void RenderWidgetHostImpl::SetEditCommandsForNextKeyEvent(
1916 const std::vector<EditCommand>& commands) {
1917 Send(new InputMsg_SetEditCommandsForNextKeyEvent(GetRoutingID(), commands));
1920 void RenderWidgetHostImpl::ExecuteEditCommand(const std::string& command,
1921 const std::string& value) {
1922 Send(new InputMsg_ExecuteEditCommand(GetRoutingID(), command, value));
1925 void RenderWidgetHostImpl::ScrollFocusedEditableNodeIntoRect(
1926 const gfx::Rect& rect) {
1927 Send(new InputMsg_ScrollFocusedEditableNodeIntoRect(GetRoutingID(), rect));
1930 void RenderWidgetHostImpl::MoveCaret(const gfx::Point& point) {
1931 Send(new InputMsg_MoveCaret(GetRoutingID(), point));
1934 bool RenderWidgetHostImpl::GotResponseToLockMouseRequest(bool allowed) {
1935 if (!allowed) {
1936 RejectMouseLockOrUnlockIfNecessary();
1937 return false;
1938 } else {
1939 if (!pending_mouse_lock_request_) {
1940 // This is possible, e.g., the plugin sends us an unlock request before
1941 // the user allows to lock to mouse.
1942 return false;
1945 pending_mouse_lock_request_ = false;
1946 if (!view_ || !view_->HasFocus()|| !view_->LockMouse()) {
1947 Send(new ViewMsg_LockMouse_ACK(routing_id_, false));
1948 return false;
1949 } else {
1950 Send(new ViewMsg_LockMouse_ACK(routing_id_, true));
1951 return true;
1956 // static
1957 void RenderWidgetHostImpl::SendSwapCompositorFrameAck(
1958 int32 route_id,
1959 uint32 output_surface_id,
1960 int renderer_host_id,
1961 const cc::CompositorFrameAck& ack) {
1962 RenderProcessHost* host = RenderProcessHost::FromID(renderer_host_id);
1963 if (!host)
1964 return;
1965 host->Send(new ViewMsg_SwapCompositorFrameAck(
1966 route_id, output_surface_id, ack));
1969 // static
1970 void RenderWidgetHostImpl::SendReclaimCompositorResources(
1971 int32 route_id,
1972 uint32 output_surface_id,
1973 int renderer_host_id,
1974 const cc::CompositorFrameAck& ack) {
1975 RenderProcessHost* host = RenderProcessHost::FromID(renderer_host_id);
1976 if (!host)
1977 return;
1978 host->Send(
1979 new ViewMsg_ReclaimCompositorResources(route_id, output_surface_id, ack));
1982 void RenderWidgetHostImpl::DelayedAutoResized() {
1983 gfx::Size new_size = new_auto_size_;
1984 // Clear the new_auto_size_ since the empty value is used as a flag to
1985 // indicate that no callback is in progress (i.e. without this line
1986 // DelayedAutoResized will not get called again).
1987 new_auto_size_.SetSize(0, 0);
1988 if (!auto_resize_enabled_)
1989 return;
1991 OnRenderAutoResized(new_size);
1994 void RenderWidgetHostImpl::DetachDelegate() {
1995 delegate_ = NULL;
1998 void RenderWidgetHostImpl::FrameSwapped(const ui::LatencyInfo& latency_info) {
1999 ui::LatencyInfo::LatencyComponent window_snapshot_component;
2000 if (latency_info.FindLatency(ui::WINDOW_SNAPSHOT_FRAME_NUMBER_COMPONENT,
2001 GetLatencyComponentId(),
2002 &window_snapshot_component)) {
2003 int sequence_number = static_cast<int>(
2004 window_snapshot_component.sequence_number);
2005 #if defined(OS_MACOSX)
2006 // On Mac, when using CoreAnmation, there is a delay between when content
2007 // is drawn to the screen, and when the snapshot will actually pick up
2008 // that content. Insert a manual delay of 1/6th of a second (to simulate
2009 // 10 frames at 60 fps) before actually taking the snapshot.
2010 base::MessageLoop::current()->PostDelayedTask(
2011 FROM_HERE,
2012 base::Bind(&RenderWidgetHostImpl::WindowSnapshotReachedScreen,
2013 weak_factory_.GetWeakPtr(),
2014 sequence_number),
2015 base::TimeDelta::FromSecondsD(1. / 6));
2016 #else
2017 WindowSnapshotReachedScreen(sequence_number);
2018 #endif
2021 latency_tracker_.OnFrameSwapped(latency_info);
2024 void RenderWidgetHostImpl::DidReceiveRendererFrame() {
2025 view_->DidReceiveRendererFrame();
2028 void RenderWidgetHostImpl::WindowSnapshotReachedScreen(int snapshot_id) {
2029 DCHECK(base::MessageLoopForUI::IsCurrent());
2031 gfx::Rect view_bounds = GetView()->GetViewBounds();
2032 gfx::Rect snapshot_bounds(view_bounds.size());
2034 std::vector<unsigned char> png;
2035 if (ui::GrabViewSnapshot(
2036 GetView()->GetNativeView(), &png, snapshot_bounds)) {
2037 OnSnapshotDataReceived(snapshot_id, &png.front(), png.size());
2038 return;
2041 ui::GrabViewSnapshotAsync(
2042 GetView()->GetNativeView(),
2043 snapshot_bounds,
2044 base::ThreadTaskRunnerHandle::Get(),
2045 base::Bind(&RenderWidgetHostImpl::OnSnapshotDataReceivedAsync,
2046 weak_factory_.GetWeakPtr(),
2047 snapshot_id));
2050 void RenderWidgetHostImpl::OnSnapshotDataReceived(int snapshot_id,
2051 const unsigned char* data,
2052 size_t size) {
2053 // Any pending snapshots with a lower ID than the one received are considered
2054 // to be implicitly complete, and returned the same snapshot data.
2055 PendingSnapshotMap::iterator it = pending_browser_snapshots_.begin();
2056 while(it != pending_browser_snapshots_.end()) {
2057 if (it->first <= snapshot_id) {
2058 it->second.Run(data, size);
2059 pending_browser_snapshots_.erase(it++);
2060 } else {
2061 ++it;
2066 void RenderWidgetHostImpl::OnSnapshotDataReceivedAsync(
2067 int snapshot_id,
2068 scoped_refptr<base::RefCountedBytes> png_data) {
2069 if (png_data.get())
2070 OnSnapshotDataReceived(snapshot_id, png_data->front(), png_data->size());
2071 else
2072 OnSnapshotDataReceived(snapshot_id, NULL, 0);
2075 // static
2076 void RenderWidgetHostImpl::CompositorFrameDrawn(
2077 const std::vector<ui::LatencyInfo>& latency_info) {
2078 for (size_t i = 0; i < latency_info.size(); i++) {
2079 std::set<RenderWidgetHostImpl*> rwhi_set;
2080 for (ui::LatencyInfo::LatencyMap::const_iterator b =
2081 latency_info[i].latency_components.begin();
2082 b != latency_info[i].latency_components.end();
2083 ++b) {
2084 if (b->first.first == ui::INPUT_EVENT_LATENCY_BEGIN_RWH_COMPONENT ||
2085 b->first.first == ui::WINDOW_SNAPSHOT_FRAME_NUMBER_COMPONENT ||
2086 b->first.first == ui::TAB_SHOW_COMPONENT) {
2087 // Matches with GetLatencyComponentId
2088 int routing_id = b->first.second & 0xffffffff;
2089 int process_id = (b->first.second >> 32) & 0xffffffff;
2090 RenderWidgetHost* rwh =
2091 RenderWidgetHost::FromID(process_id, routing_id);
2092 if (!rwh) {
2093 continue;
2095 RenderWidgetHostImpl* rwhi = RenderWidgetHostImpl::From(rwh);
2096 if (rwhi_set.insert(rwhi).second)
2097 rwhi->FrameSwapped(latency_info[i]);
2103 BrowserAccessibilityManager*
2104 RenderWidgetHostImpl::GetRootBrowserAccessibilityManager() {
2105 return delegate_ ? delegate_->GetRootBrowserAccessibilityManager() : NULL;
2108 BrowserAccessibilityManager*
2109 RenderWidgetHostImpl::GetOrCreateRootBrowserAccessibilityManager() {
2110 return delegate_ ?
2111 delegate_->GetOrCreateRootBrowserAccessibilityManager() : NULL;
2114 base::TimeDelta RenderWidgetHostImpl::GetEstimatedBrowserCompositeTime() const {
2115 return latency_tracker_.GetEstimatedBrowserCompositeTime();
2118 #if defined(OS_WIN)
2119 gfx::NativeViewAccessible
2120 RenderWidgetHostImpl::GetParentNativeViewAccessible() {
2121 return delegate_ ? delegate_->GetParentNativeViewAccessible() : NULL;
2123 #endif
2125 SkColorType RenderWidgetHostImpl::PreferredReadbackFormat() {
2126 if (view_)
2127 return view_->PreferredReadbackFormat();
2128 return kN32_SkColorType;
2131 } // namespace content