Roll DEPS for PDFium to 19ae17578f99621100a26dac3e2c7c3dbf7c7cd1
[chromium-blink-merge.git] / content / browser / renderer_host / render_widget_host_impl.cc
blob9a1f4b09c38beb9d1633cc2640b1f1b3186fcf4c
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 hung_renderer_delay_(
163 base::TimeDelta::FromMilliseconds(kHungRendererDelayMs)),
164 renderer_initialized_(false),
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_granted = IsFullscreenGranted();
598 resize_params->display_mode = GetDisplayMode();
601 const bool size_changed =
602 !old_resize_params_ ||
603 old_resize_params_->new_size != resize_params->new_size ||
604 (old_resize_params_->physical_backing_size.IsEmpty() &&
605 !resize_params->physical_backing_size.IsEmpty());
606 bool dirty =
607 size_changed || screen_info_out_of_date_ ||
608 old_resize_params_->physical_backing_size !=
609 resize_params->physical_backing_size ||
610 old_resize_params_->is_fullscreen_granted !=
611 resize_params->is_fullscreen_granted ||
612 old_resize_params_->display_mode != resize_params->display_mode ||
613 old_resize_params_->top_controls_height !=
614 resize_params->top_controls_height ||
615 old_resize_params_->top_controls_shrink_blink_size !=
616 resize_params->top_controls_shrink_blink_size ||
617 old_resize_params_->visible_viewport_size !=
618 resize_params->visible_viewport_size;
620 // We don't expect to receive an ACK when the requested size or the physical
621 // backing size is empty, or when the main viewport size didn't change.
622 resize_params->needs_resize_ack =
623 g_check_for_pending_resize_ack && !resize_params->new_size.IsEmpty() &&
624 !resize_params->physical_backing_size.IsEmpty() && size_changed;
626 return dirty;
629 void RenderWidgetHostImpl::SetInitialRenderSizeParams(
630 const ViewMsg_Resize_Params& resize_params) {
631 resize_ack_pending_ = resize_params.needs_resize_ack;
633 old_resize_params_ =
634 make_scoped_ptr(new ViewMsg_Resize_Params(resize_params));
637 void RenderWidgetHostImpl::WasResized() {
638 // Skip if the |delegate_| has already been detached because
639 // it's web contents is being deleted.
640 if (resize_ack_pending_ || !process_->HasConnection() || !view_ ||
641 !renderer_initialized_ || auto_resize_enabled_ || !delegate_) {
642 return;
645 scoped_ptr<ViewMsg_Resize_Params> params(new ViewMsg_Resize_Params);
646 if (!GetResizeParams(params.get()))
647 return;
649 bool width_changed =
650 !old_resize_params_ ||
651 old_resize_params_->new_size.width() != params->new_size.width();
652 if (Send(new ViewMsg_Resize(routing_id_, *params))) {
653 resize_ack_pending_ = params->needs_resize_ack;
654 old_resize_params_.swap(params);
657 if (delegate_)
658 delegate_->RenderWidgetWasResized(this, width_changed);
661 void RenderWidgetHostImpl::ResizeRectChanged(const gfx::Rect& new_rect) {
662 Send(new ViewMsg_ChangeResizeRect(routing_id_, new_rect));
665 void RenderWidgetHostImpl::GotFocus() {
666 Focus();
667 if (delegate_)
668 delegate_->RenderWidgetGotFocus(this);
671 void RenderWidgetHostImpl::Focus() {
672 is_focused_ = true;
674 Send(new InputMsg_SetFocus(routing_id_, true));
677 void RenderWidgetHostImpl::Blur() {
678 is_focused_ = false;
680 // If there is a pending mouse lock request, we don't want to reject it at
681 // this point. The user can switch focus back to this view and approve the
682 // request later.
683 if (IsMouseLocked())
684 view_->UnlockMouse();
686 if (touch_emulator_)
687 touch_emulator_->CancelTouch();
689 Send(new InputMsg_SetFocus(routing_id_, false));
692 void RenderWidgetHostImpl::LostCapture() {
693 if (touch_emulator_)
694 touch_emulator_->CancelTouch();
696 Send(new InputMsg_MouseCaptureLost(routing_id_));
699 void RenderWidgetHostImpl::SetActive(bool active) {
700 Send(new ViewMsg_SetActive(routing_id_, active));
703 void RenderWidgetHostImpl::LostMouseLock() {
704 Send(new ViewMsg_MouseLockLost(routing_id_));
707 void RenderWidgetHostImpl::ViewDestroyed() {
708 RejectMouseLockOrUnlockIfNecessary();
710 // TODO(evanm): tracking this may no longer be necessary;
711 // eliminate this function if so.
712 SetView(NULL);
715 void RenderWidgetHostImpl::CopyFromBackingStore(
716 const gfx::Rect& src_subrect,
717 const gfx::Size& accelerated_dst_size,
718 ReadbackRequestCallback& callback,
719 const SkColorType color_type) {
720 if (view_) {
721 TRACE_EVENT0("browser",
722 "RenderWidgetHostImpl::CopyFromBackingStore::FromCompositingSurface");
723 gfx::Rect accelerated_copy_rect = src_subrect.IsEmpty() ?
724 gfx::Rect(view_->GetViewBounds().size()) : src_subrect;
725 view_->CopyFromCompositingSurface(
726 accelerated_copy_rect, accelerated_dst_size, callback, color_type);
727 return;
730 callback.Run(SkBitmap(), content::READBACK_FAILED);
733 bool RenderWidgetHostImpl::CanCopyFromBackingStore() {
734 if (view_)
735 return view_->IsSurfaceAvailableForCopy();
736 return false;
739 #if defined(OS_ANDROID)
740 void RenderWidgetHostImpl::LockBackingStore() {
741 if (view_)
742 view_->LockCompositingSurface();
745 void RenderWidgetHostImpl::UnlockBackingStore() {
746 if (view_)
747 view_->UnlockCompositingSurface();
749 #endif
751 #if defined(OS_MACOSX)
752 void RenderWidgetHostImpl::PauseForPendingResizeOrRepaints() {
753 TRACE_EVENT0("browser",
754 "RenderWidgetHostImpl::PauseForPendingResizeOrRepaints");
756 if (!CanPauseForPendingResizeOrRepaints())
757 return;
759 WaitForSurface();
762 bool RenderWidgetHostImpl::CanPauseForPendingResizeOrRepaints() {
763 // Do not pause if the view is hidden.
764 if (is_hidden())
765 return false;
767 // Do not pause if there is not a paint or resize already coming.
768 if (!repaint_ack_pending_ && !resize_ack_pending_)
769 return false;
771 return true;
774 void RenderWidgetHostImpl::WaitForSurface() {
775 // How long to (synchronously) wait for the renderer to respond with a
776 // new frame when our current frame doesn't exist or is the wrong size.
777 // This timeout impacts the "choppiness" of our window resize.
778 const int kPaintMsgTimeoutMS = 50;
780 if (!view_)
781 return;
783 // The view_size will be current_size_ for auto-sized views and otherwise the
784 // size of the view_. (For auto-sized views, current_size_ is updated during
785 // UpdateRect messages.)
786 gfx::Size view_size = current_size_;
787 if (!auto_resize_enabled_) {
788 // Get the desired size from the current view bounds.
789 gfx::Rect view_rect = view_->GetViewBounds();
790 if (view_rect.IsEmpty())
791 return;
792 view_size = view_rect.size();
795 TRACE_EVENT2("renderer_host",
796 "RenderWidgetHostImpl::WaitForSurface",
797 "width",
798 base::IntToString(view_size.width()),
799 "height",
800 base::IntToString(view_size.height()));
802 // We should not be asked to paint while we are hidden. If we are hidden,
803 // then it means that our consumer failed to call WasShown.
804 DCHECK(!is_hidden_) << "WaitForSurface called while hidden!";
806 // We should never be called recursively; this can theoretically lead to
807 // infinite recursion and almost certainly leads to lower performance.
808 DCHECK(!in_get_backing_store_) << "WaitForSurface called recursively!";
809 base::AutoReset<bool> auto_reset_in_get_backing_store(
810 &in_get_backing_store_, true);
812 // We might have a surface that we can use already.
813 if (view_->HasAcceleratedSurface(view_size))
814 return;
816 // Request that the renderer produce a frame of the right size, if it
817 // hasn't been requested already.
818 if (!repaint_ack_pending_ && !resize_ack_pending_) {
819 repaint_start_time_ = TimeTicks::Now();
820 repaint_ack_pending_ = true;
821 TRACE_EVENT_ASYNC_BEGIN0(
822 "renderer_host", "RenderWidgetHostImpl::repaint_ack_pending_", this);
823 Send(new ViewMsg_Repaint(routing_id_, view_size));
826 // Pump a nested message loop until we time out or get a frame of the right
827 // size.
828 TimeTicks start_time = TimeTicks::Now();
829 TimeDelta time_left = TimeDelta::FromMilliseconds(kPaintMsgTimeoutMS);
830 TimeTicks timeout_time = start_time + time_left;
831 while (1) {
832 TRACE_EVENT0("renderer_host", "WaitForSurface::WaitForSingleTaskToRun");
833 if (RenderWidgetResizeHelper::Get()->WaitForSingleTaskToRun(time_left)) {
834 // For auto-resized views, current_size_ determines the view_size and it
835 // may have changed during the handling of an UpdateRect message.
836 if (auto_resize_enabled_)
837 view_size = current_size_;
838 if (view_->HasAcceleratedSurface(view_size))
839 break;
841 time_left = timeout_time - TimeTicks::Now();
842 if (time_left <= TimeDelta::FromSeconds(0)) {
843 TRACE_EVENT0("renderer_host", "WaitForSurface::Timeout");
844 break;
848 UMA_HISTOGRAM_CUSTOM_TIMES("OSX.RendererHost.SurfaceWaitTime",
849 TimeTicks::Now() - start_time,
850 TimeDelta::FromMilliseconds(1),
851 TimeDelta::FromMilliseconds(200), 50);
853 #endif
855 bool RenderWidgetHostImpl::ScheduleComposite() {
856 if (is_hidden_ || current_size_.IsEmpty() || repaint_ack_pending_ ||
857 resize_ack_pending_) {
858 return false;
861 // Send out a request to the renderer to paint the view if required.
862 repaint_start_time_ = TimeTicks::Now();
863 repaint_ack_pending_ = true;
864 TRACE_EVENT_ASYNC_BEGIN0(
865 "renderer_host", "RenderWidgetHostImpl::repaint_ack_pending_", this);
866 Send(new ViewMsg_Repaint(routing_id_, current_size_));
867 return true;
870 void RenderWidgetHostImpl::StartHangMonitorTimeout(base::TimeDelta delay) {
871 if (hang_monitor_timeout_)
872 hang_monitor_timeout_->Start(delay);
875 void RenderWidgetHostImpl::RestartHangMonitorTimeout() {
876 if (hang_monitor_timeout_)
877 hang_monitor_timeout_->Restart(hung_renderer_delay_);
880 void RenderWidgetHostImpl::StopHangMonitorTimeout() {
881 if (hang_monitor_timeout_)
882 hang_monitor_timeout_->Stop();
883 RendererIsResponsive();
886 void RenderWidgetHostImpl::ForwardMouseEvent(const WebMouseEvent& mouse_event) {
887 ForwardMouseEventWithLatencyInfo(mouse_event, ui::LatencyInfo());
890 void RenderWidgetHostImpl::ForwardMouseEventWithLatencyInfo(
891 const blink::WebMouseEvent& mouse_event,
892 const ui::LatencyInfo& ui_latency) {
893 TRACE_EVENT2("input", "RenderWidgetHostImpl::ForwardMouseEvent",
894 "x", mouse_event.x, "y", mouse_event.y);
896 for (size_t i = 0; i < mouse_event_callbacks_.size(); ++i) {
897 if (mouse_event_callbacks_[i].Run(mouse_event))
898 return;
901 if (IgnoreInputEvents())
902 return;
904 if (touch_emulator_ && touch_emulator_->HandleMouseEvent(mouse_event))
905 return;
907 MouseEventWithLatencyInfo mouse_with_latency(mouse_event, ui_latency);
908 latency_tracker_.OnInputEvent(mouse_event, &mouse_with_latency.latency);
909 input_router_->SendMouseEvent(mouse_with_latency);
911 // Pass mouse state to gpu service if the subscribe uniform
912 // extension is enabled.
913 if (process_->SubscribeUniformEnabled()) {
914 gpu::ValueState state;
915 state.int_value[0] = mouse_event.x;
916 state.int_value[1] = mouse_event.y;
917 // TODO(orglofch) Separate the mapping of pending value states to the
918 // Gpu Service to be per RWH not per process
919 process_->SendUpdateValueState(GL_MOUSE_POSITION_CHROMIUM, state);
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::IsFullscreenGranted() const {
1324 return false;
1327 blink::WebDisplayMode RenderWidgetHostImpl::GetDisplayMode() const {
1328 return blink::WebDisplayModeBrowser;
1331 void RenderWidgetHostImpl::SetAutoResize(bool enable,
1332 const gfx::Size& min_size,
1333 const gfx::Size& max_size) {
1334 auto_resize_enabled_ = enable;
1335 min_size_for_auto_resize_ = min_size;
1336 max_size_for_auto_resize_ = max_size;
1339 void RenderWidgetHostImpl::Cleanup() {
1340 if (view_) {
1341 view_->Destroy();
1342 view_ = nullptr;
1346 void RenderWidgetHostImpl::Destroy() {
1347 NotificationService::current()->Notify(
1348 NOTIFICATION_RENDER_WIDGET_HOST_DESTROYED,
1349 Source<RenderWidgetHost>(this),
1350 NotificationService::NoDetails());
1352 // Tell the view to die.
1353 // Note that in the process of the view shutting down, it can call a ton
1354 // of other messages on us. So if you do any other deinitialization here,
1355 // do it after this call to view_->Destroy().
1356 if (view_) {
1357 view_->Destroy();
1358 view_ = nullptr;
1361 delete this;
1364 void RenderWidgetHostImpl::RendererIsUnresponsive() {
1365 NotificationService::current()->Notify(
1366 NOTIFICATION_RENDER_WIDGET_HOST_HANG,
1367 Source<RenderWidgetHost>(this),
1368 NotificationService::NoDetails());
1369 is_unresponsive_ = true;
1370 NotifyRendererUnresponsive();
1373 void RenderWidgetHostImpl::RendererIsResponsive() {
1374 if (is_unresponsive_) {
1375 is_unresponsive_ = false;
1376 NotifyRendererResponsive();
1380 void RenderWidgetHostImpl::OnRenderViewReady() {
1381 SendScreenRects();
1382 WasResized();
1385 void RenderWidgetHostImpl::OnRenderProcessGone(int status, int exit_code) {
1386 // RenderFrameHost owns a RenderWidgetHost when it needs one, in which case
1387 // it handles destruction.
1388 if (!owned_by_render_frame_host_) {
1389 // TODO(evanm): This synchronously ends up calling "delete this".
1390 // Is that really what we want in response to this message? I'm matching
1391 // previous behavior of the code here.
1392 Destroy();
1393 } else {
1394 RendererExited(static_cast<base::TerminationStatus>(status), exit_code);
1398 void RenderWidgetHostImpl::OnClose() {
1399 Shutdown();
1402 void RenderWidgetHostImpl::OnSetTooltipText(
1403 const base::string16& tooltip_text,
1404 WebTextDirection text_direction_hint) {
1405 // First, add directionality marks around tooltip text if necessary.
1406 // A naive solution would be to simply always wrap the text. However, on
1407 // windows, Unicode directional embedding characters can't be displayed on
1408 // systems that lack RTL fonts and are instead displayed as empty squares.
1410 // To get around this we only wrap the string when we deem it necessary i.e.
1411 // when the locale direction is different than the tooltip direction hint.
1413 // Currently, we use element's directionality as the tooltip direction hint.
1414 // An alternate solution would be to set the overall directionality based on
1415 // trying to detect the directionality from the tooltip text rather than the
1416 // element direction. One could argue that would be a preferable solution
1417 // but we use the current approach to match Fx & IE's behavior.
1418 base::string16 wrapped_tooltip_text = tooltip_text;
1419 if (!tooltip_text.empty()) {
1420 if (text_direction_hint == blink::WebTextDirectionLeftToRight) {
1421 // Force the tooltip to have LTR directionality.
1422 wrapped_tooltip_text =
1423 base::i18n::GetDisplayStringInLTRDirectionality(wrapped_tooltip_text);
1424 } else if (text_direction_hint == blink::WebTextDirectionRightToLeft &&
1425 !base::i18n::IsRTL()) {
1426 // Force the tooltip to have RTL directionality.
1427 base::i18n::WrapStringWithRTLFormatting(&wrapped_tooltip_text);
1430 if (GetView())
1431 view_->SetTooltipText(wrapped_tooltip_text);
1434 void RenderWidgetHostImpl::OnUpdateScreenRectsAck() {
1435 waiting_for_screen_rects_ack_ = false;
1436 if (!view_)
1437 return;
1439 if (view_->GetViewBounds() == last_view_screen_rect_ &&
1440 view_->GetBoundsInRootWindow() == last_window_screen_rect_) {
1441 return;
1444 SendScreenRects();
1447 void RenderWidgetHostImpl::OnRequestMove(const gfx::Rect& pos) {
1448 if (view_) {
1449 view_->SetBounds(pos);
1450 Send(new ViewMsg_Move_ACK(routing_id_));
1454 bool RenderWidgetHostImpl::OnSwapCompositorFrame(
1455 const IPC::Message& message) {
1456 // This trace event is used in
1457 // chrome/browser/extensions/api/cast_streaming/performance_test.cc
1458 TRACE_EVENT0("test_fps,benchmark", "OnSwapCompositorFrame");
1459 ViewHostMsg_SwapCompositorFrame::Param param;
1460 if (!ViewHostMsg_SwapCompositorFrame::Read(&message, &param))
1461 return false;
1462 scoped_ptr<cc::CompositorFrame> frame(new cc::CompositorFrame);
1463 uint32 output_surface_id = get<0>(param);
1464 get<1>(param).AssignTo(frame.get());
1465 std::vector<IPC::Message> messages_to_deliver_with_frame;
1466 messages_to_deliver_with_frame.swap(get<2>(param));
1468 latency_tracker_.OnSwapCompositorFrame(&frame->metadata.latency_info);
1470 input_router_->OnViewUpdated(
1471 GetInputRouterViewFlagsFromCompositorFrameMetadata(frame->metadata));
1473 if (touch_emulator_) {
1474 touch_emulator_->SetDoubleTapSupportForPageEnabled(
1475 !IsMobileOptimizedFrame(frame->metadata));
1478 if (view_) {
1479 view_->OnSwapCompositorFrame(output_surface_id, frame.Pass());
1480 view_->DidReceiveRendererFrame();
1481 } else {
1482 cc::CompositorFrameAck ack;
1483 if (frame->gl_frame_data) {
1484 ack.gl_frame_data = frame->gl_frame_data.Pass();
1485 ack.gl_frame_data->sync_point = 0;
1486 } else if (frame->delegated_frame_data) {
1487 cc::TransferableResource::ReturnResources(
1488 frame->delegated_frame_data->resource_list,
1489 &ack.resources);
1490 } else if (frame->software_frame_data) {
1491 ack.last_software_frame_id = frame->software_frame_data->id;
1493 SendSwapCompositorFrameAck(routing_id_, output_surface_id,
1494 process_->GetID(), ack);
1497 RenderProcessHost* rph = GetProcess();
1498 for (std::vector<IPC::Message>::const_iterator i =
1499 messages_to_deliver_with_frame.begin();
1500 i != messages_to_deliver_with_frame.end();
1501 ++i) {
1502 rph->OnMessageReceived(*i);
1503 if (i->dispatch_error())
1504 rph->OnBadMessageReceived(*i);
1506 messages_to_deliver_with_frame.clear();
1508 return true;
1511 void RenderWidgetHostImpl::OnUpdateRect(
1512 const ViewHostMsg_UpdateRect_Params& params) {
1513 TRACE_EVENT0("renderer_host", "RenderWidgetHostImpl::OnUpdateRect");
1514 TimeTicks paint_start = TimeTicks::Now();
1516 // Update our knowledge of the RenderWidget's size.
1517 current_size_ = params.view_size;
1519 bool is_resize_ack =
1520 ViewHostMsg_UpdateRect_Flags::is_resize_ack(params.flags);
1522 // resize_ack_pending_ needs to be cleared before we call DidPaintRect, since
1523 // that will end up reaching GetBackingStore.
1524 if (is_resize_ack) {
1525 DCHECK(!g_check_for_pending_resize_ack || resize_ack_pending_);
1526 resize_ack_pending_ = false;
1529 bool is_repaint_ack =
1530 ViewHostMsg_UpdateRect_Flags::is_repaint_ack(params.flags);
1531 if (is_repaint_ack) {
1532 DCHECK(repaint_ack_pending_);
1533 TRACE_EVENT_ASYNC_END0(
1534 "renderer_host", "RenderWidgetHostImpl::repaint_ack_pending_", this);
1535 repaint_ack_pending_ = false;
1536 TimeDelta delta = TimeTicks::Now() - repaint_start_time_;
1537 UMA_HISTOGRAM_TIMES("MPArch.RWH_RepaintDelta", delta);
1540 DCHECK(!params.view_size.IsEmpty());
1542 DidUpdateBackingStore(params, paint_start);
1544 if (auto_resize_enabled_) {
1545 bool post_callback = new_auto_size_.IsEmpty();
1546 new_auto_size_ = params.view_size;
1547 if (post_callback) {
1548 base::MessageLoop::current()->PostTask(
1549 FROM_HERE,
1550 base::Bind(&RenderWidgetHostImpl::DelayedAutoResized,
1551 weak_factory_.GetWeakPtr()));
1555 // Log the time delta for processing a paint message. On platforms that don't
1556 // support asynchronous painting, this is equivalent to
1557 // MPArch.RWH_TotalPaintTime.
1558 TimeDelta delta = TimeTicks::Now() - paint_start;
1559 UMA_HISTOGRAM_TIMES("MPArch.RWH_OnMsgUpdateRect", delta);
1562 void RenderWidgetHostImpl::DidUpdateBackingStore(
1563 const ViewHostMsg_UpdateRect_Params& params,
1564 const TimeTicks& paint_start) {
1565 TRACE_EVENT0("renderer_host", "RenderWidgetHostImpl::DidUpdateBackingStore");
1566 TimeTicks update_start = TimeTicks::Now();
1568 // Move the plugins if the view hasn't already been destroyed. Plugin moves
1569 // will not be re-issued, so must move them now, regardless of whether we
1570 // paint or not. MovePluginWindows attempts to move the plugin windows and
1571 // in the process could dispatch other window messages which could cause the
1572 // view to be destroyed.
1573 if (view_)
1574 view_->MovePluginWindows(params.plugin_window_moves);
1576 NotificationService::current()->Notify(
1577 NOTIFICATION_RENDER_WIDGET_HOST_DID_UPDATE_BACKING_STORE,
1578 Source<RenderWidgetHost>(this),
1579 NotificationService::NoDetails());
1581 // We don't need to update the view if the view is hidden. We must do this
1582 // early return after the ACK is sent, however, or the renderer will not send
1583 // us more data.
1584 if (is_hidden_)
1585 return;
1587 // If we got a resize ack, then perhaps we have another resize to send?
1588 bool is_resize_ack =
1589 ViewHostMsg_UpdateRect_Flags::is_resize_ack(params.flags);
1590 if (is_resize_ack)
1591 WasResized();
1593 // Log the time delta for processing a paint message.
1594 TimeTicks now = TimeTicks::Now();
1595 TimeDelta delta = now - update_start;
1596 UMA_HISTOGRAM_TIMES("MPArch.RWH_DidUpdateBackingStore", delta);
1599 void RenderWidgetHostImpl::OnQueueSyntheticGesture(
1600 const SyntheticGesturePacket& gesture_packet) {
1601 // Only allow untrustworthy gestures if explicitly enabled.
1602 if (!base::CommandLine::ForCurrentProcess()->HasSwitch(
1603 cc::switches::kEnableGpuBenchmarking)) {
1604 bad_message::ReceivedBadMessage(GetProcess(),
1605 bad_message::RWH_SYNTHETIC_GESTURE);
1606 return;
1609 QueueSyntheticGesture(
1610 SyntheticGesture::Create(*gesture_packet.gesture_params()),
1611 base::Bind(&RenderWidgetHostImpl::OnSyntheticGestureCompleted,
1612 weak_factory_.GetWeakPtr()));
1615 void RenderWidgetHostImpl::OnFocus() {
1616 // Only RenderViewHost can deal with that message.
1617 bad_message::ReceivedBadMessage(GetProcess(), bad_message::RWH_FOCUS);
1620 void RenderWidgetHostImpl::OnBlur() {
1621 // Only RenderViewHost can deal with that message.
1622 bad_message::ReceivedBadMessage(GetProcess(), bad_message::RWH_BLUR);
1625 void RenderWidgetHostImpl::OnSetCursor(const WebCursor& cursor) {
1626 SetCursor(cursor);
1629 void RenderWidgetHostImpl::SetTouchEventEmulationEnabled(
1630 bool enabled, ui::GestureProviderConfigType config_type) {
1631 if (enabled) {
1632 if (!touch_emulator_)
1633 touch_emulator_.reset(new TouchEmulator(this));
1634 touch_emulator_->Enable(config_type);
1635 } else {
1636 if (touch_emulator_)
1637 touch_emulator_->Disable();
1641 void RenderWidgetHostImpl::OnTextInputTypeChanged(
1642 ui::TextInputType type,
1643 ui::TextInputMode input_mode,
1644 bool can_compose_inline,
1645 int flags) {
1646 if (view_)
1647 view_->TextInputTypeChanged(type, input_mode, can_compose_inline, flags);
1650 void RenderWidgetHostImpl::OnImeCompositionRangeChanged(
1651 const gfx::Range& range,
1652 const std::vector<gfx::Rect>& character_bounds) {
1653 if (view_)
1654 view_->ImeCompositionRangeChanged(range, character_bounds);
1657 void RenderWidgetHostImpl::OnImeCancelComposition() {
1658 if (view_)
1659 view_->ImeCancelComposition();
1662 void RenderWidgetHostImpl::OnLockMouse(bool user_gesture,
1663 bool last_unlocked_by_target,
1664 bool privileged) {
1666 if (pending_mouse_lock_request_) {
1667 Send(new ViewMsg_LockMouse_ACK(routing_id_, false));
1668 return;
1669 } else if (IsMouseLocked()) {
1670 Send(new ViewMsg_LockMouse_ACK(routing_id_, true));
1671 return;
1674 pending_mouse_lock_request_ = true;
1675 if (privileged && allow_privileged_mouse_lock_) {
1676 // Directly approve to lock the mouse.
1677 GotResponseToLockMouseRequest(true);
1678 } else {
1679 RequestToLockMouse(user_gesture, last_unlocked_by_target);
1683 void RenderWidgetHostImpl::OnUnlockMouse() {
1684 RejectMouseLockOrUnlockIfNecessary();
1687 void RenderWidgetHostImpl::OnShowDisambiguationPopup(
1688 const gfx::Rect& rect_pixels,
1689 const gfx::Size& size,
1690 const cc::SharedBitmapId& id) {
1691 DCHECK(!rect_pixels.IsEmpty());
1692 DCHECK(!size.IsEmpty());
1694 scoped_ptr<cc::SharedBitmap> bitmap =
1695 HostSharedBitmapManager::current()->GetSharedBitmapFromId(size, id);
1696 if (!bitmap) {
1697 bad_message::ReceivedBadMessage(GetProcess(),
1698 bad_message::RWH_SHARED_BITMAP);
1699 return;
1702 DCHECK(bitmap->pixels());
1704 SkImageInfo info = SkImageInfo::MakeN32Premul(size.width(), size.height());
1705 SkBitmap zoomed_bitmap;
1706 zoomed_bitmap.installPixels(info, bitmap->pixels(), info.minRowBytes());
1708 // Note that |rect| is in coordinates of pixels relative to the window origin.
1709 // Aura-based systems will want to convert this to DIPs.
1710 if (view_)
1711 view_->ShowDisambiguationPopup(rect_pixels, zoomed_bitmap);
1713 // It is assumed that the disambiguation popup will make a copy of the
1714 // provided zoomed image, so we delete this one.
1715 zoomed_bitmap.setPixels(0);
1716 Send(new ViewMsg_ReleaseDisambiguationPopupBitmap(GetRoutingID(), id));
1719 #if defined(OS_WIN)
1720 void RenderWidgetHostImpl::OnWindowlessPluginDummyWindowCreated(
1721 gfx::NativeViewId dummy_activation_window) {
1722 HWND hwnd = reinterpret_cast<HWND>(dummy_activation_window);
1724 // This may happen as a result of a race condition when the plugin is going
1725 // away.
1726 wchar_t window_title[MAX_PATH + 1] = {0};
1727 if (!IsWindow(hwnd) ||
1728 !GetWindowText(hwnd, window_title, arraysize(window_title)) ||
1729 lstrcmpiW(window_title, kDummyActivationWindowName) != 0) {
1730 return;
1733 #if defined(USE_AURA)
1734 SetParent(hwnd,
1735 reinterpret_cast<HWND>(view_->GetParentForWindowlessPlugin()));
1736 #else
1737 SetParent(hwnd, reinterpret_cast<HWND>(GetNativeViewId()));
1738 #endif
1739 dummy_windows_for_activation_.push_back(hwnd);
1742 void RenderWidgetHostImpl::OnWindowlessPluginDummyWindowDestroyed(
1743 gfx::NativeViewId dummy_activation_window) {
1744 HWND hwnd = reinterpret_cast<HWND>(dummy_activation_window);
1745 std::list<HWND>::iterator i = dummy_windows_for_activation_.begin();
1746 for (; i != dummy_windows_for_activation_.end(); ++i) {
1747 if ((*i) == hwnd) {
1748 dummy_windows_for_activation_.erase(i);
1749 return;
1752 NOTREACHED() << "Unknown dummy window";
1754 #endif
1756 void RenderWidgetHostImpl::SetIgnoreInputEvents(bool ignore_input_events) {
1757 ignore_input_events_ = ignore_input_events;
1760 bool RenderWidgetHostImpl::KeyPressListenersHandleEvent(
1761 const NativeWebKeyboardEvent& event) {
1762 if (event.skip_in_browser || event.type != WebKeyboardEvent::RawKeyDown)
1763 return false;
1765 for (size_t i = 0; i < key_press_event_callbacks_.size(); i++) {
1766 size_t original_size = key_press_event_callbacks_.size();
1767 if (key_press_event_callbacks_[i].Run(event))
1768 return true;
1770 // Check whether the callback that just ran removed itself, in which case
1771 // the iterator needs to be decremented to properly account for the removal.
1772 size_t current_size = key_press_event_callbacks_.size();
1773 if (current_size != original_size) {
1774 DCHECK_EQ(original_size - 1, current_size);
1775 --i;
1779 return false;
1782 InputEventAckState RenderWidgetHostImpl::FilterInputEvent(
1783 const blink::WebInputEvent& event, const ui::LatencyInfo& latency_info) {
1784 // Don't ignore touch cancel events, since they may be sent while input
1785 // events are being ignored in order to keep the renderer from getting
1786 // confused about how many touches are active.
1787 if (IgnoreInputEvents() && event.type != WebInputEvent::TouchCancel)
1788 return INPUT_EVENT_ACK_STATE_NO_CONSUMER_EXISTS;
1790 if (!process_->HasConnection())
1791 return INPUT_EVENT_ACK_STATE_UNKNOWN;
1793 if (event.type == WebInputEvent::MouseDown)
1794 OnUserGesture();
1796 return view_ ? view_->FilterInputEvent(event)
1797 : INPUT_EVENT_ACK_STATE_NOT_CONSUMED;
1800 void RenderWidgetHostImpl::IncrementInFlightEventCount() {
1801 increment_in_flight_event_count();
1802 if (!is_hidden_)
1803 StartHangMonitorTimeout(hung_renderer_delay_);
1806 void RenderWidgetHostImpl::DecrementInFlightEventCount() {
1807 if (decrement_in_flight_event_count() <= 0) {
1808 // Cancel pending hung renderer checks since the renderer is responsive.
1809 StopHangMonitorTimeout();
1810 } else {
1811 // The renderer is responsive, but there are in-flight events to wait for.
1812 if (!is_hidden_)
1813 RestartHangMonitorTimeout();
1817 void RenderWidgetHostImpl::OnHasTouchEventHandlers(bool has_handlers) {
1818 has_touch_handler_ = has_handlers;
1821 void RenderWidgetHostImpl::DidFlush() {
1822 if (synthetic_gesture_controller_)
1823 synthetic_gesture_controller_->OnDidFlushInput();
1826 void RenderWidgetHostImpl::DidOverscroll(const DidOverscrollParams& params) {
1827 if (view_)
1828 view_->DidOverscroll(params);
1831 void RenderWidgetHostImpl::DidStopFlinging() {
1832 if (view_)
1833 view_->DidStopFlinging();
1836 void RenderWidgetHostImpl::OnKeyboardEventAck(
1837 const NativeWebKeyboardEvent& event,
1838 InputEventAckState ack_result) {
1839 #if defined(OS_MACOSX)
1840 if (!is_hidden() && view_ && view_->PostProcessEventForPluginIme(event))
1841 return;
1842 #endif
1844 // We only send unprocessed key event upwards if we are not hidden,
1845 // because the user has moved away from us and no longer expect any effect
1846 // of this key event.
1847 const bool processed = (INPUT_EVENT_ACK_STATE_CONSUMED == ack_result);
1848 if (delegate_ && !processed && !is_hidden() && !event.skip_in_browser) {
1849 delegate_->HandleKeyboardEvent(event);
1851 // WARNING: This RenderWidgetHostImpl can be deallocated at this point
1852 // (i.e. in the case of Ctrl+W, where the call to
1853 // HandleKeyboardEvent destroys this RenderWidgetHostImpl).
1857 void RenderWidgetHostImpl::OnWheelEventAck(
1858 const MouseWheelEventWithLatencyInfo& wheel_event,
1859 InputEventAckState ack_result) {
1860 latency_tracker_.OnInputEventAck(wheel_event.event, &wheel_event.latency);
1862 if (!is_hidden() && view_) {
1863 if (ack_result != INPUT_EVENT_ACK_STATE_CONSUMED &&
1864 delegate_->HandleWheelEvent(wheel_event.event)) {
1865 ack_result = INPUT_EVENT_ACK_STATE_CONSUMED;
1867 view_->WheelEventAck(wheel_event.event, ack_result);
1871 void RenderWidgetHostImpl::OnGestureEventAck(
1872 const GestureEventWithLatencyInfo& event,
1873 InputEventAckState ack_result) {
1874 latency_tracker_.OnInputEventAck(event.event, &event.latency);
1876 if (view_)
1877 view_->GestureEventAck(event.event, ack_result);
1880 void RenderWidgetHostImpl::OnTouchEventAck(
1881 const TouchEventWithLatencyInfo& event,
1882 InputEventAckState ack_result) {
1883 latency_tracker_.OnInputEventAck(event.event, &event.latency);
1885 if (touch_emulator_ &&
1886 touch_emulator_->HandleTouchEventAck(event.event, ack_result)) {
1887 return;
1890 if (view_)
1891 view_->ProcessAckedTouchEvent(event, ack_result);
1894 void RenderWidgetHostImpl::OnUnexpectedEventAck(UnexpectedEventAckType type) {
1895 if (type == BAD_ACK_MESSAGE) {
1896 bad_message::ReceivedBadMessage(process_, bad_message::RWH_BAD_ACK_MESSAGE);
1897 } else if (type == UNEXPECTED_EVENT_TYPE) {
1898 suppress_next_char_events_ = false;
1902 void RenderWidgetHostImpl::OnSyntheticGestureCompleted(
1903 SyntheticGesture::Result result) {
1904 Send(new InputMsg_SyntheticGestureCompleted(GetRoutingID()));
1907 bool RenderWidgetHostImpl::IgnoreInputEvents() const {
1908 return ignore_input_events_ || process_->IgnoreInputEvents();
1911 void RenderWidgetHostImpl::StartUserGesture() {
1912 OnUserGesture();
1915 void RenderWidgetHostImpl::SetBackgroundOpaque(bool opaque) {
1916 Send(new ViewMsg_SetBackgroundOpaque(GetRoutingID(), opaque));
1919 void RenderWidgetHostImpl::SetEditCommandsForNextKeyEvent(
1920 const std::vector<EditCommand>& commands) {
1921 Send(new InputMsg_SetEditCommandsForNextKeyEvent(GetRoutingID(), commands));
1924 void RenderWidgetHostImpl::ExecuteEditCommand(const std::string& command,
1925 const std::string& value) {
1926 Send(new InputMsg_ExecuteEditCommand(GetRoutingID(), command, value));
1929 void RenderWidgetHostImpl::ScrollFocusedEditableNodeIntoRect(
1930 const gfx::Rect& rect) {
1931 Send(new InputMsg_ScrollFocusedEditableNodeIntoRect(GetRoutingID(), rect));
1934 void RenderWidgetHostImpl::MoveCaret(const gfx::Point& point) {
1935 Send(new InputMsg_MoveCaret(GetRoutingID(), point));
1938 bool RenderWidgetHostImpl::GotResponseToLockMouseRequest(bool allowed) {
1939 if (!allowed) {
1940 RejectMouseLockOrUnlockIfNecessary();
1941 return false;
1942 } else {
1943 if (!pending_mouse_lock_request_) {
1944 // This is possible, e.g., the plugin sends us an unlock request before
1945 // the user allows to lock to mouse.
1946 return false;
1949 pending_mouse_lock_request_ = false;
1950 if (!view_ || !view_->HasFocus()|| !view_->LockMouse()) {
1951 Send(new ViewMsg_LockMouse_ACK(routing_id_, false));
1952 return false;
1953 } else {
1954 Send(new ViewMsg_LockMouse_ACK(routing_id_, true));
1955 return true;
1960 // static
1961 void RenderWidgetHostImpl::SendSwapCompositorFrameAck(
1962 int32 route_id,
1963 uint32 output_surface_id,
1964 int renderer_host_id,
1965 const cc::CompositorFrameAck& ack) {
1966 RenderProcessHost* host = RenderProcessHost::FromID(renderer_host_id);
1967 if (!host)
1968 return;
1969 host->Send(new ViewMsg_SwapCompositorFrameAck(
1970 route_id, output_surface_id, ack));
1973 // static
1974 void RenderWidgetHostImpl::SendReclaimCompositorResources(
1975 int32 route_id,
1976 uint32 output_surface_id,
1977 int renderer_host_id,
1978 const cc::CompositorFrameAck& ack) {
1979 RenderProcessHost* host = RenderProcessHost::FromID(renderer_host_id);
1980 if (!host)
1981 return;
1982 host->Send(
1983 new ViewMsg_ReclaimCompositorResources(route_id, output_surface_id, ack));
1986 void RenderWidgetHostImpl::DelayedAutoResized() {
1987 gfx::Size new_size = new_auto_size_;
1988 // Clear the new_auto_size_ since the empty value is used as a flag to
1989 // indicate that no callback is in progress (i.e. without this line
1990 // DelayedAutoResized will not get called again).
1991 new_auto_size_.SetSize(0, 0);
1992 if (!auto_resize_enabled_)
1993 return;
1995 OnRenderAutoResized(new_size);
1998 void RenderWidgetHostImpl::DetachDelegate() {
1999 delegate_ = NULL;
2002 void RenderWidgetHostImpl::FrameSwapped(const ui::LatencyInfo& latency_info) {
2003 ui::LatencyInfo::LatencyComponent window_snapshot_component;
2004 if (latency_info.FindLatency(ui::WINDOW_SNAPSHOT_FRAME_NUMBER_COMPONENT,
2005 GetLatencyComponentId(),
2006 &window_snapshot_component)) {
2007 int sequence_number = static_cast<int>(
2008 window_snapshot_component.sequence_number);
2009 #if defined(OS_MACOSX)
2010 // On Mac, when using CoreAnmation, there is a delay between when content
2011 // is drawn to the screen, and when the snapshot will actually pick up
2012 // that content. Insert a manual delay of 1/6th of a second (to simulate
2013 // 10 frames at 60 fps) before actually taking the snapshot.
2014 base::MessageLoop::current()->PostDelayedTask(
2015 FROM_HERE,
2016 base::Bind(&RenderWidgetHostImpl::WindowSnapshotReachedScreen,
2017 weak_factory_.GetWeakPtr(),
2018 sequence_number),
2019 base::TimeDelta::FromSecondsD(1. / 6));
2020 #else
2021 WindowSnapshotReachedScreen(sequence_number);
2022 #endif
2025 latency_tracker_.OnFrameSwapped(latency_info);
2028 void RenderWidgetHostImpl::DidReceiveRendererFrame() {
2029 view_->DidReceiveRendererFrame();
2032 void RenderWidgetHostImpl::WindowSnapshotReachedScreen(int snapshot_id) {
2033 DCHECK(base::MessageLoopForUI::IsCurrent());
2035 gfx::Rect view_bounds = GetView()->GetViewBounds();
2036 gfx::Rect snapshot_bounds(view_bounds.size());
2038 std::vector<unsigned char> png;
2039 if (ui::GrabViewSnapshot(
2040 GetView()->GetNativeView(), &png, snapshot_bounds)) {
2041 OnSnapshotDataReceived(snapshot_id, &png.front(), png.size());
2042 return;
2045 ui::GrabViewSnapshotAsync(
2046 GetView()->GetNativeView(),
2047 snapshot_bounds,
2048 base::ThreadTaskRunnerHandle::Get(),
2049 base::Bind(&RenderWidgetHostImpl::OnSnapshotDataReceivedAsync,
2050 weak_factory_.GetWeakPtr(),
2051 snapshot_id));
2054 void RenderWidgetHostImpl::OnSnapshotDataReceived(int snapshot_id,
2055 const unsigned char* data,
2056 size_t size) {
2057 // Any pending snapshots with a lower ID than the one received are considered
2058 // to be implicitly complete, and returned the same snapshot data.
2059 PendingSnapshotMap::iterator it = pending_browser_snapshots_.begin();
2060 while(it != pending_browser_snapshots_.end()) {
2061 if (it->first <= snapshot_id) {
2062 it->second.Run(data, size);
2063 pending_browser_snapshots_.erase(it++);
2064 } else {
2065 ++it;
2070 void RenderWidgetHostImpl::OnSnapshotDataReceivedAsync(
2071 int snapshot_id,
2072 scoped_refptr<base::RefCountedBytes> png_data) {
2073 if (png_data.get())
2074 OnSnapshotDataReceived(snapshot_id, png_data->front(), png_data->size());
2075 else
2076 OnSnapshotDataReceived(snapshot_id, NULL, 0);
2079 // static
2080 void RenderWidgetHostImpl::CompositorFrameDrawn(
2081 const std::vector<ui::LatencyInfo>& latency_info) {
2082 for (size_t i = 0; i < latency_info.size(); i++) {
2083 std::set<RenderWidgetHostImpl*> rwhi_set;
2084 for (ui::LatencyInfo::LatencyMap::const_iterator b =
2085 latency_info[i].latency_components.begin();
2086 b != latency_info[i].latency_components.end();
2087 ++b) {
2088 if (b->first.first == ui::INPUT_EVENT_LATENCY_BEGIN_RWH_COMPONENT ||
2089 b->first.first == ui::WINDOW_SNAPSHOT_FRAME_NUMBER_COMPONENT ||
2090 b->first.first == ui::TAB_SHOW_COMPONENT) {
2091 // Matches with GetLatencyComponentId
2092 int routing_id = b->first.second & 0xffffffff;
2093 int process_id = (b->first.second >> 32) & 0xffffffff;
2094 RenderWidgetHost* rwh =
2095 RenderWidgetHost::FromID(process_id, routing_id);
2096 if (!rwh) {
2097 continue;
2099 RenderWidgetHostImpl* rwhi = RenderWidgetHostImpl::From(rwh);
2100 if (rwhi_set.insert(rwhi).second)
2101 rwhi->FrameSwapped(latency_info[i]);
2107 BrowserAccessibilityManager*
2108 RenderWidgetHostImpl::GetRootBrowserAccessibilityManager() {
2109 return delegate_ ? delegate_->GetRootBrowserAccessibilityManager() : NULL;
2112 BrowserAccessibilityManager*
2113 RenderWidgetHostImpl::GetOrCreateRootBrowserAccessibilityManager() {
2114 return delegate_ ?
2115 delegate_->GetOrCreateRootBrowserAccessibilityManager() : NULL;
2118 base::TimeDelta RenderWidgetHostImpl::GetEstimatedBrowserCompositeTime() const {
2119 return latency_tracker_.GetEstimatedBrowserCompositeTime();
2122 #if defined(OS_WIN)
2123 gfx::NativeViewAccessible
2124 RenderWidgetHostImpl::GetParentNativeViewAccessible() {
2125 return delegate_ ? delegate_->GetParentNativeViewAccessible() : NULL;
2127 #endif
2129 SkColorType RenderWidgetHostImpl::PreferredReadbackFormat() {
2130 if (view_)
2131 return view_->PreferredReadbackFormat();
2132 return kN32_SkColorType;
2135 } // namespace content