Cleanup: Update the path to gfx size headers.
[chromium-blink-merge.git] / content / browser / renderer_host / render_widget_host_impl.cc
blobc02b51aeef383a7dec78d64262fea8961339d576
1 // Copyright (c) 2012 The Chromium Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
5 #include "content/browser/renderer_host/render_widget_host_impl.h"
7 #include <math.h>
8 #include <set>
9 #include <utility>
11 #include "base/auto_reset.h"
12 #include "base/bind.h"
13 #include "base/command_line.h"
14 #include "base/containers/hash_tables.h"
15 #include "base/debug/trace_event.h"
16 #include "base/i18n/rtl.h"
17 #include "base/lazy_instance.h"
18 #include "base/message_loop/message_loop.h"
19 #include "base/metrics/field_trial.h"
20 #include "base/metrics/histogram.h"
21 #include "base/strings/string_number_conversions.h"
22 #include "base/strings/utf_string_conversions.h"
23 #include "base/thread_task_runner_handle.h"
24 #include "cc/base/switches.h"
25 #include "cc/output/compositor_frame.h"
26 #include "cc/output/compositor_frame_ack.h"
27 #include "content/browser/accessibility/accessibility_mode_helper.h"
28 #include "content/browser/accessibility/browser_accessibility_state_impl.h"
29 #include "content/browser/browser_plugin/browser_plugin_guest.h"
30 #include "content/browser/gpu/compositor_util.h"
31 #include "content/browser/gpu/gpu_process_host.h"
32 #include "content/browser/gpu/gpu_process_host_ui_shim.h"
33 #include "content/browser/gpu/gpu_surface_tracker.h"
34 #include "content/browser/renderer_host/dip_util.h"
35 #include "content/browser/renderer_host/input/input_router_config_helper.h"
36 #include "content/browser/renderer_host/input/input_router_impl.h"
37 #include "content/browser/renderer_host/input/synthetic_gesture.h"
38 #include "content/browser/renderer_host/input/synthetic_gesture_controller.h"
39 #include "content/browser/renderer_host/input/synthetic_gesture_target.h"
40 #include "content/browser/renderer_host/input/timeout_monitor.h"
41 #include "content/browser/renderer_host/input/touch_emulator.h"
42 #include "content/browser/renderer_host/render_process_host_impl.h"
43 #include "content/browser/renderer_host/render_view_host_impl.h"
44 #include "content/browser/renderer_host/render_widget_helper.h"
45 #include "content/browser/renderer_host/render_widget_host_delegate.h"
46 #include "content/browser/renderer_host/render_widget_host_view_base.h"
47 #include "content/browser/renderer_host/render_widget_resize_helper.h"
48 #include "content/common/content_constants_internal.h"
49 #include "content/common/cursors/webcursor.h"
50 #include "content/common/gpu/gpu_messages.h"
51 #include "content/common/host_shared_bitmap_manager.h"
52 #include "content/common/input_messages.h"
53 #include "content/common/view_messages.h"
54 #include "content/public/browser/native_web_keyboard_event.h"
55 #include "content/public/browser/notification_service.h"
56 #include "content/public/browser/notification_types.h"
57 #include "content/public/browser/render_widget_host_iterator.h"
58 #include "content/public/browser/user_metrics.h"
59 #include "content/public/common/content_constants.h"
60 #include "content/public/common/content_switches.h"
61 #include "content/public/common/result_codes.h"
62 #include "content/public/common/web_preferences.h"
63 #include "gpu/GLES2/gl2extchromium.h"
64 #include "gpu/command_buffer/service/gpu_switches.h"
65 #include "skia/ext/image_operations.h"
66 #include "skia/ext/platform_canvas.h"
67 #include "third_party/WebKit/public/web/WebCompositionUnderline.h"
68 #include "ui/events/event.h"
69 #include "ui/events/keycodes/keyboard_codes.h"
70 #include "ui/gfx/geometry/size_conversions.h"
71 #include "ui/gfx/geometry/vector2d_conversions.h"
72 #include "ui/gfx/skbitmap_operations.h"
73 #include "ui/snapshot/snapshot.h"
75 #if defined(OS_WIN)
76 #include "content/common/plugin_constants_win.h"
77 #endif
79 using base::Time;
80 using base::TimeDelta;
81 using base::TimeTicks;
82 using blink::WebGestureEvent;
83 using blink::WebInputEvent;
84 using blink::WebKeyboardEvent;
85 using blink::WebMouseEvent;
86 using blink::WebMouseWheelEvent;
87 using blink::WebTextDirection;
89 namespace content {
90 namespace {
92 bool g_check_for_pending_resize_ack = true;
94 typedef std::pair<int32, int32> RenderWidgetHostID;
95 typedef base::hash_map<RenderWidgetHostID, RenderWidgetHostImpl*>
96 RoutingIDWidgetMap;
97 base::LazyInstance<RoutingIDWidgetMap> g_routing_id_widget_map =
98 LAZY_INSTANCE_INITIALIZER;
100 int GetInputRouterViewFlagsFromCompositorFrameMetadata(
101 const cc::CompositorFrameMetadata metadata) {
102 int view_flags = InputRouter::VIEW_FLAGS_NONE;
104 if (metadata.min_page_scale_factor == metadata.max_page_scale_factor)
105 view_flags |= InputRouter::FIXED_PAGE_SCALE;
107 const float window_width_dip = std::ceil(
108 metadata.page_scale_factor * metadata.scrollable_viewport_size.width());
109 const float content_width_css = metadata.root_layer_size.width();
110 if (content_width_css <= window_width_dip)
111 view_flags |= InputRouter::MOBILE_VIEWPORT;
113 return view_flags;
116 // Implements the RenderWidgetHostIterator interface. It keeps a list of
117 // RenderWidgetHosts, and makes sure it returns a live RenderWidgetHost at each
118 // iteration (or NULL if there isn't any left).
119 class RenderWidgetHostIteratorImpl : public RenderWidgetHostIterator {
120 public:
121 RenderWidgetHostIteratorImpl()
122 : current_index_(0) {
125 ~RenderWidgetHostIteratorImpl() override {}
127 void Add(RenderWidgetHost* host) {
128 hosts_.push_back(RenderWidgetHostID(host->GetProcess()->GetID(),
129 host->GetRoutingID()));
132 // RenderWidgetHostIterator:
133 RenderWidgetHost* GetNextHost() override {
134 RenderWidgetHost* host = NULL;
135 while (current_index_ < hosts_.size() && !host) {
136 RenderWidgetHostID id = hosts_[current_index_];
137 host = RenderWidgetHost::FromID(id.first, id.second);
138 ++current_index_;
140 return host;
143 private:
144 std::vector<RenderWidgetHostID> hosts_;
145 size_t current_index_;
147 DISALLOW_COPY_AND_ASSIGN(RenderWidgetHostIteratorImpl);
150 } // namespace
152 ///////////////////////////////////////////////////////////////////////////////
153 // RenderWidgetHostImpl
155 RenderWidgetHostImpl::RenderWidgetHostImpl(RenderWidgetHostDelegate* delegate,
156 RenderProcessHost* process,
157 int routing_id,
158 bool hidden)
159 : view_(NULL),
160 renderer_initialized_(false),
161 hung_renderer_delay_ms_(kHungRendererDelayMs),
162 delegate_(delegate),
163 process_(process),
164 routing_id_(routing_id),
165 surface_id_(0),
166 is_loading_(false),
167 is_hidden_(hidden),
168 repaint_ack_pending_(false),
169 resize_ack_pending_(false),
170 screen_info_out_of_date_(false),
171 auto_resize_enabled_(false),
172 waiting_for_screen_rects_ack_(false),
173 needs_repainting_on_restore_(false),
174 is_unresponsive_(false),
175 in_flight_event_count_(0),
176 in_get_backing_store_(false),
177 ignore_input_events_(false),
178 input_method_active_(false),
179 text_direction_updated_(false),
180 text_direction_(blink::WebTextDirectionLeftToRight),
181 text_direction_canceled_(false),
182 suppress_next_char_events_(false),
183 pending_mouse_lock_request_(false),
184 allow_privileged_mouse_lock_(false),
185 has_touch_handler_(false),
186 next_browser_snapshot_id_(1),
187 weak_factory_(this) {
188 CHECK(delegate_);
189 if (routing_id_ == MSG_ROUTING_NONE) {
190 routing_id_ = process_->GetNextRoutingID();
191 surface_id_ = GpuSurfaceTracker::Get()->AddSurfaceForRenderer(
192 process_->GetID(),
193 routing_id_);
194 } else {
195 // TODO(piman): This is a O(N) lookup, where we could forward the
196 // information from the RenderWidgetHelper. The problem is that doing so
197 // currently leaks outside of content all the way to chrome classes, and
198 // would be a layering violation. Since we don't expect more than a few
199 // hundreds of RWH, this seems acceptable. Revisit if performance become a
200 // problem, for example by tracking in the RenderWidgetHelper the routing id
201 // (and surface id) that have been created, but whose RWH haven't yet.
202 surface_id_ = GpuSurfaceTracker::Get()->LookupSurfaceForRenderer(
203 process_->GetID(),
204 routing_id_);
205 DCHECK(surface_id_);
208 std::pair<RoutingIDWidgetMap::iterator, bool> result =
209 g_routing_id_widget_map.Get().insert(std::make_pair(
210 RenderWidgetHostID(process->GetID(), routing_id_), this));
211 CHECK(result.second) << "Inserting a duplicate item!";
212 process_->AddRoute(routing_id_, this);
214 // If we're initially visible, tell the process host that we're alive.
215 // Otherwise we'll notify the process host when we are first shown.
216 if (!hidden)
217 process_->WidgetRestored();
219 latency_tracker_.Initialize(routing_id_, GetProcess()->GetID());
221 input_router_.reset(new InputRouterImpl(
222 process_, this, this, routing_id_, GetInputRouterConfigForPlatform()));
224 touch_emulator_.reset();
226 RenderViewHostImpl* rvh = static_cast<RenderViewHostImpl*>(
227 IsRenderView() ? RenderViewHost::From(this) : NULL);
228 if (BrowserPluginGuest::IsGuest(rvh) ||
229 !base::CommandLine::ForCurrentProcess()->HasSwitch(
230 switches::kDisableHangMonitor)) {
231 hang_monitor_timeout_.reset(new TimeoutMonitor(
232 base::Bind(&RenderWidgetHostImpl::RendererIsUnresponsive,
233 weak_factory_.GetWeakPtr())));
237 RenderWidgetHostImpl::~RenderWidgetHostImpl() {
238 if (view_weak_)
239 view_weak_->RenderWidgetHostGone();
240 SetView(NULL);
242 GpuSurfaceTracker::Get()->RemoveSurface(surface_id_);
243 surface_id_ = 0;
245 process_->RemoveRoute(routing_id_);
246 g_routing_id_widget_map.Get().erase(
247 RenderWidgetHostID(process_->GetID(), routing_id_));
249 if (delegate_)
250 delegate_->RenderWidgetDeleted(this);
253 // static
254 RenderWidgetHost* RenderWidgetHost::FromID(
255 int32 process_id,
256 int32 routing_id) {
257 return RenderWidgetHostImpl::FromID(process_id, routing_id);
260 // static
261 RenderWidgetHostImpl* RenderWidgetHostImpl::FromID(
262 int32 process_id,
263 int32 routing_id) {
264 DCHECK_CURRENTLY_ON(BrowserThread::UI);
265 RoutingIDWidgetMap* widgets = g_routing_id_widget_map.Pointer();
266 RoutingIDWidgetMap::iterator it = widgets->find(
267 RenderWidgetHostID(process_id, routing_id));
268 return it == widgets->end() ? NULL : it->second;
271 // static
272 scoped_ptr<RenderWidgetHostIterator> RenderWidgetHost::GetRenderWidgetHosts() {
273 RenderWidgetHostIteratorImpl* hosts = new RenderWidgetHostIteratorImpl();
274 RoutingIDWidgetMap* widgets = g_routing_id_widget_map.Pointer();
275 for (RoutingIDWidgetMap::const_iterator it = widgets->begin();
276 it != widgets->end();
277 ++it) {
278 RenderWidgetHost* widget = it->second;
280 if (!widget->IsRenderView()) {
281 hosts->Add(widget);
282 continue;
285 // Add only active RenderViewHosts.
286 RenderViewHost* rvh = RenderViewHost::From(widget);
287 if (static_cast<RenderViewHostImpl*>(rvh)->is_active())
288 hosts->Add(widget);
291 return scoped_ptr<RenderWidgetHostIterator>(hosts);
294 // static
295 scoped_ptr<RenderWidgetHostIterator>
296 RenderWidgetHostImpl::GetAllRenderWidgetHosts() {
297 RenderWidgetHostIteratorImpl* hosts = new RenderWidgetHostIteratorImpl();
298 RoutingIDWidgetMap* widgets = g_routing_id_widget_map.Pointer();
299 for (RoutingIDWidgetMap::const_iterator it = widgets->begin();
300 it != widgets->end();
301 ++it) {
302 hosts->Add(it->second);
305 return scoped_ptr<RenderWidgetHostIterator>(hosts);
308 // static
309 RenderWidgetHostImpl* RenderWidgetHostImpl::From(RenderWidgetHost* rwh) {
310 return rwh->AsRenderWidgetHostImpl();
313 void RenderWidgetHostImpl::SetView(RenderWidgetHostViewBase* view) {
314 if (view)
315 view_weak_ = view->GetWeakPtr();
316 else
317 view_weak_.reset();
318 view_ = view;
320 GpuSurfaceTracker::Get()->SetSurfaceHandle(
321 surface_id_, GetCompositingSurface());
323 synthetic_gesture_controller_.reset();
326 RenderProcessHost* RenderWidgetHostImpl::GetProcess() const {
327 return process_;
330 int RenderWidgetHostImpl::GetRoutingID() const {
331 return routing_id_;
334 RenderWidgetHostView* RenderWidgetHostImpl::GetView() const {
335 return view_;
338 RenderWidgetHostImpl* RenderWidgetHostImpl::AsRenderWidgetHostImpl() {
339 return this;
342 gfx::NativeViewId RenderWidgetHostImpl::GetNativeViewId() const {
343 if (view_)
344 return view_->GetNativeViewId();
345 return 0;
348 gfx::GLSurfaceHandle RenderWidgetHostImpl::GetCompositingSurface() {
349 if (view_)
350 return view_->GetCompositingSurface();
351 return gfx::GLSurfaceHandle();
354 void RenderWidgetHostImpl::ResetSizeAndRepaintPendingFlags() {
355 resize_ack_pending_ = false;
356 if (repaint_ack_pending_) {
357 TRACE_EVENT_ASYNC_END0(
358 "renderer_host", "RenderWidgetHostImpl::repaint_ack_pending_", this);
360 repaint_ack_pending_ = false;
361 if (old_resize_params_)
362 old_resize_params_->new_size = gfx::Size();
365 void RenderWidgetHostImpl::SendScreenRects() {
366 if (!renderer_initialized_ || waiting_for_screen_rects_ack_)
367 return;
369 if (is_hidden_) {
370 // On GTK, this comes in for backgrounded tabs. Ignore, to match what
371 // happens on Win & Mac, and when the view is shown it'll call this again.
372 return;
375 if (!view_)
376 return;
378 last_view_screen_rect_ = view_->GetViewBounds();
379 last_window_screen_rect_ = view_->GetBoundsInRootWindow();
380 Send(new ViewMsg_UpdateScreenRects(
381 GetRoutingID(), last_view_screen_rect_, last_window_screen_rect_));
382 if (delegate_)
383 delegate_->DidSendScreenRects(this);
384 waiting_for_screen_rects_ack_ = true;
387 void RenderWidgetHostImpl::SuppressNextCharEvents() {
388 suppress_next_char_events_ = true;
391 void RenderWidgetHostImpl::FlushInput() {
392 input_router_->Flush();
393 if (synthetic_gesture_controller_)
394 synthetic_gesture_controller_->Flush(base::TimeTicks::Now());
397 void RenderWidgetHostImpl::SetNeedsFlush() {
398 if (view_)
399 view_->OnSetNeedsFlushInput();
402 void RenderWidgetHostImpl::Init() {
403 DCHECK(process_->HasConnection());
405 renderer_initialized_ = true;
407 GpuSurfaceTracker::Get()->SetSurfaceHandle(
408 surface_id_, GetCompositingSurface());
410 // Send the ack along with the information on placement.
411 Send(new ViewMsg_CreatingNew_ACK(routing_id_));
412 GetProcess()->ResumeRequestsForView(routing_id_);
414 WasResized();
417 void RenderWidgetHostImpl::Shutdown() {
418 RejectMouseLockOrUnlockIfNecessary();
420 if (process_->HasConnection()) {
421 // Tell the renderer object to close.
422 bool rv = Send(new ViewMsg_Close(routing_id_));
423 DCHECK(rv);
426 Destroy();
429 bool RenderWidgetHostImpl::IsLoading() const {
430 return is_loading_;
433 bool RenderWidgetHostImpl::IsRenderView() const {
434 return false;
437 bool RenderWidgetHostImpl::OnMessageReceived(const IPC::Message &msg) {
438 bool handled = true;
439 IPC_BEGIN_MESSAGE_MAP(RenderWidgetHostImpl, msg)
440 IPC_MESSAGE_HANDLER(InputHostMsg_QueueSyntheticGesture,
441 OnQueueSyntheticGesture)
442 IPC_MESSAGE_HANDLER(InputHostMsg_ImeCancelComposition,
443 OnImeCancelComposition)
444 IPC_MESSAGE_HANDLER(ViewHostMsg_RenderViewReady, OnRenderViewReady)
445 IPC_MESSAGE_HANDLER(ViewHostMsg_RenderProcessGone, OnRenderProcessGone)
446 IPC_MESSAGE_HANDLER(ViewHostMsg_Close, OnClose)
447 IPC_MESSAGE_HANDLER(ViewHostMsg_UpdateScreenRects_ACK,
448 OnUpdateScreenRectsAck)
449 IPC_MESSAGE_HANDLER(ViewHostMsg_RequestMove, OnRequestMove)
450 IPC_MESSAGE_HANDLER(ViewHostMsg_SetTooltipText, OnSetTooltipText)
451 IPC_MESSAGE_HANDLER_GENERIC(ViewHostMsg_SwapCompositorFrame,
452 OnSwapCompositorFrame(msg))
453 IPC_MESSAGE_HANDLER(ViewHostMsg_DidStopFlinging, OnFlingingStopped)
454 IPC_MESSAGE_HANDLER(ViewHostMsg_UpdateRect, OnUpdateRect)
455 IPC_MESSAGE_HANDLER(ViewHostMsg_Focus, OnFocus)
456 IPC_MESSAGE_HANDLER(ViewHostMsg_Blur, OnBlur)
457 IPC_MESSAGE_HANDLER(ViewHostMsg_SetCursor, OnSetCursor)
458 IPC_MESSAGE_HANDLER(ViewHostMsg_TextInputTypeChanged,
459 OnTextInputTypeChanged)
460 IPC_MESSAGE_HANDLER(ViewHostMsg_LockMouse, OnLockMouse)
461 IPC_MESSAGE_HANDLER(ViewHostMsg_UnlockMouse, OnUnlockMouse)
462 IPC_MESSAGE_HANDLER(ViewHostMsg_ShowDisambiguationPopup,
463 OnShowDisambiguationPopup)
464 IPC_MESSAGE_HANDLER(ViewHostMsg_SelectionChanged, OnSelectionChanged)
465 IPC_MESSAGE_HANDLER(ViewHostMsg_SelectionBoundsChanged,
466 OnSelectionBoundsChanged)
467 #if defined(OS_WIN)
468 IPC_MESSAGE_HANDLER(ViewHostMsg_WindowlessPluginDummyWindowCreated,
469 OnWindowlessPluginDummyWindowCreated)
470 IPC_MESSAGE_HANDLER(ViewHostMsg_WindowlessPluginDummyWindowDestroyed,
471 OnWindowlessPluginDummyWindowDestroyed)
472 #endif
473 IPC_MESSAGE_HANDLER(InputHostMsg_ImeCompositionRangeChanged,
474 OnImeCompositionRangeChanged)
475 IPC_MESSAGE_UNHANDLED(handled = false)
476 IPC_END_MESSAGE_MAP()
478 if (!handled && input_router_ && input_router_->OnMessageReceived(msg))
479 return true;
481 if (!handled && view_ && view_->OnMessageReceived(msg))
482 return true;
484 return handled;
487 bool RenderWidgetHostImpl::Send(IPC::Message* msg) {
488 if (IPC_MESSAGE_ID_CLASS(msg->type()) == InputMsgStart)
489 return input_router_->SendInput(make_scoped_ptr(msg));
491 return process_->Send(msg);
494 void RenderWidgetHostImpl::SetIsLoading(bool is_loading) {
495 is_loading_ = is_loading;
496 if (!view_)
497 return;
498 view_->SetIsLoading(is_loading);
501 void RenderWidgetHostImpl::WasHidden() {
502 if (is_hidden_)
503 return;
505 is_hidden_ = true;
507 // Don't bother reporting hung state when we aren't active.
508 StopHangMonitorTimeout();
510 // If we have a renderer, then inform it that we are being hidden so it can
511 // reduce its resource utilization.
512 Send(new ViewMsg_WasHidden(routing_id_));
514 // Tell the RenderProcessHost we were hidden.
515 process_->WidgetHidden();
517 bool is_visible = false;
518 NotificationService::current()->Notify(
519 NOTIFICATION_RENDER_WIDGET_VISIBILITY_CHANGED,
520 Source<RenderWidgetHost>(this),
521 Details<bool>(&is_visible));
524 void RenderWidgetHostImpl::WasShown(const ui::LatencyInfo& latency_info) {
525 if (!is_hidden_)
526 return;
527 is_hidden_ = false;
529 SendScreenRects();
531 // Always repaint on restore.
532 bool needs_repainting = true;
533 needs_repainting_on_restore_ = false;
534 Send(new ViewMsg_WasShown(routing_id_, needs_repainting, latency_info));
536 process_->WidgetRestored();
538 bool is_visible = true;
539 NotificationService::current()->Notify(
540 NOTIFICATION_RENDER_WIDGET_VISIBILITY_CHANGED,
541 Source<RenderWidgetHost>(this),
542 Details<bool>(&is_visible));
544 // It's possible for our size to be out of sync with the renderer. The
545 // following is one case that leads to this:
546 // 1. WasResized -> Send ViewMsg_Resize to render
547 // 2. WasResized -> do nothing as resize_ack_pending_ is true
548 // 3. WasHidden
549 // 4. OnUpdateRect from (1) processed. Does NOT invoke WasResized as view
550 // is hidden. Now renderer/browser out of sync with what they think size
551 // is.
552 // By invoking WasResized the renderer is updated as necessary. WasResized
553 // does nothing if the sizes are already in sync.
555 // TODO: ideally ViewMsg_WasShown would take a size. This way, the renderer
556 // could handle both the restore and resize at once. This isn't that big a
557 // deal as RenderWidget::WasShown delays updating, so that the resize from
558 // WasResized is usually processed before the renderer is painted.
559 WasResized();
562 void RenderWidgetHostImpl::GetResizeParams(
563 ViewMsg_Resize_Params* resize_params) {
564 *resize_params = ViewMsg_Resize_Params();
566 if (!screen_info_) {
567 screen_info_.reset(new blink::WebScreenInfo);
568 GetWebScreenInfo(screen_info_.get());
570 resize_params->screen_info = *screen_info_;
571 resize_params->resizer_rect = GetRootWindowResizerRect();
573 if (view_) {
574 resize_params->new_size = view_->GetRequestedRendererSize();
575 resize_params->physical_backing_size = view_->GetPhysicalBackingSize();
576 resize_params->top_controls_height = view_->GetTopControlsHeight();
577 resize_params->top_controls_shrink_blink_size =
578 view_->DoTopControlsShrinkBlinkSize();
579 resize_params->visible_viewport_size = view_->GetVisibleViewportSize();
580 resize_params->is_fullscreen = IsFullscreen();
584 void RenderWidgetHostImpl::SetInitialRenderSizeParams(
585 const ViewMsg_Resize_Params& resize_params) {
586 // We don't expect to receive an ACK when the requested size or the physical
587 // backing size is empty, or when the main viewport size didn't change.
588 if (!resize_params.new_size.IsEmpty() &&
589 !resize_params.physical_backing_size.IsEmpty()) {
590 resize_ack_pending_ = g_check_for_pending_resize_ack;
593 old_resize_params_ =
594 make_scoped_ptr(new ViewMsg_Resize_Params(resize_params));
597 void RenderWidgetHostImpl::WasResized() {
598 // Skip if the |delegate_| has already been detached because
599 // it's web contents is being deleted.
600 if (resize_ack_pending_ || !process_->HasConnection() || !view_ ||
601 !renderer_initialized_ || auto_resize_enabled_ || !delegate_) {
602 return;
605 bool size_changed = true;
606 bool side_payload_changed = screen_info_out_of_date_;
607 scoped_ptr<ViewMsg_Resize_Params> params(new ViewMsg_Resize_Params);
609 GetResizeParams(params.get());
610 if (old_resize_params_) {
611 size_changed = old_resize_params_->new_size != params->new_size;
612 side_payload_changed =
613 side_payload_changed ||
614 old_resize_params_->physical_backing_size !=
615 params->physical_backing_size ||
616 old_resize_params_->is_fullscreen != params->is_fullscreen ||
617 old_resize_params_->top_controls_height !=
618 params->top_controls_height ||
619 old_resize_params_->top_controls_shrink_blink_size !=
620 params->top_controls_shrink_blink_size ||
621 old_resize_params_->visible_viewport_size !=
622 params->visible_viewport_size;
625 if (!size_changed && !side_payload_changed)
626 return;
628 // We don't expect to receive an ACK when the requested size or the physical
629 // backing size is empty, or when the main viewport size didn't change.
630 if (!params->new_size.IsEmpty() && !params->physical_backing_size.IsEmpty() &&
631 size_changed) {
632 resize_ack_pending_ = g_check_for_pending_resize_ack;
635 if (!Send(new ViewMsg_Resize(routing_id_, *params))) {
636 resize_ack_pending_ = false;
637 } else {
638 old_resize_params_.swap(params);
642 void RenderWidgetHostImpl::ResizeRectChanged(const gfx::Rect& new_rect) {
643 Send(new ViewMsg_ChangeResizeRect(routing_id_, new_rect));
646 void RenderWidgetHostImpl::GotFocus() {
647 Focus();
648 if (delegate_)
649 delegate_->RenderWidgetGotFocus(this);
652 void RenderWidgetHostImpl::Focus() {
653 Send(new InputMsg_SetFocus(routing_id_, true));
656 void RenderWidgetHostImpl::Blur() {
657 // If there is a pending mouse lock request, we don't want to reject it at
658 // this point. The user can switch focus back to this view and approve the
659 // request later.
660 if (IsMouseLocked())
661 view_->UnlockMouse();
663 if (touch_emulator_)
664 touch_emulator_->CancelTouch();
666 Send(new InputMsg_SetFocus(routing_id_, false));
669 void RenderWidgetHostImpl::LostCapture() {
670 if (touch_emulator_)
671 touch_emulator_->CancelTouch();
673 Send(new InputMsg_MouseCaptureLost(routing_id_));
676 void RenderWidgetHostImpl::SetActive(bool active) {
677 Send(new ViewMsg_SetActive(routing_id_, active));
680 void RenderWidgetHostImpl::LostMouseLock() {
681 Send(new ViewMsg_MouseLockLost(routing_id_));
684 void RenderWidgetHostImpl::ViewDestroyed() {
685 RejectMouseLockOrUnlockIfNecessary();
687 // TODO(evanm): tracking this may no longer be necessary;
688 // eliminate this function if so.
689 SetView(NULL);
692 void RenderWidgetHostImpl::CopyFromBackingStore(
693 const gfx::Rect& src_subrect,
694 const gfx::Size& accelerated_dst_size,
695 ReadbackRequestCallback& callback,
696 const SkColorType color_type) {
697 if (view_) {
698 TRACE_EVENT0("browser",
699 "RenderWidgetHostImpl::CopyFromBackingStore::FromCompositingSurface");
700 gfx::Rect accelerated_copy_rect = src_subrect.IsEmpty() ?
701 gfx::Rect(view_->GetViewBounds().size()) : src_subrect;
702 view_->CopyFromCompositingSurface(
703 accelerated_copy_rect, accelerated_dst_size, callback, color_type);
704 return;
707 callback.Run(SkBitmap(), content::READBACK_FAILED);
710 bool RenderWidgetHostImpl::CanCopyFromBackingStore() {
711 if (view_)
712 return view_->IsSurfaceAvailableForCopy();
713 return false;
716 #if defined(OS_ANDROID)
717 void RenderWidgetHostImpl::LockBackingStore() {
718 if (view_)
719 view_->LockCompositingSurface();
722 void RenderWidgetHostImpl::UnlockBackingStore() {
723 if (view_)
724 view_->UnlockCompositingSurface();
726 #endif
728 #if defined(OS_MACOSX)
729 void RenderWidgetHostImpl::PauseForPendingResizeOrRepaints() {
730 TRACE_EVENT0("browser",
731 "RenderWidgetHostImpl::PauseForPendingResizeOrRepaints");
733 if (!CanPauseForPendingResizeOrRepaints())
734 return;
736 WaitForSurface();
739 bool RenderWidgetHostImpl::CanPauseForPendingResizeOrRepaints() {
740 // Do not pause if the view is hidden.
741 if (is_hidden())
742 return false;
744 // Do not pause if there is not a paint or resize already coming.
745 if (!repaint_ack_pending_ && !resize_ack_pending_)
746 return false;
748 return true;
751 void RenderWidgetHostImpl::WaitForSurface() {
752 TRACE_EVENT0("browser", "RenderWidgetHostImpl::WaitForSurface");
754 // How long to (synchronously) wait for the renderer to respond with a
755 // new frame when our current frame doesn't exist or is the wrong size.
756 // This timeout impacts the "choppiness" of our window resize.
757 const int kPaintMsgTimeoutMS = 50;
759 if (!view_)
760 return;
762 // The view_size will be current_size_ for auto-sized views and otherwise the
763 // size of the view_. (For auto-sized views, current_size_ is updated during
764 // UpdateRect messages.)
765 gfx::Size view_size = current_size_;
766 if (!auto_resize_enabled_) {
767 // Get the desired size from the current view bounds.
768 gfx::Rect view_rect = view_->GetViewBounds();
769 if (view_rect.IsEmpty())
770 return;
771 view_size = view_rect.size();
774 TRACE_EVENT2("renderer_host",
775 "RenderWidgetHostImpl::WaitForBackingStore",
776 "width",
777 base::IntToString(view_size.width()),
778 "height",
779 base::IntToString(view_size.height()));
781 // We should not be asked to paint while we are hidden. If we are hidden,
782 // then it means that our consumer failed to call WasShown. If we're not
783 // force creating the backing store, it's OK since we can feel free to give
784 // out our cached one if we have it.
785 DCHECK(!is_hidden_) << "WaitForSurface called while hidden!";
787 // We should never be called recursively; this can theoretically lead to
788 // infinite recursion and almost certainly leads to lower performance.
789 DCHECK(!in_get_backing_store_) << "WaitForSurface called recursively!";
790 base::AutoReset<bool> auto_reset_in_get_backing_store(
791 &in_get_backing_store_, true);
793 // We might have a surface that we can use!
794 if (view_->HasAcceleratedSurface(view_size))
795 return;
797 // We do not have a suitable backing store in the cache, so send out a
798 // request to the renderer to paint the view if required.
799 if (!repaint_ack_pending_ && !resize_ack_pending_) {
800 repaint_start_time_ = TimeTicks::Now();
801 repaint_ack_pending_ = true;
802 TRACE_EVENT_ASYNC_BEGIN0(
803 "renderer_host", "RenderWidgetHostImpl::repaint_ack_pending_", this);
804 Send(new ViewMsg_Repaint(routing_id_, view_size));
807 TimeDelta max_delay = TimeDelta::FromMilliseconds(kPaintMsgTimeoutMS);
808 TimeTicks end_time = TimeTicks::Now() + max_delay;
809 do {
810 TRACE_EVENT0("renderer_host", "WaitForSurface::WaitForUpdate");
812 // When we have asked the RenderWidget to resize, and we are still waiting
813 // on a response, block for a little while to see if we can't get a response
814 // before returning the old (incorrectly sized) backing store.
815 IPC::Message msg;
816 if (RenderWidgetResizeHelper::Get()->WaitForSingleTaskToRun(max_delay)) {
818 // For auto-resized views, current_size_ determines the view_size and it
819 // may have changed during the handling of an UpdateRect message.
820 if (auto_resize_enabled_)
821 view_size = current_size_;
823 // Break now if we got a backing store or accelerated surface of the
824 // correct size.
825 if (view_->HasAcceleratedSurface(view_size))
826 return;
827 } else {
828 TRACE_EVENT0("renderer_host", "WaitForSurface::Timeout");
829 break;
832 // Loop if we still have time left and haven't gotten a properly sized
833 // BackingStore yet. This is necessary to support the GPU path which
834 // typically has multiple frames pipelined -- we may need to skip one or two
835 // BackingStore messages to get to the latest.
836 max_delay = end_time - TimeTicks::Now();
837 } while (max_delay > TimeDelta::FromSeconds(0));
839 #endif
841 bool RenderWidgetHostImpl::ScheduleComposite() {
842 if (is_hidden_ || current_size_.IsEmpty() || repaint_ack_pending_ ||
843 resize_ack_pending_) {
844 return false;
847 // Send out a request to the renderer to paint the view if required.
848 repaint_start_time_ = TimeTicks::Now();
849 repaint_ack_pending_ = true;
850 TRACE_EVENT_ASYNC_BEGIN0(
851 "renderer_host", "RenderWidgetHostImpl::repaint_ack_pending_", this);
852 Send(new ViewMsg_Repaint(routing_id_, current_size_));
853 return true;
856 void RenderWidgetHostImpl::StartHangMonitorTimeout(base::TimeDelta delay) {
857 if (hang_monitor_timeout_)
858 hang_monitor_timeout_->Start(delay);
861 void RenderWidgetHostImpl::RestartHangMonitorTimeout() {
862 if (hang_monitor_timeout_)
863 hang_monitor_timeout_->Restart(
864 base::TimeDelta::FromMilliseconds(hung_renderer_delay_ms_));
867 void RenderWidgetHostImpl::StopHangMonitorTimeout() {
868 if (hang_monitor_timeout_)
869 hang_monitor_timeout_->Stop();
870 RendererIsResponsive();
873 void RenderWidgetHostImpl::ForwardMouseEvent(const WebMouseEvent& mouse_event) {
874 ForwardMouseEventWithLatencyInfo(mouse_event, ui::LatencyInfo());
877 void RenderWidgetHostImpl::ForwardMouseEventWithLatencyInfo(
878 const blink::WebMouseEvent& mouse_event,
879 const ui::LatencyInfo& ui_latency) {
880 TRACE_EVENT2("input", "RenderWidgetHostImpl::ForwardMouseEvent",
881 "x", mouse_event.x, "y", mouse_event.y);
883 for (size_t i = 0; i < mouse_event_callbacks_.size(); ++i) {
884 if (mouse_event_callbacks_[i].Run(mouse_event))
885 return;
888 if (IgnoreInputEvents())
889 return;
891 if (touch_emulator_ && touch_emulator_->HandleMouseEvent(mouse_event))
892 return;
894 MouseEventWithLatencyInfo mouse_with_latency(mouse_event, ui_latency);
895 latency_tracker_.OnInputEvent(mouse_event, &mouse_with_latency.latency);
896 input_router_->SendMouseEvent(mouse_with_latency);
898 // Pass mouse state to gpu service if the subscribe uniform
899 // extension is enabled.
900 if (process_->SubscribeUniformEnabled()) {
901 gpu::ValueState state;
902 state.int_value[0] = mouse_event.x;
903 state.int_value[1] = mouse_event.y;
904 // TODO(orglofch) Separate the mapping of pending value states to the
905 // Gpu Service to be per RWH not per process
906 process_->SendUpdateValueState(GL_MOUSE_POSITION_CHROMIUM, state);
910 void RenderWidgetHostImpl::OnPointerEventActivate() {
913 void RenderWidgetHostImpl::ForwardWheelEvent(
914 const WebMouseWheelEvent& wheel_event) {
915 ForwardWheelEventWithLatencyInfo(wheel_event, ui::LatencyInfo());
918 void RenderWidgetHostImpl::ForwardWheelEventWithLatencyInfo(
919 const blink::WebMouseWheelEvent& wheel_event,
920 const ui::LatencyInfo& ui_latency) {
921 TRACE_EVENT0("input", "RenderWidgetHostImpl::ForwardWheelEvent");
923 if (IgnoreInputEvents())
924 return;
926 if (touch_emulator_ && touch_emulator_->HandleMouseWheelEvent(wheel_event))
927 return;
929 MouseWheelEventWithLatencyInfo wheel_with_latency(wheel_event, ui_latency);
930 latency_tracker_.OnInputEvent(wheel_event, &wheel_with_latency.latency);
931 input_router_->SendWheelEvent(wheel_with_latency);
934 void RenderWidgetHostImpl::ForwardGestureEvent(
935 const blink::WebGestureEvent& gesture_event) {
936 ForwardGestureEventWithLatencyInfo(gesture_event, ui::LatencyInfo());
939 void RenderWidgetHostImpl::ForwardGestureEventWithLatencyInfo(
940 const blink::WebGestureEvent& gesture_event,
941 const ui::LatencyInfo& ui_latency) {
942 TRACE_EVENT0("input", "RenderWidgetHostImpl::ForwardGestureEvent");
943 // Early out if necessary, prior to performing latency logic.
944 if (IgnoreInputEvents())
945 return;
947 if (delegate_->PreHandleGestureEvent(gesture_event))
948 return;
950 GestureEventWithLatencyInfo gesture_with_latency(gesture_event, ui_latency);
951 latency_tracker_.OnInputEvent(gesture_event, &gesture_with_latency.latency);
952 input_router_->SendGestureEvent(gesture_with_latency);
955 void RenderWidgetHostImpl::ForwardEmulatedTouchEvent(
956 const blink::WebTouchEvent& touch_event) {
957 TRACE_EVENT0("input", "RenderWidgetHostImpl::ForwardEmulatedTouchEvent");
959 TouchEventWithLatencyInfo touch_with_latency(touch_event);
960 latency_tracker_.OnInputEvent(touch_event, &touch_with_latency.latency);
961 input_router_->SendTouchEvent(touch_with_latency);
964 void RenderWidgetHostImpl::ForwardTouchEventWithLatencyInfo(
965 const blink::WebTouchEvent& touch_event,
966 const ui::LatencyInfo& ui_latency) {
967 TRACE_EVENT0("input", "RenderWidgetHostImpl::ForwardTouchEvent");
969 // Always forward TouchEvents for touch stream consistency. They will be
970 // ignored if appropriate in FilterInputEvent().
972 TouchEventWithLatencyInfo touch_with_latency(touch_event, ui_latency);
973 if (touch_emulator_ &&
974 touch_emulator_->HandleTouchEvent(touch_with_latency.event)) {
975 if (view_) {
976 view_->ProcessAckedTouchEvent(
977 touch_with_latency, INPUT_EVENT_ACK_STATE_CONSUMED);
979 return;
982 latency_tracker_.OnInputEvent(touch_event, &touch_with_latency.latency);
983 input_router_->SendTouchEvent(touch_with_latency);
986 void RenderWidgetHostImpl::ForwardKeyboardEvent(
987 const NativeWebKeyboardEvent& key_event) {
988 TRACE_EVENT0("input", "RenderWidgetHostImpl::ForwardKeyboardEvent");
989 if (IgnoreInputEvents())
990 return;
992 if (!process_->HasConnection())
993 return;
995 // First, let keypress listeners take a shot at handling the event. If a
996 // listener handles the event, it should not be propagated to the renderer.
997 if (KeyPressListenersHandleEvent(key_event)) {
998 // Some keypresses that are accepted by the listener might have follow up
999 // char events, which should be ignored.
1000 if (key_event.type == WebKeyboardEvent::RawKeyDown)
1001 suppress_next_char_events_ = true;
1002 return;
1005 if (key_event.type == WebKeyboardEvent::Char &&
1006 (key_event.windowsKeyCode == ui::VKEY_RETURN ||
1007 key_event.windowsKeyCode == ui::VKEY_SPACE)) {
1008 OnUserGesture();
1011 // Double check the type to make sure caller hasn't sent us nonsense that
1012 // will mess up our key queue.
1013 if (!WebInputEvent::isKeyboardEventType(key_event.type))
1014 return;
1016 if (suppress_next_char_events_) {
1017 // If preceding RawKeyDown event was handled by the browser, then we need
1018 // suppress all Char events generated by it. Please note that, one
1019 // RawKeyDown event may generate multiple Char events, so we can't reset
1020 // |suppress_next_char_events_| until we get a KeyUp or a RawKeyDown.
1021 if (key_event.type == WebKeyboardEvent::Char)
1022 return;
1023 // We get a KeyUp or a RawKeyDown event.
1024 suppress_next_char_events_ = false;
1027 bool is_shortcut = false;
1029 // Only pre-handle the key event if it's not handled by the input method.
1030 if (delegate_ && !key_event.skip_in_browser) {
1031 // We need to set |suppress_next_char_events_| to true if
1032 // PreHandleKeyboardEvent() returns true, but |this| may already be
1033 // destroyed at that time. So set |suppress_next_char_events_| true here,
1034 // then revert it afterwards when necessary.
1035 if (key_event.type == WebKeyboardEvent::RawKeyDown)
1036 suppress_next_char_events_ = true;
1038 // Tab switching/closing accelerators aren't sent to the renderer to avoid
1039 // a hung/malicious renderer from interfering.
1040 if (delegate_->PreHandleKeyboardEvent(key_event, &is_shortcut))
1041 return;
1043 if (key_event.type == WebKeyboardEvent::RawKeyDown)
1044 suppress_next_char_events_ = false;
1047 if (touch_emulator_ && touch_emulator_->HandleKeyboardEvent(key_event))
1048 return;
1050 ui::LatencyInfo latency;
1051 latency_tracker_.OnInputEvent(key_event, &latency);
1052 input_router_->SendKeyboardEvent(key_event, latency, is_shortcut);
1055 void RenderWidgetHostImpl::QueueSyntheticGesture(
1056 scoped_ptr<SyntheticGesture> synthetic_gesture,
1057 const base::Callback<void(SyntheticGesture::Result)>& on_complete) {
1058 if (!synthetic_gesture_controller_ && view_) {
1059 synthetic_gesture_controller_.reset(
1060 new SyntheticGestureController(
1061 view_->CreateSyntheticGestureTarget().Pass()));
1063 if (synthetic_gesture_controller_) {
1064 synthetic_gesture_controller_->QueueSyntheticGesture(
1065 synthetic_gesture.Pass(), on_complete);
1069 void RenderWidgetHostImpl::SetCursor(const WebCursor& cursor) {
1070 if (!view_)
1071 return;
1072 view_->UpdateCursor(cursor);
1075 void RenderWidgetHostImpl::ShowContextMenuAtPoint(const gfx::Point& point) {
1076 Send(new ViewMsg_ShowContextMenu(
1077 GetRoutingID(), ui::MENU_SOURCE_MOUSE, point));
1080 void RenderWidgetHostImpl::SendCursorVisibilityState(bool is_visible) {
1081 Send(new InputMsg_CursorVisibilityChange(GetRoutingID(), is_visible));
1084 int64 RenderWidgetHostImpl::GetLatencyComponentId() const {
1085 return latency_tracker_.latency_component_id();
1088 // static
1089 void RenderWidgetHostImpl::DisableResizeAckCheckForTesting() {
1090 g_check_for_pending_resize_ack = false;
1093 void RenderWidgetHostImpl::AddKeyPressEventCallback(
1094 const KeyPressEventCallback& callback) {
1095 key_press_event_callbacks_.push_back(callback);
1098 void RenderWidgetHostImpl::RemoveKeyPressEventCallback(
1099 const KeyPressEventCallback& callback) {
1100 for (size_t i = 0; i < key_press_event_callbacks_.size(); ++i) {
1101 if (key_press_event_callbacks_[i].Equals(callback)) {
1102 key_press_event_callbacks_.erase(
1103 key_press_event_callbacks_.begin() + i);
1104 return;
1109 void RenderWidgetHostImpl::AddMouseEventCallback(
1110 const MouseEventCallback& callback) {
1111 mouse_event_callbacks_.push_back(callback);
1114 void RenderWidgetHostImpl::RemoveMouseEventCallback(
1115 const MouseEventCallback& callback) {
1116 for (size_t i = 0; i < mouse_event_callbacks_.size(); ++i) {
1117 if (mouse_event_callbacks_[i].Equals(callback)) {
1118 mouse_event_callbacks_.erase(mouse_event_callbacks_.begin() + i);
1119 return;
1124 void RenderWidgetHostImpl::GetWebScreenInfo(blink::WebScreenInfo* result) {
1125 TRACE_EVENT0("renderer_host", "RenderWidgetHostImpl::GetWebScreenInfo");
1126 if (view_)
1127 view_->GetScreenInfo(result);
1128 else
1129 RenderWidgetHostViewBase::GetDefaultScreenInfo(result);
1130 latency_tracker_.set_device_scale_factor(result->deviceScaleFactor);
1131 screen_info_out_of_date_ = false;
1134 const NativeWebKeyboardEvent*
1135 RenderWidgetHostImpl::GetLastKeyboardEvent() const {
1136 return input_router_->GetLastKeyboardEvent();
1139 void RenderWidgetHostImpl::NotifyScreenInfoChanged() {
1140 // The resize message (which may not happen immediately) will carry with it
1141 // the screen info as well as the new size (if the screen has changed scale
1142 // factor).
1143 InvalidateScreenInfo();
1144 WasResized();
1147 void RenderWidgetHostImpl::InvalidateScreenInfo() {
1148 screen_info_out_of_date_ = true;
1149 screen_info_.reset();
1152 void RenderWidgetHostImpl::GetSnapshotFromBrowser(
1153 const base::Callback<void(const unsigned char*,size_t)> callback) {
1154 int id = next_browser_snapshot_id_++;
1155 pending_browser_snapshots_.insert(std::make_pair(id, callback));
1156 Send(new ViewMsg_ForceRedraw(GetRoutingID(), id));
1159 void RenderWidgetHostImpl::OnSelectionChanged(const base::string16& text,
1160 size_t offset,
1161 const gfx::Range& range) {
1162 if (view_)
1163 view_->SelectionChanged(text, offset, range);
1166 void RenderWidgetHostImpl::OnSelectionBoundsChanged(
1167 const ViewHostMsg_SelectionBounds_Params& params) {
1168 if (view_) {
1169 view_->SelectionBoundsChanged(params);
1173 void RenderWidgetHostImpl::UpdateVSyncParameters(base::TimeTicks timebase,
1174 base::TimeDelta interval) {
1175 Send(new ViewMsg_UpdateVSyncParameters(GetRoutingID(), timebase, interval));
1178 void RenderWidgetHostImpl::RendererExited(base::TerminationStatus status,
1179 int exit_code) {
1180 // Clearing this flag causes us to re-create the renderer when recovering
1181 // from a crashed renderer.
1182 renderer_initialized_ = false;
1184 waiting_for_screen_rects_ack_ = false;
1186 // Must reset these to ensure that keyboard events work with a new renderer.
1187 suppress_next_char_events_ = false;
1189 // Reset some fields in preparation for recovering from a crash.
1190 ResetSizeAndRepaintPendingFlags();
1191 current_size_.SetSize(0, 0);
1192 // After the renderer crashes, the view is destroyed and so the
1193 // RenderWidgetHost cannot track its visibility anymore. We assume such
1194 // RenderWidgetHost to be visible for the sake of internal accounting - be
1195 // careful about changing this - see http://crbug.com/401859.
1197 // We need to at least make sure that the RenderProcessHost is notified about
1198 // the |is_hidden_| change, so that the renderer will have correct visibility
1199 // set when respawned.
1200 if (is_hidden_) {
1201 process_->WidgetRestored();
1202 is_hidden_ = false;
1205 // Reset this to ensure the hung renderer mechanism is working properly.
1206 in_flight_event_count_ = 0;
1208 if (view_) {
1209 GpuSurfaceTracker::Get()->SetSurfaceHandle(surface_id_,
1210 gfx::GLSurfaceHandle());
1211 view_->RenderProcessGone(status, exit_code);
1212 view_ = NULL; // The View should be deleted by RenderProcessGone.
1213 view_weak_.reset();
1216 // Reconstruct the input router to ensure that it has fresh state for a new
1217 // renderer. Otherwise it may be stuck waiting for the old renderer to ack an
1218 // event. (In particular, the above call to view_->RenderProcessGone will
1219 // destroy the aura window, which may dispatch a synthetic mouse move.)
1220 input_router_.reset(new InputRouterImpl(
1221 process_, this, this, routing_id_, GetInputRouterConfigForPlatform()));
1223 synthetic_gesture_controller_.reset();
1226 void RenderWidgetHostImpl::UpdateTextDirection(WebTextDirection direction) {
1227 text_direction_updated_ = true;
1228 text_direction_ = direction;
1231 void RenderWidgetHostImpl::CancelUpdateTextDirection() {
1232 if (text_direction_updated_)
1233 text_direction_canceled_ = true;
1236 void RenderWidgetHostImpl::NotifyTextDirection() {
1237 if (text_direction_updated_) {
1238 if (!text_direction_canceled_)
1239 Send(new ViewMsg_SetTextDirection(GetRoutingID(), text_direction_));
1240 text_direction_updated_ = false;
1241 text_direction_canceled_ = false;
1245 void RenderWidgetHostImpl::SetInputMethodActive(bool activate) {
1246 input_method_active_ = activate;
1247 Send(new ViewMsg_SetInputMethodActive(GetRoutingID(), activate));
1250 void RenderWidgetHostImpl::CandidateWindowShown() {
1251 Send(new ViewMsg_CandidateWindowShown(GetRoutingID()));
1254 void RenderWidgetHostImpl::CandidateWindowUpdated() {
1255 Send(new ViewMsg_CandidateWindowUpdated(GetRoutingID()));
1258 void RenderWidgetHostImpl::CandidateWindowHidden() {
1259 Send(new ViewMsg_CandidateWindowHidden(GetRoutingID()));
1262 void RenderWidgetHostImpl::ImeSetComposition(
1263 const base::string16& text,
1264 const std::vector<blink::WebCompositionUnderline>& underlines,
1265 int selection_start,
1266 int selection_end) {
1267 Send(new InputMsg_ImeSetComposition(
1268 GetRoutingID(), text, underlines, selection_start, selection_end));
1271 void RenderWidgetHostImpl::ImeConfirmComposition(
1272 const base::string16& text,
1273 const gfx::Range& replacement_range,
1274 bool keep_selection) {
1275 Send(new InputMsg_ImeConfirmComposition(
1276 GetRoutingID(), text, replacement_range, keep_selection));
1279 void RenderWidgetHostImpl::ImeCancelComposition() {
1280 Send(new InputMsg_ImeSetComposition(GetRoutingID(), base::string16(),
1281 std::vector<blink::WebCompositionUnderline>(), 0, 0));
1284 gfx::Rect RenderWidgetHostImpl::GetRootWindowResizerRect() const {
1285 return gfx::Rect();
1288 void RenderWidgetHostImpl::RequestToLockMouse(bool user_gesture,
1289 bool last_unlocked_by_target) {
1290 // Directly reject to lock the mouse. Subclass can override this method to
1291 // decide whether to allow mouse lock or not.
1292 GotResponseToLockMouseRequest(false);
1295 void RenderWidgetHostImpl::RejectMouseLockOrUnlockIfNecessary() {
1296 DCHECK(!pending_mouse_lock_request_ || !IsMouseLocked());
1297 if (pending_mouse_lock_request_) {
1298 pending_mouse_lock_request_ = false;
1299 Send(new ViewMsg_LockMouse_ACK(routing_id_, false));
1300 } else if (IsMouseLocked()) {
1301 view_->UnlockMouse();
1305 bool RenderWidgetHostImpl::IsMouseLocked() const {
1306 return view_ ? view_->IsMouseLocked() : false;
1309 bool RenderWidgetHostImpl::IsFullscreen() const {
1310 return false;
1313 void RenderWidgetHostImpl::SetAutoResize(bool enable,
1314 const gfx::Size& min_size,
1315 const gfx::Size& max_size) {
1316 auto_resize_enabled_ = enable;
1317 min_size_for_auto_resize_ = min_size;
1318 max_size_for_auto_resize_ = max_size;
1321 void RenderWidgetHostImpl::Destroy() {
1322 NotificationService::current()->Notify(
1323 NOTIFICATION_RENDER_WIDGET_HOST_DESTROYED,
1324 Source<RenderWidgetHost>(this),
1325 NotificationService::NoDetails());
1327 // Tell the view to die.
1328 // Note that in the process of the view shutting down, it can call a ton
1329 // of other messages on us. So if you do any other deinitialization here,
1330 // do it after this call to view_->Destroy().
1331 if (view_)
1332 view_->Destroy();
1334 delete this;
1337 void RenderWidgetHostImpl::RendererIsUnresponsive() {
1338 NotificationService::current()->Notify(
1339 NOTIFICATION_RENDER_WIDGET_HOST_HANG,
1340 Source<RenderWidgetHost>(this),
1341 NotificationService::NoDetails());
1342 is_unresponsive_ = true;
1343 NotifyRendererUnresponsive();
1346 void RenderWidgetHostImpl::RendererIsResponsive() {
1347 if (is_unresponsive_) {
1348 is_unresponsive_ = false;
1349 NotifyRendererResponsive();
1353 void RenderWidgetHostImpl::OnRenderViewReady() {
1354 SendScreenRects();
1355 WasResized();
1358 void RenderWidgetHostImpl::OnRenderProcessGone(int status, int exit_code) {
1359 // TODO(evanm): This synchronously ends up calling "delete this".
1360 // Is that really what we want in response to this message? I'm matching
1361 // previous behavior of the code here.
1362 Destroy();
1365 void RenderWidgetHostImpl::OnClose() {
1366 Shutdown();
1369 void RenderWidgetHostImpl::OnSetTooltipText(
1370 const base::string16& tooltip_text,
1371 WebTextDirection text_direction_hint) {
1372 // First, add directionality marks around tooltip text if necessary.
1373 // A naive solution would be to simply always wrap the text. However, on
1374 // windows, Unicode directional embedding characters can't be displayed on
1375 // systems that lack RTL fonts and are instead displayed as empty squares.
1377 // To get around this we only wrap the string when we deem it necessary i.e.
1378 // when the locale direction is different than the tooltip direction hint.
1380 // Currently, we use element's directionality as the tooltip direction hint.
1381 // An alternate solution would be to set the overall directionality based on
1382 // trying to detect the directionality from the tooltip text rather than the
1383 // element direction. One could argue that would be a preferable solution
1384 // but we use the current approach to match Fx & IE's behavior.
1385 base::string16 wrapped_tooltip_text = tooltip_text;
1386 if (!tooltip_text.empty()) {
1387 if (text_direction_hint == blink::WebTextDirectionLeftToRight) {
1388 // Force the tooltip to have LTR directionality.
1389 wrapped_tooltip_text =
1390 base::i18n::GetDisplayStringInLTRDirectionality(wrapped_tooltip_text);
1391 } else if (text_direction_hint == blink::WebTextDirectionRightToLeft &&
1392 !base::i18n::IsRTL()) {
1393 // Force the tooltip to have RTL directionality.
1394 base::i18n::WrapStringWithRTLFormatting(&wrapped_tooltip_text);
1397 if (GetView())
1398 view_->SetTooltipText(wrapped_tooltip_text);
1401 void RenderWidgetHostImpl::OnUpdateScreenRectsAck() {
1402 waiting_for_screen_rects_ack_ = false;
1403 if (!view_)
1404 return;
1406 if (view_->GetViewBounds() == last_view_screen_rect_ &&
1407 view_->GetBoundsInRootWindow() == last_window_screen_rect_) {
1408 return;
1411 SendScreenRects();
1414 void RenderWidgetHostImpl::OnRequestMove(const gfx::Rect& pos) {
1415 if (view_) {
1416 view_->SetBounds(pos);
1417 Send(new ViewMsg_Move_ACK(routing_id_));
1421 bool RenderWidgetHostImpl::OnSwapCompositorFrame(
1422 const IPC::Message& message) {
1423 // This trace event is used in
1424 // chrome/browser/extensions/api/cast_streaming/performance_test.cc
1425 TRACE_EVENT0("test_fps",
1426 TRACE_DISABLED_BY_DEFAULT("OnSwapCompositorFrame"));
1427 ViewHostMsg_SwapCompositorFrame::Param param;
1428 if (!ViewHostMsg_SwapCompositorFrame::Read(&message, &param))
1429 return false;
1430 scoped_ptr<cc::CompositorFrame> frame(new cc::CompositorFrame);
1431 uint32 output_surface_id = get<0>(param);
1432 get<1>(param).AssignTo(frame.get());
1433 std::vector<IPC::Message> messages_to_deliver_with_frame;
1434 messages_to_deliver_with_frame.swap(get<2>(param));
1436 latency_tracker_.OnSwapCompositorFrame(&frame->metadata.latency_info);
1438 input_router_->OnViewUpdated(
1439 GetInputRouterViewFlagsFromCompositorFrameMetadata(frame->metadata));
1441 if (view_) {
1442 view_->OnSwapCompositorFrame(output_surface_id, frame.Pass());
1443 view_->DidReceiveRendererFrame();
1444 } else {
1445 cc::CompositorFrameAck ack;
1446 if (frame->gl_frame_data) {
1447 ack.gl_frame_data = frame->gl_frame_data.Pass();
1448 ack.gl_frame_data->sync_point = 0;
1449 } else if (frame->delegated_frame_data) {
1450 cc::TransferableResource::ReturnResources(
1451 frame->delegated_frame_data->resource_list,
1452 &ack.resources);
1453 } else if (frame->software_frame_data) {
1454 ack.last_software_frame_id = frame->software_frame_data->id;
1456 SendSwapCompositorFrameAck(routing_id_, output_surface_id,
1457 process_->GetID(), ack);
1460 RenderProcessHost* rph = GetProcess();
1461 for (std::vector<IPC::Message>::const_iterator i =
1462 messages_to_deliver_with_frame.begin();
1463 i != messages_to_deliver_with_frame.end();
1464 ++i) {
1465 rph->OnMessageReceived(*i);
1466 if (i->dispatch_error())
1467 rph->OnBadMessageReceived(*i);
1469 messages_to_deliver_with_frame.clear();
1471 return true;
1474 void RenderWidgetHostImpl::OnFlingingStopped() {
1475 if (view_)
1476 view_->DidStopFlinging();
1479 void RenderWidgetHostImpl::OnUpdateRect(
1480 const ViewHostMsg_UpdateRect_Params& params) {
1481 TRACE_EVENT0("renderer_host", "RenderWidgetHostImpl::OnUpdateRect");
1482 TimeTicks paint_start = TimeTicks::Now();
1484 // Update our knowledge of the RenderWidget's size.
1485 current_size_ = params.view_size;
1487 bool is_resize_ack =
1488 ViewHostMsg_UpdateRect_Flags::is_resize_ack(params.flags);
1490 // resize_ack_pending_ needs to be cleared before we call DidPaintRect, since
1491 // that will end up reaching GetBackingStore.
1492 if (is_resize_ack) {
1493 DCHECK(!g_check_for_pending_resize_ack || resize_ack_pending_);
1494 resize_ack_pending_ = false;
1497 bool is_repaint_ack =
1498 ViewHostMsg_UpdateRect_Flags::is_repaint_ack(params.flags);
1499 if (is_repaint_ack) {
1500 DCHECK(repaint_ack_pending_);
1501 TRACE_EVENT_ASYNC_END0(
1502 "renderer_host", "RenderWidgetHostImpl::repaint_ack_pending_", this);
1503 repaint_ack_pending_ = false;
1504 TimeDelta delta = TimeTicks::Now() - repaint_start_time_;
1505 UMA_HISTOGRAM_TIMES("MPArch.RWH_RepaintDelta", delta);
1508 DCHECK(!params.view_size.IsEmpty());
1510 DidUpdateBackingStore(params, paint_start);
1512 if (auto_resize_enabled_) {
1513 bool post_callback = new_auto_size_.IsEmpty();
1514 new_auto_size_ = params.view_size;
1515 if (post_callback) {
1516 base::MessageLoop::current()->PostTask(
1517 FROM_HERE,
1518 base::Bind(&RenderWidgetHostImpl::DelayedAutoResized,
1519 weak_factory_.GetWeakPtr()));
1523 // Log the time delta for processing a paint message. On platforms that don't
1524 // support asynchronous painting, this is equivalent to
1525 // MPArch.RWH_TotalPaintTime.
1526 TimeDelta delta = TimeTicks::Now() - paint_start;
1527 UMA_HISTOGRAM_TIMES("MPArch.RWH_OnMsgUpdateRect", delta);
1530 void RenderWidgetHostImpl::DidUpdateBackingStore(
1531 const ViewHostMsg_UpdateRect_Params& params,
1532 const TimeTicks& paint_start) {
1533 TRACE_EVENT0("renderer_host", "RenderWidgetHostImpl::DidUpdateBackingStore");
1534 TimeTicks update_start = TimeTicks::Now();
1536 // Move the plugins if the view hasn't already been destroyed. Plugin moves
1537 // will not be re-issued, so must move them now, regardless of whether we
1538 // paint or not. MovePluginWindows attempts to move the plugin windows and
1539 // in the process could dispatch other window messages which could cause the
1540 // view to be destroyed.
1541 if (view_)
1542 view_->MovePluginWindows(params.plugin_window_moves);
1544 NotificationService::current()->Notify(
1545 NOTIFICATION_RENDER_WIDGET_HOST_DID_UPDATE_BACKING_STORE,
1546 Source<RenderWidgetHost>(this),
1547 NotificationService::NoDetails());
1549 // We don't need to update the view if the view is hidden. We must do this
1550 // early return after the ACK is sent, however, or the renderer will not send
1551 // us more data.
1552 if (is_hidden_)
1553 return;
1555 // If we got a resize ack, then perhaps we have another resize to send?
1556 bool is_resize_ack =
1557 ViewHostMsg_UpdateRect_Flags::is_resize_ack(params.flags);
1558 if (is_resize_ack)
1559 WasResized();
1561 // Log the time delta for processing a paint message.
1562 TimeTicks now = TimeTicks::Now();
1563 TimeDelta delta = now - update_start;
1564 UMA_HISTOGRAM_TIMES("MPArch.RWH_DidUpdateBackingStore", delta);
1567 void RenderWidgetHostImpl::OnQueueSyntheticGesture(
1568 const SyntheticGesturePacket& gesture_packet) {
1569 // Only allow untrustworthy gestures if explicitly enabled.
1570 if (!base::CommandLine::ForCurrentProcess()->HasSwitch(
1571 cc::switches::kEnableGpuBenchmarking)) {
1572 RecordAction(base::UserMetricsAction("BadMessageTerminate_RWH7"));
1573 GetProcess()->ReceivedBadMessage();
1574 return;
1577 QueueSyntheticGesture(
1578 SyntheticGesture::Create(*gesture_packet.gesture_params()),
1579 base::Bind(&RenderWidgetHostImpl::OnSyntheticGestureCompleted,
1580 weak_factory_.GetWeakPtr()));
1583 void RenderWidgetHostImpl::OnFocus() {
1584 // Only RenderViewHost can deal with that message.
1585 RecordAction(base::UserMetricsAction("BadMessageTerminate_RWH4"));
1586 GetProcess()->ReceivedBadMessage();
1589 void RenderWidgetHostImpl::OnBlur() {
1590 // Only RenderViewHost can deal with that message.
1591 RecordAction(base::UserMetricsAction("BadMessageTerminate_RWH5"));
1592 GetProcess()->ReceivedBadMessage();
1595 void RenderWidgetHostImpl::OnSetCursor(const WebCursor& cursor) {
1596 SetCursor(cursor);
1599 void RenderWidgetHostImpl::SetTouchEventEmulationEnabled(bool enabled) {
1600 if (enabled) {
1601 if (!touch_emulator_)
1602 touch_emulator_.reset(new TouchEmulator(this));
1603 touch_emulator_->Enable();
1604 } else {
1605 if (touch_emulator_)
1606 touch_emulator_->Disable();
1610 void RenderWidgetHostImpl::OnTextInputTypeChanged(
1611 ui::TextInputType type,
1612 ui::TextInputMode input_mode,
1613 bool can_compose_inline,
1614 int flags) {
1615 if (view_)
1616 view_->TextInputTypeChanged(type, input_mode, can_compose_inline, flags);
1619 void RenderWidgetHostImpl::OnImeCompositionRangeChanged(
1620 const gfx::Range& range,
1621 const std::vector<gfx::Rect>& character_bounds) {
1622 if (view_)
1623 view_->ImeCompositionRangeChanged(range, character_bounds);
1626 void RenderWidgetHostImpl::OnImeCancelComposition() {
1627 if (view_)
1628 view_->ImeCancelComposition();
1631 void RenderWidgetHostImpl::OnLockMouse(bool user_gesture,
1632 bool last_unlocked_by_target,
1633 bool privileged) {
1635 if (pending_mouse_lock_request_) {
1636 Send(new ViewMsg_LockMouse_ACK(routing_id_, false));
1637 return;
1638 } else if (IsMouseLocked()) {
1639 Send(new ViewMsg_LockMouse_ACK(routing_id_, true));
1640 return;
1643 pending_mouse_lock_request_ = true;
1644 if (privileged && allow_privileged_mouse_lock_) {
1645 // Directly approve to lock the mouse.
1646 GotResponseToLockMouseRequest(true);
1647 } else {
1648 RequestToLockMouse(user_gesture, last_unlocked_by_target);
1652 void RenderWidgetHostImpl::OnUnlockMouse() {
1653 RejectMouseLockOrUnlockIfNecessary();
1656 void RenderWidgetHostImpl::OnShowDisambiguationPopup(
1657 const gfx::Rect& rect_pixels,
1658 const gfx::Size& size,
1659 const cc::SharedBitmapId& id) {
1660 DCHECK(!rect_pixels.IsEmpty());
1661 DCHECK(!size.IsEmpty());
1663 scoped_ptr<cc::SharedBitmap> bitmap =
1664 HostSharedBitmapManager::current()->GetSharedBitmapFromId(size, id);
1665 if (!bitmap) {
1666 RecordAction(base::UserMetricsAction("BadMessageTerminate_RWH6"));
1667 GetProcess()->ReceivedBadMessage();
1668 return;
1671 DCHECK(bitmap->pixels());
1673 SkImageInfo info = SkImageInfo::MakeN32Premul(size.width(), size.height());
1674 SkBitmap zoomed_bitmap;
1675 zoomed_bitmap.installPixels(info, bitmap->pixels(), info.minRowBytes());
1677 // Note that |rect| is in coordinates of pixels relative to the window origin.
1678 // Aura-based systems will want to convert this to DIPs.
1679 if (view_)
1680 view_->ShowDisambiguationPopup(rect_pixels, zoomed_bitmap);
1682 // It is assumed that the disambiguation popup will make a copy of the
1683 // provided zoomed image, so we delete this one.
1684 zoomed_bitmap.setPixels(0);
1685 Send(new ViewMsg_ReleaseDisambiguationPopupBitmap(GetRoutingID(), id));
1688 #if defined(OS_WIN)
1689 void RenderWidgetHostImpl::OnWindowlessPluginDummyWindowCreated(
1690 gfx::NativeViewId dummy_activation_window) {
1691 HWND hwnd = reinterpret_cast<HWND>(dummy_activation_window);
1693 // This may happen as a result of a race condition when the plugin is going
1694 // away.
1695 wchar_t window_title[MAX_PATH + 1] = {0};
1696 if (!IsWindow(hwnd) ||
1697 !GetWindowText(hwnd, window_title, arraysize(window_title)) ||
1698 lstrcmpiW(window_title, kDummyActivationWindowName) != 0) {
1699 return;
1702 #if defined(USE_AURA)
1703 SetParent(hwnd,
1704 reinterpret_cast<HWND>(view_->GetParentForWindowlessPlugin()));
1705 #else
1706 SetParent(hwnd, reinterpret_cast<HWND>(GetNativeViewId()));
1707 #endif
1708 dummy_windows_for_activation_.push_back(hwnd);
1711 void RenderWidgetHostImpl::OnWindowlessPluginDummyWindowDestroyed(
1712 gfx::NativeViewId dummy_activation_window) {
1713 HWND hwnd = reinterpret_cast<HWND>(dummy_activation_window);
1714 std::list<HWND>::iterator i = dummy_windows_for_activation_.begin();
1715 for (; i != dummy_windows_for_activation_.end(); ++i) {
1716 if ((*i) == hwnd) {
1717 dummy_windows_for_activation_.erase(i);
1718 return;
1721 NOTREACHED() << "Unknown dummy window";
1723 #endif
1725 void RenderWidgetHostImpl::SetIgnoreInputEvents(bool ignore_input_events) {
1726 ignore_input_events_ = ignore_input_events;
1729 bool RenderWidgetHostImpl::KeyPressListenersHandleEvent(
1730 const NativeWebKeyboardEvent& event) {
1731 if (event.skip_in_browser || event.type != WebKeyboardEvent::RawKeyDown)
1732 return false;
1734 for (size_t i = 0; i < key_press_event_callbacks_.size(); i++) {
1735 size_t original_size = key_press_event_callbacks_.size();
1736 if (key_press_event_callbacks_[i].Run(event))
1737 return true;
1739 // Check whether the callback that just ran removed itself, in which case
1740 // the iterator needs to be decremented to properly account for the removal.
1741 size_t current_size = key_press_event_callbacks_.size();
1742 if (current_size != original_size) {
1743 DCHECK_EQ(original_size - 1, current_size);
1744 --i;
1748 return false;
1751 InputEventAckState RenderWidgetHostImpl::FilterInputEvent(
1752 const blink::WebInputEvent& event, const ui::LatencyInfo& latency_info) {
1753 // Don't ignore touch cancel events, since they may be sent while input
1754 // events are being ignored in order to keep the renderer from getting
1755 // confused about how many touches are active.
1756 if (IgnoreInputEvents() && event.type != WebInputEvent::TouchCancel)
1757 return INPUT_EVENT_ACK_STATE_NO_CONSUMER_EXISTS;
1759 if (!process_->HasConnection())
1760 return INPUT_EVENT_ACK_STATE_UNKNOWN;
1762 if (event.type == WebInputEvent::MouseDown)
1763 OnUserGesture();
1765 return view_ ? view_->FilterInputEvent(event)
1766 : INPUT_EVENT_ACK_STATE_NOT_CONSUMED;
1769 void RenderWidgetHostImpl::IncrementInFlightEventCount() {
1770 StartHangMonitorTimeout(
1771 TimeDelta::FromMilliseconds(hung_renderer_delay_ms_));
1772 increment_in_flight_event_count();
1775 void RenderWidgetHostImpl::DecrementInFlightEventCount() {
1776 if (decrement_in_flight_event_count() <= 0) {
1777 // Cancel pending hung renderer checks since the renderer is responsive.
1778 StopHangMonitorTimeout();
1779 } else {
1780 // The renderer is responsive, but there are in-flight events to wait for.
1781 RestartHangMonitorTimeout();
1785 void RenderWidgetHostImpl::OnHasTouchEventHandlers(bool has_handlers) {
1786 has_touch_handler_ = has_handlers;
1789 void RenderWidgetHostImpl::DidFlush() {
1790 if (synthetic_gesture_controller_)
1791 synthetic_gesture_controller_->OnDidFlushInput();
1792 if (view_)
1793 view_->OnDidFlushInput();
1796 void RenderWidgetHostImpl::DidOverscroll(const DidOverscrollParams& params) {
1797 if (view_)
1798 view_->DidOverscroll(params);
1801 void RenderWidgetHostImpl::OnKeyboardEventAck(
1802 const NativeWebKeyboardEvent& event,
1803 InputEventAckState ack_result) {
1804 #if defined(OS_MACOSX)
1805 if (!is_hidden() && view_ && view_->PostProcessEventForPluginIme(event))
1806 return;
1807 #endif
1809 // We only send unprocessed key event upwards if we are not hidden,
1810 // because the user has moved away from us and no longer expect any effect
1811 // of this key event.
1812 const bool processed = (INPUT_EVENT_ACK_STATE_CONSUMED == ack_result);
1813 if (delegate_ && !processed && !is_hidden() && !event.skip_in_browser) {
1814 delegate_->HandleKeyboardEvent(event);
1816 // WARNING: This RenderWidgetHostImpl can be deallocated at this point
1817 // (i.e. in the case of Ctrl+W, where the call to
1818 // HandleKeyboardEvent destroys this RenderWidgetHostImpl).
1822 void RenderWidgetHostImpl::OnWheelEventAck(
1823 const MouseWheelEventWithLatencyInfo& wheel_event,
1824 InputEventAckState ack_result) {
1825 latency_tracker_.OnInputEventAck(wheel_event.event, &wheel_event.latency);
1827 if (!is_hidden() && view_) {
1828 if (ack_result != INPUT_EVENT_ACK_STATE_CONSUMED &&
1829 delegate_->HandleWheelEvent(wheel_event.event)) {
1830 ack_result = INPUT_EVENT_ACK_STATE_CONSUMED;
1832 view_->WheelEventAck(wheel_event.event, ack_result);
1836 void RenderWidgetHostImpl::OnGestureEventAck(
1837 const GestureEventWithLatencyInfo& event,
1838 InputEventAckState ack_result) {
1839 latency_tracker_.OnInputEventAck(event.event, &event.latency);
1841 if (ack_result != INPUT_EVENT_ACK_STATE_CONSUMED) {
1842 if (delegate_->HandleGestureEvent(event.event))
1843 ack_result = INPUT_EVENT_ACK_STATE_CONSUMED;
1846 if (view_)
1847 view_->GestureEventAck(event.event, ack_result);
1850 void RenderWidgetHostImpl::OnTouchEventAck(
1851 const TouchEventWithLatencyInfo& event,
1852 InputEventAckState ack_result) {
1853 latency_tracker_.OnInputEventAck(event.event, &event.latency);
1855 if (touch_emulator_ &&
1856 touch_emulator_->HandleTouchEventAck(event.event, ack_result)) {
1857 return;
1860 if (view_)
1861 view_->ProcessAckedTouchEvent(event, ack_result);
1864 void RenderWidgetHostImpl::OnUnexpectedEventAck(UnexpectedEventAckType type) {
1865 if (type == BAD_ACK_MESSAGE) {
1866 RecordAction(base::UserMetricsAction("BadMessageTerminate_RWH2"));
1867 process_->ReceivedBadMessage();
1868 } else if (type == UNEXPECTED_EVENT_TYPE) {
1869 suppress_next_char_events_ = false;
1873 void RenderWidgetHostImpl::OnSyntheticGestureCompleted(
1874 SyntheticGesture::Result result) {
1875 Send(new InputMsg_SyntheticGestureCompleted(GetRoutingID()));
1878 bool RenderWidgetHostImpl::IgnoreInputEvents() const {
1879 return ignore_input_events_ || process_->IgnoreInputEvents();
1882 bool RenderWidgetHostImpl::ShouldForwardTouchEvent() const {
1883 // It's important that the emulator sees a complete native touch stream,
1884 // allowing it to perform touch filtering as appropriate.
1885 // TODO(dgozman): Remove when touch stream forwarding issues resolved, see
1886 // crbug.com/375940.
1887 if (touch_emulator_ && touch_emulator_->enabled())
1888 return true;
1890 return input_router_->ShouldForwardTouchEvent();
1893 void RenderWidgetHostImpl::StartUserGesture() {
1894 OnUserGesture();
1897 void RenderWidgetHostImpl::SetBackgroundOpaque(bool opaque) {
1898 Send(new ViewMsg_SetBackgroundOpaque(GetRoutingID(), opaque));
1901 void RenderWidgetHostImpl::SetEditCommandsForNextKeyEvent(
1902 const std::vector<EditCommand>& commands) {
1903 Send(new InputMsg_SetEditCommandsForNextKeyEvent(GetRoutingID(), commands));
1906 void RenderWidgetHostImpl::ExecuteEditCommand(const std::string& command,
1907 const std::string& value) {
1908 Send(new InputMsg_ExecuteEditCommand(GetRoutingID(), command, value));
1911 void RenderWidgetHostImpl::ScrollFocusedEditableNodeIntoRect(
1912 const gfx::Rect& rect) {
1913 Send(new InputMsg_ScrollFocusedEditableNodeIntoRect(GetRoutingID(), rect));
1916 void RenderWidgetHostImpl::MoveCaret(const gfx::Point& point) {
1917 Send(new InputMsg_MoveCaret(GetRoutingID(), point));
1920 bool RenderWidgetHostImpl::GotResponseToLockMouseRequest(bool allowed) {
1921 if (!allowed) {
1922 RejectMouseLockOrUnlockIfNecessary();
1923 return false;
1924 } else {
1925 if (!pending_mouse_lock_request_) {
1926 // This is possible, e.g., the plugin sends us an unlock request before
1927 // the user allows to lock to mouse.
1928 return false;
1931 pending_mouse_lock_request_ = false;
1932 if (!view_ || !view_->HasFocus()|| !view_->LockMouse()) {
1933 Send(new ViewMsg_LockMouse_ACK(routing_id_, false));
1934 return false;
1935 } else {
1936 Send(new ViewMsg_LockMouse_ACK(routing_id_, true));
1937 return true;
1942 // static
1943 void RenderWidgetHostImpl::SendSwapCompositorFrameAck(
1944 int32 route_id,
1945 uint32 output_surface_id,
1946 int renderer_host_id,
1947 const cc::CompositorFrameAck& ack) {
1948 RenderProcessHost* host = RenderProcessHost::FromID(renderer_host_id);
1949 if (!host)
1950 return;
1951 host->Send(new ViewMsg_SwapCompositorFrameAck(
1952 route_id, output_surface_id, ack));
1955 // static
1956 void RenderWidgetHostImpl::SendReclaimCompositorResources(
1957 int32 route_id,
1958 uint32 output_surface_id,
1959 int renderer_host_id,
1960 const cc::CompositorFrameAck& ack) {
1961 RenderProcessHost* host = RenderProcessHost::FromID(renderer_host_id);
1962 if (!host)
1963 return;
1964 host->Send(
1965 new ViewMsg_ReclaimCompositorResources(route_id, output_surface_id, ack));
1968 void RenderWidgetHostImpl::DelayedAutoResized() {
1969 gfx::Size new_size = new_auto_size_;
1970 // Clear the new_auto_size_ since the empty value is used as a flag to
1971 // indicate that no callback is in progress (i.e. without this line
1972 // DelayedAutoResized will not get called again).
1973 new_auto_size_.SetSize(0, 0);
1974 if (!auto_resize_enabled_)
1975 return;
1977 OnRenderAutoResized(new_size);
1980 void RenderWidgetHostImpl::DetachDelegate() {
1981 delegate_ = NULL;
1984 void RenderWidgetHostImpl::FrameSwapped(const ui::LatencyInfo& latency_info) {
1985 ui::LatencyInfo::LatencyComponent window_snapshot_component;
1986 if (latency_info.FindLatency(ui::WINDOW_OLD_SNAPSHOT_FRAME_NUMBER_COMPONENT,
1987 GetLatencyComponentId(),
1988 &window_snapshot_component)) {
1989 WindowOldSnapshotReachedScreen(
1990 static_cast<int>(window_snapshot_component.sequence_number));
1992 if (latency_info.FindLatency(ui::WINDOW_SNAPSHOT_FRAME_NUMBER_COMPONENT,
1993 GetLatencyComponentId(),
1994 &window_snapshot_component)) {
1995 int sequence_number = static_cast<int>(
1996 window_snapshot_component.sequence_number);
1997 #if defined(OS_MACOSX)
1998 // On Mac, when using CoreAnmation, there is a delay between when content
1999 // is drawn to the screen, and when the snapshot will actually pick up
2000 // that content. Insert a manual delay of 1/6th of a second (to simulate
2001 // 10 frames at 60 fps) before actually taking the snapshot.
2002 base::MessageLoop::current()->PostDelayedTask(
2003 FROM_HERE,
2004 base::Bind(&RenderWidgetHostImpl::WindowSnapshotReachedScreen,
2005 weak_factory_.GetWeakPtr(),
2006 sequence_number),
2007 base::TimeDelta::FromSecondsD(1. / 6));
2008 #else
2009 WindowSnapshotReachedScreen(sequence_number);
2010 #endif
2013 latency_tracker_.OnFrameSwapped(latency_info);
2016 void RenderWidgetHostImpl::DidReceiveRendererFrame() {
2017 view_->DidReceiveRendererFrame();
2020 void RenderWidgetHostImpl::WindowSnapshotAsyncCallback(
2021 int routing_id,
2022 int snapshot_id,
2023 gfx::Size snapshot_size,
2024 scoped_refptr<base::RefCountedBytes> png_data) {
2025 if (!png_data.get()) {
2026 std::vector<unsigned char> png_vector;
2027 Send(new ViewMsg_WindowSnapshotCompleted(
2028 routing_id, snapshot_id, gfx::Size(), png_vector));
2029 return;
2032 Send(new ViewMsg_WindowSnapshotCompleted(
2033 routing_id, snapshot_id, snapshot_size, png_data->data()));
2036 void RenderWidgetHostImpl::WindowOldSnapshotReachedScreen(int snapshot_id) {
2037 DCHECK(base::MessageLoopForUI::IsCurrent());
2039 std::vector<unsigned char> png;
2041 // This feature is behind the kEnableGpuBenchmarking command line switch
2042 // because it poses security concerns and should only be used for testing.
2043 const base::CommandLine& command_line =
2044 *base::CommandLine::ForCurrentProcess();
2045 if (!command_line.HasSwitch(cc::switches::kEnableGpuBenchmarking)) {
2046 Send(new ViewMsg_WindowSnapshotCompleted(
2047 GetRoutingID(), snapshot_id, gfx::Size(), png));
2048 return;
2051 gfx::Rect view_bounds = GetView()->GetViewBounds();
2052 gfx::Rect snapshot_bounds(view_bounds.size());
2053 gfx::Size snapshot_size = snapshot_bounds.size();
2055 if (ui::GrabViewSnapshot(
2056 GetView()->GetNativeView(), &png, snapshot_bounds)) {
2057 Send(new ViewMsg_WindowSnapshotCompleted(
2058 GetRoutingID(), snapshot_id, snapshot_size, png));
2059 return;
2062 ui::GrabViewSnapshotAsync(
2063 GetView()->GetNativeView(),
2064 snapshot_bounds,
2065 base::ThreadTaskRunnerHandle::Get(),
2066 base::Bind(&RenderWidgetHostImpl::WindowSnapshotAsyncCallback,
2067 weak_factory_.GetWeakPtr(),
2068 GetRoutingID(),
2069 snapshot_id,
2070 snapshot_size));
2073 void RenderWidgetHostImpl::WindowSnapshotReachedScreen(int snapshot_id) {
2074 DCHECK(base::MessageLoopForUI::IsCurrent());
2076 gfx::Rect view_bounds = GetView()->GetViewBounds();
2077 gfx::Rect snapshot_bounds(view_bounds.size());
2079 std::vector<unsigned char> png;
2080 if (ui::GrabViewSnapshot(
2081 GetView()->GetNativeView(), &png, snapshot_bounds)) {
2082 OnSnapshotDataReceived(snapshot_id, &png.front(), png.size());
2083 return;
2086 ui::GrabViewSnapshotAsync(
2087 GetView()->GetNativeView(),
2088 snapshot_bounds,
2089 base::ThreadTaskRunnerHandle::Get(),
2090 base::Bind(&RenderWidgetHostImpl::OnSnapshotDataReceivedAsync,
2091 weak_factory_.GetWeakPtr(),
2092 snapshot_id));
2095 void RenderWidgetHostImpl::OnSnapshotDataReceived(int snapshot_id,
2096 const unsigned char* data,
2097 size_t size) {
2098 // Any pending snapshots with a lower ID than the one received are considered
2099 // to be implicitly complete, and returned the same snapshot data.
2100 PendingSnapshotMap::iterator it = pending_browser_snapshots_.begin();
2101 while(it != pending_browser_snapshots_.end()) {
2102 if (it->first <= snapshot_id) {
2103 it->second.Run(data, size);
2104 pending_browser_snapshots_.erase(it++);
2105 } else {
2106 ++it;
2111 void RenderWidgetHostImpl::OnSnapshotDataReceivedAsync(
2112 int snapshot_id,
2113 scoped_refptr<base::RefCountedBytes> png_data) {
2114 if (png_data.get())
2115 OnSnapshotDataReceived(snapshot_id, png_data->front(), png_data->size());
2116 else
2117 OnSnapshotDataReceived(snapshot_id, NULL, 0);
2120 // static
2121 void RenderWidgetHostImpl::CompositorFrameDrawn(
2122 const std::vector<ui::LatencyInfo>& latency_info) {
2123 for (size_t i = 0; i < latency_info.size(); i++) {
2124 std::set<RenderWidgetHostImpl*> rwhi_set;
2125 for (ui::LatencyInfo::LatencyMap::const_iterator b =
2126 latency_info[i].latency_components.begin();
2127 b != latency_info[i].latency_components.end();
2128 ++b) {
2129 if (b->first.first == ui::INPUT_EVENT_LATENCY_BEGIN_RWH_COMPONENT ||
2130 b->first.first == ui::WINDOW_SNAPSHOT_FRAME_NUMBER_COMPONENT ||
2131 b->first.first == ui::WINDOW_OLD_SNAPSHOT_FRAME_NUMBER_COMPONENT ||
2132 b->first.first == ui::TAB_SHOW_COMPONENT) {
2133 // Matches with GetLatencyComponentId
2134 int routing_id = b->first.second & 0xffffffff;
2135 int process_id = (b->first.second >> 32) & 0xffffffff;
2136 RenderWidgetHost* rwh =
2137 RenderWidgetHost::FromID(process_id, routing_id);
2138 if (!rwh) {
2139 continue;
2141 RenderWidgetHostImpl* rwhi = RenderWidgetHostImpl::From(rwh);
2142 if (rwhi_set.insert(rwhi).second)
2143 rwhi->FrameSwapped(latency_info[i]);
2149 BrowserAccessibilityManager*
2150 RenderWidgetHostImpl::GetRootBrowserAccessibilityManager() {
2151 return delegate_ ? delegate_->GetRootBrowserAccessibilityManager() : NULL;
2154 BrowserAccessibilityManager*
2155 RenderWidgetHostImpl::GetOrCreateRootBrowserAccessibilityManager() {
2156 return delegate_ ?
2157 delegate_->GetOrCreateRootBrowserAccessibilityManager() : NULL;
2160 #if defined(OS_WIN)
2161 gfx::NativeViewAccessible
2162 RenderWidgetHostImpl::GetParentNativeViewAccessible() {
2163 return delegate_ ? delegate_->GetParentNativeViewAccessible() : NULL;
2165 #endif
2167 SkColorType RenderWidgetHostImpl::PreferredReadbackFormat() {
2168 if (view_)
2169 return view_->PreferredReadbackFormat();
2170 return kN32_SkColorType;
2173 } // namespace content