ozone: evdev: Sync caps lock LED state to evdev
[chromium-blink-merge.git] / content / browser / renderer_host / render_widget_host_impl.cc
blobf1cbc2a9bc2bad989f3eab13ed7a24ebd2fd4259
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/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/frame_metadata_util.h"
36 #include "content/browser/renderer_host/input/input_router_config_helper.h"
37 #include "content/browser/renderer_host/input/input_router_impl.h"
38 #include "content/browser/renderer_host/input/synthetic_gesture.h"
39 #include "content/browser/renderer_host/input/synthetic_gesture_controller.h"
40 #include "content/browser/renderer_host/input/synthetic_gesture_target.h"
41 #include "content/browser/renderer_host/input/timeout_monitor.h"
42 #include "content/browser/renderer_host/input/touch_emulator.h"
43 #include "content/browser/renderer_host/render_process_host_impl.h"
44 #include "content/browser/renderer_host/render_view_host_impl.h"
45 #include "content/browser/renderer_host/render_widget_helper.h"
46 #include "content/browser/renderer_host/render_widget_host_delegate.h"
47 #include "content/browser/renderer_host/render_widget_host_view_base.h"
48 #include "content/browser/renderer_host/render_widget_resize_helper.h"
49 #include "content/common/content_constants_internal.h"
50 #include "content/common/cursors/webcursor.h"
51 #include "content/common/frame_messages.h"
52 #include "content/common/gpu/gpu_messages.h"
53 #include "content/common/host_shared_bitmap_manager.h"
54 #include "content/common/input_messages.h"
55 #include "content/common/view_messages.h"
56 #include "content/public/browser/native_web_keyboard_event.h"
57 #include "content/public/browser/notification_service.h"
58 #include "content/public/browser/notification_types.h"
59 #include "content/public/browser/render_widget_host_iterator.h"
60 #include "content/public/browser/user_metrics.h"
61 #include "content/public/common/content_constants.h"
62 #include "content/public/common/content_switches.h"
63 #include "content/public/common/result_codes.h"
64 #include "content/public/common/web_preferences.h"
65 #include "gpu/GLES2/gl2extchromium.h"
66 #include "gpu/command_buffer/service/gpu_switches.h"
67 #include "skia/ext/image_operations.h"
68 #include "skia/ext/platform_canvas.h"
69 #include "third_party/WebKit/public/web/WebCompositionUnderline.h"
70 #include "ui/events/event.h"
71 #include "ui/events/keycodes/keyboard_codes.h"
72 #include "ui/gfx/geometry/size_conversions.h"
73 #include "ui/gfx/geometry/vector2d_conversions.h"
74 #include "ui/gfx/skbitmap_operations.h"
75 #include "ui/snapshot/snapshot.h"
77 #if defined(OS_WIN)
78 #include "content/common/plugin_constants_win.h"
79 #endif
81 using base::Time;
82 using base::TimeDelta;
83 using base::TimeTicks;
84 using blink::WebGestureEvent;
85 using blink::WebInputEvent;
86 using blink::WebKeyboardEvent;
87 using blink::WebMouseEvent;
88 using blink::WebMouseWheelEvent;
89 using blink::WebTextDirection;
91 namespace content {
92 namespace {
94 bool g_check_for_pending_resize_ack = true;
96 typedef std::pair<int32, int32> RenderWidgetHostID;
97 typedef base::hash_map<RenderWidgetHostID, RenderWidgetHostImpl*>
98 RoutingIDWidgetMap;
99 base::LazyInstance<RoutingIDWidgetMap> g_routing_id_widget_map =
100 LAZY_INSTANCE_INITIALIZER;
102 int GetInputRouterViewFlagsFromCompositorFrameMetadata(
103 const cc::CompositorFrameMetadata metadata) {
104 int view_flags = InputRouter::VIEW_FLAGS_NONE;
106 if (metadata.min_page_scale_factor == metadata.max_page_scale_factor)
107 view_flags |= InputRouter::FIXED_PAGE_SCALE;
109 const float window_width_dip = std::ceil(
110 metadata.page_scale_factor * metadata.scrollable_viewport_size.width());
111 const float content_width_css = metadata.root_layer_size.width();
112 if (content_width_css <= window_width_dip)
113 view_flags |= InputRouter::MOBILE_VIEWPORT;
115 return view_flags;
118 // Implements the RenderWidgetHostIterator interface. It keeps a list of
119 // RenderWidgetHosts, and makes sure it returns a live RenderWidgetHost at each
120 // iteration (or NULL if there isn't any left).
121 class RenderWidgetHostIteratorImpl : public RenderWidgetHostIterator {
122 public:
123 RenderWidgetHostIteratorImpl()
124 : current_index_(0) {
127 ~RenderWidgetHostIteratorImpl() override {}
129 void Add(RenderWidgetHost* host) {
130 hosts_.push_back(RenderWidgetHostID(host->GetProcess()->GetID(),
131 host->GetRoutingID()));
134 // RenderWidgetHostIterator:
135 RenderWidgetHost* GetNextHost() override {
136 RenderWidgetHost* host = NULL;
137 while (current_index_ < hosts_.size() && !host) {
138 RenderWidgetHostID id = hosts_[current_index_];
139 host = RenderWidgetHost::FromID(id.first, id.second);
140 ++current_index_;
142 return host;
145 private:
146 std::vector<RenderWidgetHostID> hosts_;
147 size_t current_index_;
149 DISALLOW_COPY_AND_ASSIGN(RenderWidgetHostIteratorImpl);
152 } // namespace
154 ///////////////////////////////////////////////////////////////////////////////
155 // RenderWidgetHostImpl
157 RenderWidgetHostImpl::RenderWidgetHostImpl(RenderWidgetHostDelegate* delegate,
158 RenderProcessHost* process,
159 int routing_id,
160 bool hidden)
161 : view_(NULL),
162 renderer_initialized_(false),
163 hung_renderer_delay_ms_(kHungRendererDelayMs),
164 delegate_(delegate),
165 process_(process),
166 routing_id_(routing_id),
167 surface_id_(0),
168 is_loading_(false),
169 is_hidden_(hidden),
170 repaint_ack_pending_(false),
171 resize_ack_pending_(false),
172 screen_info_out_of_date_(false),
173 auto_resize_enabled_(false),
174 waiting_for_screen_rects_ack_(false),
175 needs_repainting_on_restore_(false),
176 is_unresponsive_(false),
177 in_flight_event_count_(0),
178 in_get_backing_store_(false),
179 ignore_input_events_(false),
180 input_method_active_(false),
181 text_direction_updated_(false),
182 text_direction_(blink::WebTextDirectionLeftToRight),
183 text_direction_canceled_(false),
184 suppress_next_char_events_(false),
185 pending_mouse_lock_request_(false),
186 allow_privileged_mouse_lock_(false),
187 has_touch_handler_(false),
188 next_browser_snapshot_id_(1),
189 owned_by_render_frame_host_(false),
190 is_focused_(false),
191 weak_factory_(this) {
192 CHECK(delegate_);
193 if (routing_id_ == MSG_ROUTING_NONE) {
194 routing_id_ = process_->GetNextRoutingID();
195 surface_id_ = GpuSurfaceTracker::Get()->AddSurfaceForRenderer(
196 process_->GetID(),
197 routing_id_);
198 } else {
199 // TODO(piman): This is a O(N) lookup, where we could forward the
200 // information from the RenderWidgetHelper. The problem is that doing so
201 // currently leaks outside of content all the way to chrome classes, and
202 // would be a layering violation. Since we don't expect more than a few
203 // hundreds of RWH, this seems acceptable. Revisit if performance become a
204 // problem, for example by tracking in the RenderWidgetHelper the routing id
205 // (and surface id) that have been created, but whose RWH haven't yet.
206 surface_id_ = GpuSurfaceTracker::Get()->LookupSurfaceForRenderer(
207 process_->GetID(),
208 routing_id_);
209 DCHECK(surface_id_);
212 std::pair<RoutingIDWidgetMap::iterator, bool> result =
213 g_routing_id_widget_map.Get().insert(std::make_pair(
214 RenderWidgetHostID(process->GetID(), routing_id_), this));
215 CHECK(result.second) << "Inserting a duplicate item!";
216 process_->AddRoute(routing_id_, this);
218 // If we're initially visible, tell the process host that we're alive.
219 // Otherwise we'll notify the process host when we are first shown.
220 if (!hidden)
221 process_->WidgetRestored();
223 latency_tracker_.Initialize(routing_id_, GetProcess()->GetID());
225 input_router_.reset(new InputRouterImpl(
226 process_, this, this, routing_id_, GetInputRouterConfigForPlatform()));
228 touch_emulator_.reset();
230 RenderViewHostImpl* rvh = static_cast<RenderViewHostImpl*>(
231 IsRenderView() ? RenderViewHost::From(this) : NULL);
232 if (BrowserPluginGuest::IsGuest(rvh) ||
233 !base::CommandLine::ForCurrentProcess()->HasSwitch(
234 switches::kDisableHangMonitor)) {
235 hang_monitor_timeout_.reset(new TimeoutMonitor(
236 base::Bind(&RenderWidgetHostImpl::RendererIsUnresponsive,
237 weak_factory_.GetWeakPtr())));
241 RenderWidgetHostImpl::~RenderWidgetHostImpl() {
242 if (view_weak_)
243 view_weak_->RenderWidgetHostGone();
244 SetView(NULL);
246 GpuSurfaceTracker::Get()->RemoveSurface(surface_id_);
247 surface_id_ = 0;
249 process_->RemoveRoute(routing_id_);
250 g_routing_id_widget_map.Get().erase(
251 RenderWidgetHostID(process_->GetID(), routing_id_));
253 if (delegate_)
254 delegate_->RenderWidgetDeleted(this);
257 // static
258 RenderWidgetHost* RenderWidgetHost::FromID(
259 int32 process_id,
260 int32 routing_id) {
261 return RenderWidgetHostImpl::FromID(process_id, routing_id);
264 // static
265 RenderWidgetHostImpl* RenderWidgetHostImpl::FromID(
266 int32 process_id,
267 int32 routing_id) {
268 DCHECK_CURRENTLY_ON(BrowserThread::UI);
269 RoutingIDWidgetMap* widgets = g_routing_id_widget_map.Pointer();
270 RoutingIDWidgetMap::iterator it = widgets->find(
271 RenderWidgetHostID(process_id, routing_id));
272 return it == widgets->end() ? NULL : it->second;
275 // static
276 scoped_ptr<RenderWidgetHostIterator> RenderWidgetHost::GetRenderWidgetHosts() {
277 RenderWidgetHostIteratorImpl* hosts = new RenderWidgetHostIteratorImpl();
278 RoutingIDWidgetMap* widgets = g_routing_id_widget_map.Pointer();
279 for (RoutingIDWidgetMap::const_iterator it = widgets->begin();
280 it != widgets->end();
281 ++it) {
282 RenderWidgetHost* widget = it->second;
284 if (!widget->IsRenderView()) {
285 hosts->Add(widget);
286 continue;
289 // Add only active RenderViewHosts.
290 RenderViewHost* rvh = RenderViewHost::From(widget);
291 if (static_cast<RenderViewHostImpl*>(rvh)->is_active())
292 hosts->Add(widget);
295 return scoped_ptr<RenderWidgetHostIterator>(hosts);
298 // static
299 scoped_ptr<RenderWidgetHostIterator>
300 RenderWidgetHostImpl::GetAllRenderWidgetHosts() {
301 RenderWidgetHostIteratorImpl* hosts = new RenderWidgetHostIteratorImpl();
302 RoutingIDWidgetMap* widgets = g_routing_id_widget_map.Pointer();
303 for (RoutingIDWidgetMap::const_iterator it = widgets->begin();
304 it != widgets->end();
305 ++it) {
306 hosts->Add(it->second);
309 return scoped_ptr<RenderWidgetHostIterator>(hosts);
312 // static
313 RenderWidgetHostImpl* RenderWidgetHostImpl::From(RenderWidgetHost* rwh) {
314 return rwh->AsRenderWidgetHostImpl();
317 void RenderWidgetHostImpl::SetView(RenderWidgetHostViewBase* view) {
318 if (view)
319 view_weak_ = view->GetWeakPtr();
320 else
321 view_weak_.reset();
322 view_ = view;
324 GpuSurfaceTracker::Get()->SetSurfaceHandle(
325 surface_id_, GetCompositingSurface());
327 synthetic_gesture_controller_.reset();
330 RenderProcessHost* RenderWidgetHostImpl::GetProcess() const {
331 return process_;
334 int RenderWidgetHostImpl::GetRoutingID() const {
335 return routing_id_;
338 RenderWidgetHostView* RenderWidgetHostImpl::GetView() const {
339 return view_;
342 RenderWidgetHostImpl* RenderWidgetHostImpl::AsRenderWidgetHostImpl() {
343 return this;
346 gfx::NativeViewId RenderWidgetHostImpl::GetNativeViewId() const {
347 if (view_)
348 return view_->GetNativeViewId();
349 return 0;
352 gfx::GLSurfaceHandle RenderWidgetHostImpl::GetCompositingSurface() {
353 if (view_)
354 return view_->GetCompositingSurface();
355 return gfx::GLSurfaceHandle();
358 void RenderWidgetHostImpl::ResetSizeAndRepaintPendingFlags() {
359 resize_ack_pending_ = false;
360 if (repaint_ack_pending_) {
361 TRACE_EVENT_ASYNC_END0(
362 "renderer_host", "RenderWidgetHostImpl::repaint_ack_pending_", this);
364 repaint_ack_pending_ = false;
365 if (old_resize_params_)
366 old_resize_params_->new_size = gfx::Size();
369 void RenderWidgetHostImpl::SendScreenRects() {
370 if (!renderer_initialized_ || waiting_for_screen_rects_ack_)
371 return;
373 if (is_hidden_) {
374 // On GTK, this comes in for backgrounded tabs. Ignore, to match what
375 // happens on Win & Mac, and when the view is shown it'll call this again.
376 return;
379 if (!view_)
380 return;
382 last_view_screen_rect_ = view_->GetViewBounds();
383 last_window_screen_rect_ = view_->GetBoundsInRootWindow();
384 Send(new ViewMsg_UpdateScreenRects(
385 GetRoutingID(), last_view_screen_rect_, last_window_screen_rect_));
386 if (delegate_)
387 delegate_->DidSendScreenRects(this);
388 waiting_for_screen_rects_ack_ = true;
391 void RenderWidgetHostImpl::SuppressNextCharEvents() {
392 suppress_next_char_events_ = true;
395 void RenderWidgetHostImpl::FlushInput() {
396 input_router_->Flush();
397 if (synthetic_gesture_controller_)
398 synthetic_gesture_controller_->Flush(base::TimeTicks::Now());
401 void RenderWidgetHostImpl::SetNeedsFlush() {
402 if (view_)
403 view_->OnSetNeedsFlushInput();
406 void RenderWidgetHostImpl::Init() {
407 DCHECK(process_->HasConnection());
409 renderer_initialized_ = true;
411 GpuSurfaceTracker::Get()->SetSurfaceHandle(
412 surface_id_, GetCompositingSurface());
414 // Send the ack along with the information on placement.
415 Send(new ViewMsg_CreatingNew_ACK(routing_id_));
416 GetProcess()->ResumeRequestsForView(routing_id_);
418 WasResized();
421 void RenderWidgetHostImpl::InitForFrame() {
422 DCHECK(process_->HasConnection());
423 renderer_initialized_ = true;
426 void RenderWidgetHostImpl::Shutdown() {
427 RejectMouseLockOrUnlockIfNecessary();
429 if (process_->HasConnection()) {
430 // Tell the renderer object to close.
431 bool rv = Send(new ViewMsg_Close(routing_id_));
432 DCHECK(rv);
435 Destroy();
438 bool RenderWidgetHostImpl::IsLoading() const {
439 return is_loading_;
442 bool RenderWidgetHostImpl::IsRenderView() const {
443 return false;
446 bool RenderWidgetHostImpl::OnMessageReceived(const IPC::Message &msg) {
447 bool handled = true;
448 IPC_BEGIN_MESSAGE_MAP(RenderWidgetHostImpl, msg)
449 IPC_MESSAGE_HANDLER(FrameHostMsg_RenderProcessGone, OnRenderProcessGone)
450 IPC_MESSAGE_HANDLER(InputHostMsg_QueueSyntheticGesture,
451 OnQueueSyntheticGesture)
452 IPC_MESSAGE_HANDLER(InputHostMsg_ImeCancelComposition,
453 OnImeCancelComposition)
454 IPC_MESSAGE_HANDLER(ViewHostMsg_RenderViewReady, OnRenderViewReady)
455 IPC_MESSAGE_HANDLER(ViewHostMsg_Close, OnClose)
456 IPC_MESSAGE_HANDLER(ViewHostMsg_UpdateScreenRects_ACK,
457 OnUpdateScreenRectsAck)
458 IPC_MESSAGE_HANDLER(ViewHostMsg_RequestMove, OnRequestMove)
459 IPC_MESSAGE_HANDLER(ViewHostMsg_SetTooltipText, OnSetTooltipText)
460 IPC_MESSAGE_HANDLER_GENERIC(ViewHostMsg_SwapCompositorFrame,
461 OnSwapCompositorFrame(msg))
462 IPC_MESSAGE_HANDLER(ViewHostMsg_DidStopFlinging, OnFlingingStopped)
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 is_hidden_ = true;
516 // Don't bother reporting hung state when we aren't active.
517 StopHangMonitorTimeout();
519 // If we have a renderer, then inform it that we are being hidden so it can
520 // reduce its resource utilization.
521 Send(new ViewMsg_WasHidden(routing_id_));
523 // Tell the RenderProcessHost we were hidden.
524 process_->WidgetHidden();
526 bool is_visible = false;
527 NotificationService::current()->Notify(
528 NOTIFICATION_RENDER_WIDGET_VISIBILITY_CHANGED,
529 Source<RenderWidgetHost>(this),
530 Details<bool>(&is_visible));
533 void RenderWidgetHostImpl::WasShown(const ui::LatencyInfo& latency_info) {
534 if (!is_hidden_)
535 return;
536 is_hidden_ = false;
538 SendScreenRects();
540 // Always repaint on restore.
541 bool needs_repainting = true;
542 needs_repainting_on_restore_ = false;
543 Send(new ViewMsg_WasShown(routing_id_, needs_repainting, latency_info));
545 process_->WidgetRestored();
547 bool is_visible = true;
548 NotificationService::current()->Notify(
549 NOTIFICATION_RENDER_WIDGET_VISIBILITY_CHANGED,
550 Source<RenderWidgetHost>(this),
551 Details<bool>(&is_visible));
553 // It's possible for our size to be out of sync with the renderer. The
554 // following is one case that leads to this:
555 // 1. WasResized -> Send ViewMsg_Resize to render
556 // 2. WasResized -> do nothing as resize_ack_pending_ is true
557 // 3. WasHidden
558 // 4. OnUpdateRect from (1) processed. Does NOT invoke WasResized as view
559 // is hidden. Now renderer/browser out of sync with what they think size
560 // is.
561 // By invoking WasResized the renderer is updated as necessary. WasResized
562 // does nothing if the sizes are already in sync.
564 // TODO: ideally ViewMsg_WasShown would take a size. This way, the renderer
565 // could handle both the restore and resize at once. This isn't that big a
566 // deal as RenderWidget::WasShown delays updating, so that the resize from
567 // WasResized is usually processed before the renderer is painted.
568 WasResized();
571 bool RenderWidgetHostImpl::GetResizeParams(
572 ViewMsg_Resize_Params* resize_params) {
573 *resize_params = ViewMsg_Resize_Params();
575 if (!screen_info_) {
576 screen_info_.reset(new blink::WebScreenInfo);
577 GetWebScreenInfo(screen_info_.get());
579 resize_params->screen_info = *screen_info_;
580 resize_params->resizer_rect = GetRootWindowResizerRect();
582 if (view_) {
583 resize_params->new_size = view_->GetRequestedRendererSize();
584 resize_params->physical_backing_size = view_->GetPhysicalBackingSize();
585 resize_params->top_controls_height = view_->GetTopControlsHeight();
586 resize_params->top_controls_shrink_blink_size =
587 view_->DoTopControlsShrinkBlinkSize();
588 resize_params->visible_viewport_size = view_->GetVisibleViewportSize();
589 resize_params->is_fullscreen = IsFullscreen();
592 const bool size_changed =
593 !old_resize_params_ ||
594 old_resize_params_->new_size != resize_params->new_size ||
595 (old_resize_params_->physical_backing_size.IsEmpty() &&
596 !resize_params->physical_backing_size.IsEmpty());
597 bool dirty =
598 size_changed || screen_info_out_of_date_ ||
599 old_resize_params_->physical_backing_size !=
600 resize_params->physical_backing_size ||
601 old_resize_params_->is_fullscreen != resize_params->is_fullscreen ||
602 old_resize_params_->top_controls_height !=
603 resize_params->top_controls_height ||
604 old_resize_params_->top_controls_shrink_blink_size !=
605 resize_params->top_controls_shrink_blink_size ||
606 old_resize_params_->visible_viewport_size !=
607 resize_params->visible_viewport_size;
609 // We don't expect to receive an ACK when the requested size or the physical
610 // backing size is empty, or when the main viewport size didn't change.
611 resize_params->needs_resize_ack =
612 g_check_for_pending_resize_ack && !resize_params->new_size.IsEmpty() &&
613 !resize_params->physical_backing_size.IsEmpty() && size_changed;
615 return dirty;
618 void RenderWidgetHostImpl::SetInitialRenderSizeParams(
619 const ViewMsg_Resize_Params& resize_params) {
620 resize_ack_pending_ = resize_params.needs_resize_ack;
622 old_resize_params_ =
623 make_scoped_ptr(new ViewMsg_Resize_Params(resize_params));
626 void RenderWidgetHostImpl::WasResized() {
627 // Skip if the |delegate_| has already been detached because
628 // it's web contents is being deleted.
629 if (resize_ack_pending_ || !process_->HasConnection() || !view_ ||
630 !renderer_initialized_ || auto_resize_enabled_ || !delegate_) {
631 return;
634 scoped_ptr<ViewMsg_Resize_Params> params(new ViewMsg_Resize_Params);
635 if (!GetResizeParams(params.get()))
636 return;
638 bool width_changed =
639 !old_resize_params_ ||
640 old_resize_params_->new_size.width() != params->new_size.width();
641 if (Send(new ViewMsg_Resize(routing_id_, *params))) {
642 resize_ack_pending_ = params->needs_resize_ack;
643 old_resize_params_.swap(params);
646 if (delegate_)
647 delegate_->RenderWidgetWasResized(this, width_changed);
650 void RenderWidgetHostImpl::ResizeRectChanged(const gfx::Rect& new_rect) {
651 Send(new ViewMsg_ChangeResizeRect(routing_id_, new_rect));
654 void RenderWidgetHostImpl::GotFocus() {
655 Focus();
656 if (delegate_)
657 delegate_->RenderWidgetGotFocus(this);
660 void RenderWidgetHostImpl::Focus() {
661 is_focused_ = true;
663 Send(new InputMsg_SetFocus(routing_id_, true));
666 void RenderWidgetHostImpl::Blur() {
667 is_focused_ = false;
669 // If there is a pending mouse lock request, we don't want to reject it at
670 // this point. The user can switch focus back to this view and approve the
671 // request later.
672 if (IsMouseLocked())
673 view_->UnlockMouse();
675 if (touch_emulator_)
676 touch_emulator_->CancelTouch();
678 Send(new InputMsg_SetFocus(routing_id_, false));
681 void RenderWidgetHostImpl::LostCapture() {
682 if (touch_emulator_)
683 touch_emulator_->CancelTouch();
685 Send(new InputMsg_MouseCaptureLost(routing_id_));
688 void RenderWidgetHostImpl::SetActive(bool active) {
689 Send(new ViewMsg_SetActive(routing_id_, active));
692 void RenderWidgetHostImpl::LostMouseLock() {
693 Send(new ViewMsg_MouseLockLost(routing_id_));
696 void RenderWidgetHostImpl::ViewDestroyed() {
697 RejectMouseLockOrUnlockIfNecessary();
699 // TODO(evanm): tracking this may no longer be necessary;
700 // eliminate this function if so.
701 SetView(NULL);
704 void RenderWidgetHostImpl::CopyFromBackingStore(
705 const gfx::Rect& src_subrect,
706 const gfx::Size& accelerated_dst_size,
707 ReadbackRequestCallback& callback,
708 const SkColorType color_type) {
709 if (view_) {
710 TRACE_EVENT0("browser",
711 "RenderWidgetHostImpl::CopyFromBackingStore::FromCompositingSurface");
712 gfx::Rect accelerated_copy_rect = src_subrect.IsEmpty() ?
713 gfx::Rect(view_->GetViewBounds().size()) : src_subrect;
714 view_->CopyFromCompositingSurface(
715 accelerated_copy_rect, accelerated_dst_size, callback, color_type);
716 return;
719 callback.Run(SkBitmap(), content::READBACK_FAILED);
722 bool RenderWidgetHostImpl::CanCopyFromBackingStore() {
723 if (view_)
724 return view_->IsSurfaceAvailableForCopy();
725 return false;
728 #if defined(OS_ANDROID)
729 void RenderWidgetHostImpl::LockBackingStore() {
730 if (view_)
731 view_->LockCompositingSurface();
734 void RenderWidgetHostImpl::UnlockBackingStore() {
735 if (view_)
736 view_->UnlockCompositingSurface();
738 #endif
740 #if defined(OS_MACOSX)
741 void RenderWidgetHostImpl::PauseForPendingResizeOrRepaints() {
742 TRACE_EVENT0("browser",
743 "RenderWidgetHostImpl::PauseForPendingResizeOrRepaints");
745 if (!CanPauseForPendingResizeOrRepaints())
746 return;
748 WaitForSurface();
751 bool RenderWidgetHostImpl::CanPauseForPendingResizeOrRepaints() {
752 // Do not pause if the view is hidden.
753 if (is_hidden())
754 return false;
756 // Do not pause if there is not a paint or resize already coming.
757 if (!repaint_ack_pending_ && !resize_ack_pending_)
758 return false;
760 return true;
763 void RenderWidgetHostImpl::WaitForSurface() {
764 // How long to (synchronously) wait for the renderer to respond with a
765 // new frame when our current frame doesn't exist or is the wrong size.
766 // This timeout impacts the "choppiness" of our window resize.
767 const int kPaintMsgTimeoutMS = 50;
769 if (!view_)
770 return;
772 // The view_size will be current_size_ for auto-sized views and otherwise the
773 // size of the view_. (For auto-sized views, current_size_ is updated during
774 // UpdateRect messages.)
775 gfx::Size view_size = current_size_;
776 if (!auto_resize_enabled_) {
777 // Get the desired size from the current view bounds.
778 gfx::Rect view_rect = view_->GetViewBounds();
779 if (view_rect.IsEmpty())
780 return;
781 view_size = view_rect.size();
784 TRACE_EVENT2("renderer_host",
785 "RenderWidgetHostImpl::WaitForSurface",
786 "width",
787 base::IntToString(view_size.width()),
788 "height",
789 base::IntToString(view_size.height()));
791 // We should not be asked to paint while we are hidden. If we are hidden,
792 // then it means that our consumer failed to call WasShown.
793 DCHECK(!is_hidden_) << "WaitForSurface called while hidden!";
795 // We should never be called recursively; this can theoretically lead to
796 // infinite recursion and almost certainly leads to lower performance.
797 DCHECK(!in_get_backing_store_) << "WaitForSurface called recursively!";
798 base::AutoReset<bool> auto_reset_in_get_backing_store(
799 &in_get_backing_store_, true);
801 // We might have a surface that we can use already.
802 if (view_->HasAcceleratedSurface(view_size))
803 return;
805 // Request that the renderer produce a frame of the right size, if it
806 // hasn't been requested already.
807 if (!repaint_ack_pending_ && !resize_ack_pending_) {
808 repaint_start_time_ = TimeTicks::Now();
809 repaint_ack_pending_ = true;
810 TRACE_EVENT_ASYNC_BEGIN0(
811 "renderer_host", "RenderWidgetHostImpl::repaint_ack_pending_", this);
812 Send(new ViewMsg_Repaint(routing_id_, view_size));
815 // Pump a nested message loop until we time out or get a frame of the right
816 // size.
817 TimeTicks start_time = TimeTicks::Now();
818 TimeDelta time_left = TimeDelta::FromMilliseconds(kPaintMsgTimeoutMS);
819 TimeTicks timeout_time = start_time + time_left;
820 while (1) {
821 TRACE_EVENT0("renderer_host", "WaitForSurface::WaitForSingleTaskToRun");
822 if (RenderWidgetResizeHelper::Get()->WaitForSingleTaskToRun(time_left)) {
823 // For auto-resized views, current_size_ determines the view_size and it
824 // may have changed during the handling of an UpdateRect message.
825 if (auto_resize_enabled_)
826 view_size = current_size_;
827 if (view_->HasAcceleratedSurface(view_size))
828 break;
830 time_left = timeout_time - TimeTicks::Now();
831 if (time_left <= TimeDelta::FromSeconds(0)) {
832 TRACE_EVENT0("renderer_host", "WaitForSurface::Timeout");
833 break;
837 UMA_HISTOGRAM_CUSTOM_TIMES("OSX.RendererHost.SurfaceWaitTime",
838 TimeTicks::Now() - start_time,
839 TimeDelta::FromMilliseconds(1),
840 TimeDelta::FromMilliseconds(200), 50);
842 #endif
844 bool RenderWidgetHostImpl::ScheduleComposite() {
845 if (is_hidden_ || current_size_.IsEmpty() || repaint_ack_pending_ ||
846 resize_ack_pending_) {
847 return false;
850 // Send out a request to the renderer to paint the view if required.
851 repaint_start_time_ = TimeTicks::Now();
852 repaint_ack_pending_ = true;
853 TRACE_EVENT_ASYNC_BEGIN0(
854 "renderer_host", "RenderWidgetHostImpl::repaint_ack_pending_", this);
855 Send(new ViewMsg_Repaint(routing_id_, current_size_));
856 return true;
859 void RenderWidgetHostImpl::StartHangMonitorTimeout(base::TimeDelta delay) {
860 if (hang_monitor_timeout_)
861 hang_monitor_timeout_->Start(delay);
864 void RenderWidgetHostImpl::RestartHangMonitorTimeout() {
865 if (hang_monitor_timeout_)
866 hang_monitor_timeout_->Restart(
867 base::TimeDelta::FromMilliseconds(hung_renderer_delay_ms_));
870 void RenderWidgetHostImpl::StopHangMonitorTimeout() {
871 if (hang_monitor_timeout_)
872 hang_monitor_timeout_->Stop();
873 RendererIsResponsive();
876 void RenderWidgetHostImpl::ForwardMouseEvent(const WebMouseEvent& mouse_event) {
877 ForwardMouseEventWithLatencyInfo(mouse_event, ui::LatencyInfo());
880 void RenderWidgetHostImpl::ForwardMouseEventWithLatencyInfo(
881 const blink::WebMouseEvent& mouse_event,
882 const ui::LatencyInfo& ui_latency) {
883 TRACE_EVENT2("input", "RenderWidgetHostImpl::ForwardMouseEvent",
884 "x", mouse_event.x, "y", mouse_event.y);
886 for (size_t i = 0; i < mouse_event_callbacks_.size(); ++i) {
887 if (mouse_event_callbacks_[i].Run(mouse_event))
888 return;
891 if (IgnoreInputEvents())
892 return;
894 if (touch_emulator_ && touch_emulator_->HandleMouseEvent(mouse_event))
895 return;
897 MouseEventWithLatencyInfo mouse_with_latency(mouse_event, ui_latency);
898 latency_tracker_.OnInputEvent(mouse_event, &mouse_with_latency.latency);
899 input_router_->SendMouseEvent(mouse_with_latency);
901 // Pass mouse state to gpu service if the subscribe uniform
902 // extension is enabled.
903 if (process_->SubscribeUniformEnabled()) {
904 gpu::ValueState state;
905 state.int_value[0] = mouse_event.x;
906 state.int_value[1] = mouse_event.y;
907 // TODO(orglofch) Separate the mapping of pending value states to the
908 // Gpu Service to be per RWH not per process
909 process_->SendUpdateValueState(GL_MOUSE_POSITION_CHROMIUM, state);
913 void RenderWidgetHostImpl::OnPointerEventActivate() {
916 void RenderWidgetHostImpl::ForwardWheelEvent(
917 const WebMouseWheelEvent& wheel_event) {
918 ForwardWheelEventWithLatencyInfo(wheel_event, ui::LatencyInfo());
921 void RenderWidgetHostImpl::ForwardWheelEventWithLatencyInfo(
922 const blink::WebMouseWheelEvent& wheel_event,
923 const ui::LatencyInfo& ui_latency) {
924 TRACE_EVENT0("input", "RenderWidgetHostImpl::ForwardWheelEvent");
926 if (IgnoreInputEvents())
927 return;
929 if (touch_emulator_ && touch_emulator_->HandleMouseWheelEvent(wheel_event))
930 return;
932 MouseWheelEventWithLatencyInfo wheel_with_latency(wheel_event, ui_latency);
933 latency_tracker_.OnInputEvent(wheel_event, &wheel_with_latency.latency);
934 input_router_->SendWheelEvent(wheel_with_latency);
937 void RenderWidgetHostImpl::ForwardGestureEvent(
938 const blink::WebGestureEvent& gesture_event) {
939 ForwardGestureEventWithLatencyInfo(gesture_event, ui::LatencyInfo());
942 void RenderWidgetHostImpl::ForwardGestureEventWithLatencyInfo(
943 const blink::WebGestureEvent& gesture_event,
944 const ui::LatencyInfo& ui_latency) {
945 TRACE_EVENT0("input", "RenderWidgetHostImpl::ForwardGestureEvent");
946 // Early out if necessary, prior to performing latency logic.
947 if (IgnoreInputEvents())
948 return;
950 if (delegate_->PreHandleGestureEvent(gesture_event))
951 return;
953 GestureEventWithLatencyInfo gesture_with_latency(gesture_event, ui_latency);
954 latency_tracker_.OnInputEvent(gesture_event, &gesture_with_latency.latency);
955 input_router_->SendGestureEvent(gesture_with_latency);
958 void RenderWidgetHostImpl::ForwardEmulatedTouchEvent(
959 const blink::WebTouchEvent& touch_event) {
960 TRACE_EVENT0("input", "RenderWidgetHostImpl::ForwardEmulatedTouchEvent");
962 TouchEventWithLatencyInfo touch_with_latency(touch_event);
963 latency_tracker_.OnInputEvent(touch_event, &touch_with_latency.latency);
964 input_router_->SendTouchEvent(touch_with_latency);
967 void RenderWidgetHostImpl::ForwardTouchEventWithLatencyInfo(
968 const blink::WebTouchEvent& touch_event,
969 const ui::LatencyInfo& ui_latency) {
970 TRACE_EVENT0("input", "RenderWidgetHostImpl::ForwardTouchEvent");
972 // Always forward TouchEvents for touch stream consistency. They will be
973 // ignored if appropriate in FilterInputEvent().
975 TouchEventWithLatencyInfo touch_with_latency(touch_event, ui_latency);
976 if (touch_emulator_ &&
977 touch_emulator_->HandleTouchEvent(touch_with_latency.event)) {
978 if (view_) {
979 view_->ProcessAckedTouchEvent(
980 touch_with_latency, INPUT_EVENT_ACK_STATE_CONSUMED);
982 return;
985 latency_tracker_.OnInputEvent(touch_event, &touch_with_latency.latency);
986 input_router_->SendTouchEvent(touch_with_latency);
989 void RenderWidgetHostImpl::ForwardKeyboardEvent(
990 const NativeWebKeyboardEvent& key_event) {
991 TRACE_EVENT0("input", "RenderWidgetHostImpl::ForwardKeyboardEvent");
992 if (IgnoreInputEvents())
993 return;
995 if (!process_->HasConnection())
996 return;
998 // First, let keypress listeners take a shot at handling the event. If a
999 // listener handles the event, it should not be propagated to the renderer.
1000 if (KeyPressListenersHandleEvent(key_event)) {
1001 // Some keypresses that are accepted by the listener might have follow up
1002 // char events, which should be ignored.
1003 if (key_event.type == WebKeyboardEvent::RawKeyDown)
1004 suppress_next_char_events_ = true;
1005 return;
1008 if (key_event.type == WebKeyboardEvent::Char &&
1009 (key_event.windowsKeyCode == ui::VKEY_RETURN ||
1010 key_event.windowsKeyCode == ui::VKEY_SPACE)) {
1011 OnUserGesture();
1014 // Double check the type to make sure caller hasn't sent us nonsense that
1015 // will mess up our key queue.
1016 if (!WebInputEvent::isKeyboardEventType(key_event.type))
1017 return;
1019 if (suppress_next_char_events_) {
1020 // If preceding RawKeyDown event was handled by the browser, then we need
1021 // suppress all Char events generated by it. Please note that, one
1022 // RawKeyDown event may generate multiple Char events, so we can't reset
1023 // |suppress_next_char_events_| until we get a KeyUp or a RawKeyDown.
1024 if (key_event.type == WebKeyboardEvent::Char)
1025 return;
1026 // We get a KeyUp or a RawKeyDown event.
1027 suppress_next_char_events_ = false;
1030 bool is_shortcut = false;
1032 // Only pre-handle the key event if it's not handled by the input method.
1033 if (delegate_ && !key_event.skip_in_browser) {
1034 // We need to set |suppress_next_char_events_| to true if
1035 // PreHandleKeyboardEvent() returns true, but |this| may already be
1036 // destroyed at that time. So set |suppress_next_char_events_| true here,
1037 // then revert it afterwards when necessary.
1038 if (key_event.type == WebKeyboardEvent::RawKeyDown)
1039 suppress_next_char_events_ = true;
1041 // Tab switching/closing accelerators aren't sent to the renderer to avoid
1042 // a hung/malicious renderer from interfering.
1043 if (delegate_->PreHandleKeyboardEvent(key_event, &is_shortcut))
1044 return;
1046 if (key_event.type == WebKeyboardEvent::RawKeyDown)
1047 suppress_next_char_events_ = false;
1050 if (touch_emulator_ && touch_emulator_->HandleKeyboardEvent(key_event))
1051 return;
1053 ui::LatencyInfo latency;
1054 latency_tracker_.OnInputEvent(key_event, &latency);
1055 input_router_->SendKeyboardEvent(key_event, latency, is_shortcut);
1058 void RenderWidgetHostImpl::QueueSyntheticGesture(
1059 scoped_ptr<SyntheticGesture> synthetic_gesture,
1060 const base::Callback<void(SyntheticGesture::Result)>& on_complete) {
1061 if (!synthetic_gesture_controller_ && view_) {
1062 synthetic_gesture_controller_.reset(
1063 new SyntheticGestureController(
1064 view_->CreateSyntheticGestureTarget().Pass()));
1066 if (synthetic_gesture_controller_) {
1067 synthetic_gesture_controller_->QueueSyntheticGesture(
1068 synthetic_gesture.Pass(), on_complete);
1072 void RenderWidgetHostImpl::SetCursor(const WebCursor& cursor) {
1073 if (!view_)
1074 return;
1075 view_->UpdateCursor(cursor);
1078 void RenderWidgetHostImpl::ShowContextMenuAtPoint(const gfx::Point& point) {
1079 Send(new ViewMsg_ShowContextMenu(
1080 GetRoutingID(), ui::MENU_SOURCE_MOUSE, point));
1083 void RenderWidgetHostImpl::SendCursorVisibilityState(bool is_visible) {
1084 Send(new InputMsg_CursorVisibilityChange(GetRoutingID(), is_visible));
1087 int64 RenderWidgetHostImpl::GetLatencyComponentId() const {
1088 return latency_tracker_.latency_component_id();
1091 // static
1092 void RenderWidgetHostImpl::DisableResizeAckCheckForTesting() {
1093 g_check_for_pending_resize_ack = false;
1096 void RenderWidgetHostImpl::AddKeyPressEventCallback(
1097 const KeyPressEventCallback& callback) {
1098 key_press_event_callbacks_.push_back(callback);
1101 void RenderWidgetHostImpl::RemoveKeyPressEventCallback(
1102 const KeyPressEventCallback& callback) {
1103 for (size_t i = 0; i < key_press_event_callbacks_.size(); ++i) {
1104 if (key_press_event_callbacks_[i].Equals(callback)) {
1105 key_press_event_callbacks_.erase(
1106 key_press_event_callbacks_.begin() + i);
1107 return;
1112 void RenderWidgetHostImpl::AddMouseEventCallback(
1113 const MouseEventCallback& callback) {
1114 mouse_event_callbacks_.push_back(callback);
1117 void RenderWidgetHostImpl::RemoveMouseEventCallback(
1118 const MouseEventCallback& callback) {
1119 for (size_t i = 0; i < mouse_event_callbacks_.size(); ++i) {
1120 if (mouse_event_callbacks_[i].Equals(callback)) {
1121 mouse_event_callbacks_.erase(mouse_event_callbacks_.begin() + i);
1122 return;
1127 void RenderWidgetHostImpl::GetWebScreenInfo(blink::WebScreenInfo* result) {
1128 TRACE_EVENT0("renderer_host", "RenderWidgetHostImpl::GetWebScreenInfo");
1129 if (view_)
1130 view_->GetScreenInfo(result);
1131 else
1132 RenderWidgetHostViewBase::GetDefaultScreenInfo(result);
1133 latency_tracker_.set_device_scale_factor(result->deviceScaleFactor);
1134 screen_info_out_of_date_ = false;
1137 const NativeWebKeyboardEvent*
1138 RenderWidgetHostImpl::GetLastKeyboardEvent() const {
1139 return input_router_->GetLastKeyboardEvent();
1142 void RenderWidgetHostImpl::NotifyScreenInfoChanged() {
1143 if (delegate_)
1144 delegate_->ScreenInfoChanged();
1146 // The resize message (which may not happen immediately) will carry with it
1147 // the screen info as well as the new size (if the screen has changed scale
1148 // factor).
1149 InvalidateScreenInfo();
1150 WasResized();
1153 void RenderWidgetHostImpl::InvalidateScreenInfo() {
1154 screen_info_out_of_date_ = true;
1155 screen_info_.reset();
1158 void RenderWidgetHostImpl::GetSnapshotFromBrowser(
1159 const base::Callback<void(const unsigned char*,size_t)> callback) {
1160 int id = next_browser_snapshot_id_++;
1161 pending_browser_snapshots_.insert(std::make_pair(id, callback));
1162 Send(new ViewMsg_ForceRedraw(GetRoutingID(), id));
1165 void RenderWidgetHostImpl::OnSelectionChanged(const base::string16& text,
1166 size_t offset,
1167 const gfx::Range& range) {
1168 if (view_)
1169 view_->SelectionChanged(text, offset, range);
1172 void RenderWidgetHostImpl::OnSelectionBoundsChanged(
1173 const ViewHostMsg_SelectionBounds_Params& params) {
1174 if (view_) {
1175 view_->SelectionBoundsChanged(params);
1179 void RenderWidgetHostImpl::UpdateVSyncParameters(base::TimeTicks timebase,
1180 base::TimeDelta interval) {
1181 Send(new ViewMsg_UpdateVSyncParameters(GetRoutingID(), timebase, interval));
1184 void RenderWidgetHostImpl::RendererExited(base::TerminationStatus status,
1185 int exit_code) {
1186 // Clearing this flag causes us to re-create the renderer when recovering
1187 // from a crashed renderer.
1188 renderer_initialized_ = false;
1190 waiting_for_screen_rects_ack_ = false;
1192 // Must reset these to ensure that keyboard events work with a new renderer.
1193 suppress_next_char_events_ = false;
1195 // Reset some fields in preparation for recovering from a crash.
1196 ResetSizeAndRepaintPendingFlags();
1197 current_size_.SetSize(0, 0);
1198 // After the renderer crashes, the view is destroyed and so the
1199 // RenderWidgetHost cannot track its visibility anymore. We assume such
1200 // RenderWidgetHost to be visible for the sake of internal accounting - be
1201 // careful about changing this - see http://crbug.com/401859.
1203 // We need to at least make sure that the RenderProcessHost is notified about
1204 // the |is_hidden_| change, so that the renderer will have correct visibility
1205 // set when respawned.
1206 if (is_hidden_) {
1207 process_->WidgetRestored();
1208 is_hidden_ = false;
1211 // Reset this to ensure the hung renderer mechanism is working properly.
1212 in_flight_event_count_ = 0;
1214 if (view_) {
1215 GpuSurfaceTracker::Get()->SetSurfaceHandle(surface_id_,
1216 gfx::GLSurfaceHandle());
1217 view_->RenderProcessGone(status, exit_code);
1218 view_ = NULL; // The View should be deleted by RenderProcessGone.
1219 view_weak_.reset();
1222 // Reconstruct the input router to ensure that it has fresh state for a new
1223 // renderer. Otherwise it may be stuck waiting for the old renderer to ack an
1224 // event. (In particular, the above call to view_->RenderProcessGone will
1225 // destroy the aura window, which may dispatch a synthetic mouse move.)
1226 input_router_.reset(new InputRouterImpl(
1227 process_, this, this, routing_id_, GetInputRouterConfigForPlatform()));
1229 synthetic_gesture_controller_.reset();
1232 void RenderWidgetHostImpl::UpdateTextDirection(WebTextDirection direction) {
1233 text_direction_updated_ = true;
1234 text_direction_ = direction;
1237 void RenderWidgetHostImpl::CancelUpdateTextDirection() {
1238 if (text_direction_updated_)
1239 text_direction_canceled_ = true;
1242 void RenderWidgetHostImpl::NotifyTextDirection() {
1243 if (text_direction_updated_) {
1244 if (!text_direction_canceled_)
1245 Send(new ViewMsg_SetTextDirection(GetRoutingID(), text_direction_));
1246 text_direction_updated_ = false;
1247 text_direction_canceled_ = false;
1251 void RenderWidgetHostImpl::SetInputMethodActive(bool activate) {
1252 input_method_active_ = activate;
1253 Send(new ViewMsg_SetInputMethodActive(GetRoutingID(), activate));
1256 void RenderWidgetHostImpl::CandidateWindowShown() {
1257 Send(new ViewMsg_CandidateWindowShown(GetRoutingID()));
1260 void RenderWidgetHostImpl::CandidateWindowUpdated() {
1261 Send(new ViewMsg_CandidateWindowUpdated(GetRoutingID()));
1264 void RenderWidgetHostImpl::CandidateWindowHidden() {
1265 Send(new ViewMsg_CandidateWindowHidden(GetRoutingID()));
1268 void RenderWidgetHostImpl::ImeSetComposition(
1269 const base::string16& text,
1270 const std::vector<blink::WebCompositionUnderline>& underlines,
1271 int selection_start,
1272 int selection_end) {
1273 Send(new InputMsg_ImeSetComposition(
1274 GetRoutingID(), text, underlines, selection_start, selection_end));
1277 void RenderWidgetHostImpl::ImeConfirmComposition(
1278 const base::string16& text,
1279 const gfx::Range& replacement_range,
1280 bool keep_selection) {
1281 Send(new InputMsg_ImeConfirmComposition(
1282 GetRoutingID(), text, replacement_range, keep_selection));
1285 void RenderWidgetHostImpl::ImeCancelComposition() {
1286 Send(new InputMsg_ImeSetComposition(GetRoutingID(), base::string16(),
1287 std::vector<blink::WebCompositionUnderline>(), 0, 0));
1290 gfx::Rect RenderWidgetHostImpl::GetRootWindowResizerRect() const {
1291 return gfx::Rect();
1294 void RenderWidgetHostImpl::RequestToLockMouse(bool user_gesture,
1295 bool last_unlocked_by_target) {
1296 // Directly reject to lock the mouse. Subclass can override this method to
1297 // decide whether to allow mouse lock or not.
1298 GotResponseToLockMouseRequest(false);
1301 void RenderWidgetHostImpl::RejectMouseLockOrUnlockIfNecessary() {
1302 DCHECK(!pending_mouse_lock_request_ || !IsMouseLocked());
1303 if (pending_mouse_lock_request_) {
1304 pending_mouse_lock_request_ = false;
1305 Send(new ViewMsg_LockMouse_ACK(routing_id_, false));
1306 } else if (IsMouseLocked()) {
1307 view_->UnlockMouse();
1311 bool RenderWidgetHostImpl::IsMouseLocked() const {
1312 return view_ ? view_->IsMouseLocked() : false;
1315 bool RenderWidgetHostImpl::IsFullscreen() const {
1316 return false;
1319 void RenderWidgetHostImpl::SetAutoResize(bool enable,
1320 const gfx::Size& min_size,
1321 const gfx::Size& max_size) {
1322 auto_resize_enabled_ = enable;
1323 min_size_for_auto_resize_ = min_size;
1324 max_size_for_auto_resize_ = max_size;
1327 void RenderWidgetHostImpl::Cleanup() {
1328 if (view_) {
1329 view_->Destroy();
1330 view_ = nullptr;
1334 void RenderWidgetHostImpl::Destroy() {
1335 NotificationService::current()->Notify(
1336 NOTIFICATION_RENDER_WIDGET_HOST_DESTROYED,
1337 Source<RenderWidgetHost>(this),
1338 NotificationService::NoDetails());
1340 // Tell the view to die.
1341 // Note that in the process of the view shutting down, it can call a ton
1342 // of other messages on us. So if you do any other deinitialization here,
1343 // do it after this call to view_->Destroy().
1344 if (view_) {
1345 view_->Destroy();
1346 view_ = nullptr;
1349 delete this;
1352 void RenderWidgetHostImpl::RendererIsUnresponsive() {
1353 NotificationService::current()->Notify(
1354 NOTIFICATION_RENDER_WIDGET_HOST_HANG,
1355 Source<RenderWidgetHost>(this),
1356 NotificationService::NoDetails());
1357 is_unresponsive_ = true;
1358 NotifyRendererUnresponsive();
1361 void RenderWidgetHostImpl::RendererIsResponsive() {
1362 if (is_unresponsive_) {
1363 is_unresponsive_ = false;
1364 NotifyRendererResponsive();
1368 void RenderWidgetHostImpl::OnRenderViewReady() {
1369 SendScreenRects();
1370 WasResized();
1373 void RenderWidgetHostImpl::OnRenderProcessGone(int status, int exit_code) {
1374 // RenderFrameHost owns a RenderWidgetHost when it needs one, in which case
1375 // it handles destruction.
1376 if (!owned_by_render_frame_host_) {
1377 // TODO(evanm): This synchronously ends up calling "delete this".
1378 // Is that really what we want in response to this message? I'm matching
1379 // previous behavior of the code here.
1380 Destroy();
1381 } else {
1382 RendererExited(static_cast<base::TerminationStatus>(status), exit_code);
1386 void RenderWidgetHostImpl::OnClose() {
1387 Shutdown();
1390 void RenderWidgetHostImpl::OnSetTooltipText(
1391 const base::string16& tooltip_text,
1392 WebTextDirection text_direction_hint) {
1393 // First, add directionality marks around tooltip text if necessary.
1394 // A naive solution would be to simply always wrap the text. However, on
1395 // windows, Unicode directional embedding characters can't be displayed on
1396 // systems that lack RTL fonts and are instead displayed as empty squares.
1398 // To get around this we only wrap the string when we deem it necessary i.e.
1399 // when the locale direction is different than the tooltip direction hint.
1401 // Currently, we use element's directionality as the tooltip direction hint.
1402 // An alternate solution would be to set the overall directionality based on
1403 // trying to detect the directionality from the tooltip text rather than the
1404 // element direction. One could argue that would be a preferable solution
1405 // but we use the current approach to match Fx & IE's behavior.
1406 base::string16 wrapped_tooltip_text = tooltip_text;
1407 if (!tooltip_text.empty()) {
1408 if (text_direction_hint == blink::WebTextDirectionLeftToRight) {
1409 // Force the tooltip to have LTR directionality.
1410 wrapped_tooltip_text =
1411 base::i18n::GetDisplayStringInLTRDirectionality(wrapped_tooltip_text);
1412 } else if (text_direction_hint == blink::WebTextDirectionRightToLeft &&
1413 !base::i18n::IsRTL()) {
1414 // Force the tooltip to have RTL directionality.
1415 base::i18n::WrapStringWithRTLFormatting(&wrapped_tooltip_text);
1418 if (GetView())
1419 view_->SetTooltipText(wrapped_tooltip_text);
1422 void RenderWidgetHostImpl::OnUpdateScreenRectsAck() {
1423 waiting_for_screen_rects_ack_ = false;
1424 if (!view_)
1425 return;
1427 if (view_->GetViewBounds() == last_view_screen_rect_ &&
1428 view_->GetBoundsInRootWindow() == last_window_screen_rect_) {
1429 return;
1432 SendScreenRects();
1435 void RenderWidgetHostImpl::OnRequestMove(const gfx::Rect& pos) {
1436 if (view_) {
1437 view_->SetBounds(pos);
1438 Send(new ViewMsg_Move_ACK(routing_id_));
1442 bool RenderWidgetHostImpl::OnSwapCompositorFrame(
1443 const IPC::Message& message) {
1444 // This trace event is used in
1445 // chrome/browser/extensions/api/cast_streaming/performance_test.cc
1446 TRACE_EVENT0("test_fps,benchmark", "OnSwapCompositorFrame");
1447 ViewHostMsg_SwapCompositorFrame::Param param;
1448 if (!ViewHostMsg_SwapCompositorFrame::Read(&message, &param))
1449 return false;
1450 scoped_ptr<cc::CompositorFrame> frame(new cc::CompositorFrame);
1451 uint32 output_surface_id = get<0>(param);
1452 get<1>(param).AssignTo(frame.get());
1453 std::vector<IPC::Message> messages_to_deliver_with_frame;
1454 messages_to_deliver_with_frame.swap(get<2>(param));
1456 latency_tracker_.OnSwapCompositorFrame(&frame->metadata.latency_info);
1458 input_router_->OnViewUpdated(
1459 GetInputRouterViewFlagsFromCompositorFrameMetadata(frame->metadata));
1461 if (touch_emulator_) {
1462 touch_emulator_->SetDoubleTapSupportForPageEnabled(
1463 !IsMobileOptimizedFrame(frame->metadata));
1466 if (view_) {
1467 view_->OnSwapCompositorFrame(output_surface_id, frame.Pass());
1468 view_->DidReceiveRendererFrame();
1469 } else {
1470 cc::CompositorFrameAck ack;
1471 if (frame->gl_frame_data) {
1472 ack.gl_frame_data = frame->gl_frame_data.Pass();
1473 ack.gl_frame_data->sync_point = 0;
1474 } else if (frame->delegated_frame_data) {
1475 cc::TransferableResource::ReturnResources(
1476 frame->delegated_frame_data->resource_list,
1477 &ack.resources);
1478 } else if (frame->software_frame_data) {
1479 ack.last_software_frame_id = frame->software_frame_data->id;
1481 SendSwapCompositorFrameAck(routing_id_, output_surface_id,
1482 process_->GetID(), ack);
1485 RenderProcessHost* rph = GetProcess();
1486 for (std::vector<IPC::Message>::const_iterator i =
1487 messages_to_deliver_with_frame.begin();
1488 i != messages_to_deliver_with_frame.end();
1489 ++i) {
1490 rph->OnMessageReceived(*i);
1491 if (i->dispatch_error())
1492 rph->OnBadMessageReceived(*i);
1494 messages_to_deliver_with_frame.clear();
1496 return true;
1499 void RenderWidgetHostImpl::OnFlingingStopped() {
1500 if (view_)
1501 view_->DidStopFlinging();
1504 void RenderWidgetHostImpl::OnUpdateRect(
1505 const ViewHostMsg_UpdateRect_Params& params) {
1506 TRACE_EVENT0("renderer_host", "RenderWidgetHostImpl::OnUpdateRect");
1507 TimeTicks paint_start = TimeTicks::Now();
1509 // Update our knowledge of the RenderWidget's size.
1510 current_size_ = params.view_size;
1512 bool is_resize_ack =
1513 ViewHostMsg_UpdateRect_Flags::is_resize_ack(params.flags);
1515 // resize_ack_pending_ needs to be cleared before we call DidPaintRect, since
1516 // that will end up reaching GetBackingStore.
1517 if (is_resize_ack) {
1518 DCHECK(!g_check_for_pending_resize_ack || resize_ack_pending_);
1519 resize_ack_pending_ = false;
1522 bool is_repaint_ack =
1523 ViewHostMsg_UpdateRect_Flags::is_repaint_ack(params.flags);
1524 if (is_repaint_ack) {
1525 DCHECK(repaint_ack_pending_);
1526 TRACE_EVENT_ASYNC_END0(
1527 "renderer_host", "RenderWidgetHostImpl::repaint_ack_pending_", this);
1528 repaint_ack_pending_ = false;
1529 TimeDelta delta = TimeTicks::Now() - repaint_start_time_;
1530 UMA_HISTOGRAM_TIMES("MPArch.RWH_RepaintDelta", delta);
1533 DCHECK(!params.view_size.IsEmpty());
1535 DidUpdateBackingStore(params, paint_start);
1537 if (auto_resize_enabled_) {
1538 bool post_callback = new_auto_size_.IsEmpty();
1539 new_auto_size_ = params.view_size;
1540 if (post_callback) {
1541 base::MessageLoop::current()->PostTask(
1542 FROM_HERE,
1543 base::Bind(&RenderWidgetHostImpl::DelayedAutoResized,
1544 weak_factory_.GetWeakPtr()));
1548 // Log the time delta for processing a paint message. On platforms that don't
1549 // support asynchronous painting, this is equivalent to
1550 // MPArch.RWH_TotalPaintTime.
1551 TimeDelta delta = TimeTicks::Now() - paint_start;
1552 UMA_HISTOGRAM_TIMES("MPArch.RWH_OnMsgUpdateRect", delta);
1555 void RenderWidgetHostImpl::DidUpdateBackingStore(
1556 const ViewHostMsg_UpdateRect_Params& params,
1557 const TimeTicks& paint_start) {
1558 TRACE_EVENT0("renderer_host", "RenderWidgetHostImpl::DidUpdateBackingStore");
1559 TimeTicks update_start = TimeTicks::Now();
1561 // Move the plugins if the view hasn't already been destroyed. Plugin moves
1562 // will not be re-issued, so must move them now, regardless of whether we
1563 // paint or not. MovePluginWindows attempts to move the plugin windows and
1564 // in the process could dispatch other window messages which could cause the
1565 // view to be destroyed.
1566 if (view_)
1567 view_->MovePluginWindows(params.plugin_window_moves);
1569 NotificationService::current()->Notify(
1570 NOTIFICATION_RENDER_WIDGET_HOST_DID_UPDATE_BACKING_STORE,
1571 Source<RenderWidgetHost>(this),
1572 NotificationService::NoDetails());
1574 // We don't need to update the view if the view is hidden. We must do this
1575 // early return after the ACK is sent, however, or the renderer will not send
1576 // us more data.
1577 if (is_hidden_)
1578 return;
1580 // If we got a resize ack, then perhaps we have another resize to send?
1581 bool is_resize_ack =
1582 ViewHostMsg_UpdateRect_Flags::is_resize_ack(params.flags);
1583 if (is_resize_ack)
1584 WasResized();
1586 // Log the time delta for processing a paint message.
1587 TimeTicks now = TimeTicks::Now();
1588 TimeDelta delta = now - update_start;
1589 UMA_HISTOGRAM_TIMES("MPArch.RWH_DidUpdateBackingStore", delta);
1592 void RenderWidgetHostImpl::OnQueueSyntheticGesture(
1593 const SyntheticGesturePacket& gesture_packet) {
1594 // Only allow untrustworthy gestures if explicitly enabled.
1595 if (!base::CommandLine::ForCurrentProcess()->HasSwitch(
1596 cc::switches::kEnableGpuBenchmarking)) {
1597 RecordAction(base::UserMetricsAction("BadMessageTerminate_RWH7"));
1598 GetProcess()->ReceivedBadMessage();
1599 return;
1602 QueueSyntheticGesture(
1603 SyntheticGesture::Create(*gesture_packet.gesture_params()),
1604 base::Bind(&RenderWidgetHostImpl::OnSyntheticGestureCompleted,
1605 weak_factory_.GetWeakPtr()));
1608 void RenderWidgetHostImpl::OnFocus() {
1609 // Only RenderViewHost can deal with that message.
1610 RecordAction(base::UserMetricsAction("BadMessageTerminate_RWH4"));
1611 GetProcess()->ReceivedBadMessage();
1614 void RenderWidgetHostImpl::OnBlur() {
1615 // Only RenderViewHost can deal with that message.
1616 RecordAction(base::UserMetricsAction("BadMessageTerminate_RWH5"));
1617 GetProcess()->ReceivedBadMessage();
1620 void RenderWidgetHostImpl::OnSetCursor(const WebCursor& cursor) {
1621 SetCursor(cursor);
1624 void RenderWidgetHostImpl::SetTouchEventEmulationEnabled(
1625 bool enabled, ui::GestureProviderConfigType config_type) {
1626 if (enabled) {
1627 if (!touch_emulator_)
1628 touch_emulator_.reset(new TouchEmulator(this));
1629 touch_emulator_->Enable(config_type);
1630 } else {
1631 if (touch_emulator_)
1632 touch_emulator_->Disable();
1636 void RenderWidgetHostImpl::OnTextInputTypeChanged(
1637 ui::TextInputType type,
1638 ui::TextInputMode input_mode,
1639 bool can_compose_inline,
1640 int flags) {
1641 if (view_)
1642 view_->TextInputTypeChanged(type, input_mode, can_compose_inline, flags);
1645 void RenderWidgetHostImpl::OnImeCompositionRangeChanged(
1646 const gfx::Range& range,
1647 const std::vector<gfx::Rect>& character_bounds) {
1648 if (view_)
1649 view_->ImeCompositionRangeChanged(range, character_bounds);
1652 void RenderWidgetHostImpl::OnImeCancelComposition() {
1653 if (view_)
1654 view_->ImeCancelComposition();
1657 void RenderWidgetHostImpl::OnLockMouse(bool user_gesture,
1658 bool last_unlocked_by_target,
1659 bool privileged) {
1661 if (pending_mouse_lock_request_) {
1662 Send(new ViewMsg_LockMouse_ACK(routing_id_, false));
1663 return;
1664 } else if (IsMouseLocked()) {
1665 Send(new ViewMsg_LockMouse_ACK(routing_id_, true));
1666 return;
1669 pending_mouse_lock_request_ = true;
1670 if (privileged && allow_privileged_mouse_lock_) {
1671 // Directly approve to lock the mouse.
1672 GotResponseToLockMouseRequest(true);
1673 } else {
1674 RequestToLockMouse(user_gesture, last_unlocked_by_target);
1678 void RenderWidgetHostImpl::OnUnlockMouse() {
1679 RejectMouseLockOrUnlockIfNecessary();
1682 void RenderWidgetHostImpl::OnShowDisambiguationPopup(
1683 const gfx::Rect& rect_pixels,
1684 const gfx::Size& size,
1685 const cc::SharedBitmapId& id) {
1686 DCHECK(!rect_pixels.IsEmpty());
1687 DCHECK(!size.IsEmpty());
1689 scoped_ptr<cc::SharedBitmap> bitmap =
1690 HostSharedBitmapManager::current()->GetSharedBitmapFromId(size, id);
1691 if (!bitmap) {
1692 RecordAction(base::UserMetricsAction("BadMessageTerminate_RWH6"));
1693 GetProcess()->ReceivedBadMessage();
1694 return;
1697 DCHECK(bitmap->pixels());
1699 SkImageInfo info = SkImageInfo::MakeN32Premul(size.width(), size.height());
1700 SkBitmap zoomed_bitmap;
1701 zoomed_bitmap.installPixels(info, bitmap->pixels(), info.minRowBytes());
1703 // Note that |rect| is in coordinates of pixels relative to the window origin.
1704 // Aura-based systems will want to convert this to DIPs.
1705 if (view_)
1706 view_->ShowDisambiguationPopup(rect_pixels, zoomed_bitmap);
1708 // It is assumed that the disambiguation popup will make a copy of the
1709 // provided zoomed image, so we delete this one.
1710 zoomed_bitmap.setPixels(0);
1711 Send(new ViewMsg_ReleaseDisambiguationPopupBitmap(GetRoutingID(), id));
1714 #if defined(OS_WIN)
1715 void RenderWidgetHostImpl::OnWindowlessPluginDummyWindowCreated(
1716 gfx::NativeViewId dummy_activation_window) {
1717 HWND hwnd = reinterpret_cast<HWND>(dummy_activation_window);
1719 // This may happen as a result of a race condition when the plugin is going
1720 // away.
1721 wchar_t window_title[MAX_PATH + 1] = {0};
1722 if (!IsWindow(hwnd) ||
1723 !GetWindowText(hwnd, window_title, arraysize(window_title)) ||
1724 lstrcmpiW(window_title, kDummyActivationWindowName) != 0) {
1725 return;
1728 #if defined(USE_AURA)
1729 SetParent(hwnd,
1730 reinterpret_cast<HWND>(view_->GetParentForWindowlessPlugin()));
1731 #else
1732 SetParent(hwnd, reinterpret_cast<HWND>(GetNativeViewId()));
1733 #endif
1734 dummy_windows_for_activation_.push_back(hwnd);
1737 void RenderWidgetHostImpl::OnWindowlessPluginDummyWindowDestroyed(
1738 gfx::NativeViewId dummy_activation_window) {
1739 HWND hwnd = reinterpret_cast<HWND>(dummy_activation_window);
1740 std::list<HWND>::iterator i = dummy_windows_for_activation_.begin();
1741 for (; i != dummy_windows_for_activation_.end(); ++i) {
1742 if ((*i) == hwnd) {
1743 dummy_windows_for_activation_.erase(i);
1744 return;
1747 NOTREACHED() << "Unknown dummy window";
1749 #endif
1751 void RenderWidgetHostImpl::SetIgnoreInputEvents(bool ignore_input_events) {
1752 ignore_input_events_ = ignore_input_events;
1755 bool RenderWidgetHostImpl::KeyPressListenersHandleEvent(
1756 const NativeWebKeyboardEvent& event) {
1757 if (event.skip_in_browser || event.type != WebKeyboardEvent::RawKeyDown)
1758 return false;
1760 for (size_t i = 0; i < key_press_event_callbacks_.size(); i++) {
1761 size_t original_size = key_press_event_callbacks_.size();
1762 if (key_press_event_callbacks_[i].Run(event))
1763 return true;
1765 // Check whether the callback that just ran removed itself, in which case
1766 // the iterator needs to be decremented to properly account for the removal.
1767 size_t current_size = key_press_event_callbacks_.size();
1768 if (current_size != original_size) {
1769 DCHECK_EQ(original_size - 1, current_size);
1770 --i;
1774 return false;
1777 InputEventAckState RenderWidgetHostImpl::FilterInputEvent(
1778 const blink::WebInputEvent& event, const ui::LatencyInfo& latency_info) {
1779 // Don't ignore touch cancel events, since they may be sent while input
1780 // events are being ignored in order to keep the renderer from getting
1781 // confused about how many touches are active.
1782 if (IgnoreInputEvents() && event.type != WebInputEvent::TouchCancel)
1783 return INPUT_EVENT_ACK_STATE_NO_CONSUMER_EXISTS;
1785 if (!process_->HasConnection())
1786 return INPUT_EVENT_ACK_STATE_UNKNOWN;
1788 if (event.type == WebInputEvent::MouseDown)
1789 OnUserGesture();
1791 return view_ ? view_->FilterInputEvent(event)
1792 : INPUT_EVENT_ACK_STATE_NOT_CONSUMED;
1795 void RenderWidgetHostImpl::IncrementInFlightEventCount() {
1796 StartHangMonitorTimeout(
1797 TimeDelta::FromMilliseconds(hung_renderer_delay_ms_));
1798 increment_in_flight_event_count();
1801 void RenderWidgetHostImpl::DecrementInFlightEventCount() {
1802 if (decrement_in_flight_event_count() <= 0) {
1803 // Cancel pending hung renderer checks since the renderer is responsive.
1804 StopHangMonitorTimeout();
1805 } else {
1806 // The renderer is responsive, but there are in-flight events to wait for.
1807 RestartHangMonitorTimeout();
1811 void RenderWidgetHostImpl::OnHasTouchEventHandlers(bool has_handlers) {
1812 has_touch_handler_ = has_handlers;
1815 void RenderWidgetHostImpl::DidFlush() {
1816 if (synthetic_gesture_controller_)
1817 synthetic_gesture_controller_->OnDidFlushInput();
1818 if (view_)
1819 view_->OnDidFlushInput();
1822 void RenderWidgetHostImpl::DidOverscroll(const DidOverscrollParams& params) {
1823 if (view_)
1824 view_->DidOverscroll(params);
1827 void RenderWidgetHostImpl::OnKeyboardEventAck(
1828 const NativeWebKeyboardEvent& event,
1829 InputEventAckState ack_result) {
1830 #if defined(OS_MACOSX)
1831 if (!is_hidden() && view_ && view_->PostProcessEventForPluginIme(event))
1832 return;
1833 #endif
1835 // We only send unprocessed key event upwards if we are not hidden,
1836 // because the user has moved away from us and no longer expect any effect
1837 // of this key event.
1838 const bool processed = (INPUT_EVENT_ACK_STATE_CONSUMED == ack_result);
1839 if (delegate_ && !processed && !is_hidden() && !event.skip_in_browser) {
1840 delegate_->HandleKeyboardEvent(event);
1842 // WARNING: This RenderWidgetHostImpl can be deallocated at this point
1843 // (i.e. in the case of Ctrl+W, where the call to
1844 // HandleKeyboardEvent destroys this RenderWidgetHostImpl).
1848 void RenderWidgetHostImpl::OnWheelEventAck(
1849 const MouseWheelEventWithLatencyInfo& wheel_event,
1850 InputEventAckState ack_result) {
1851 latency_tracker_.OnInputEventAck(wheel_event.event, &wheel_event.latency);
1853 if (!is_hidden() && view_) {
1854 if (ack_result != INPUT_EVENT_ACK_STATE_CONSUMED &&
1855 delegate_->HandleWheelEvent(wheel_event.event)) {
1856 ack_result = INPUT_EVENT_ACK_STATE_CONSUMED;
1858 view_->WheelEventAck(wheel_event.event, ack_result);
1862 void RenderWidgetHostImpl::OnGestureEventAck(
1863 const GestureEventWithLatencyInfo& event,
1864 InputEventAckState ack_result) {
1865 latency_tracker_.OnInputEventAck(event.event, &event.latency);
1867 if (view_)
1868 view_->GestureEventAck(event.event, ack_result);
1871 void RenderWidgetHostImpl::OnTouchEventAck(
1872 const TouchEventWithLatencyInfo& event,
1873 InputEventAckState ack_result) {
1874 latency_tracker_.OnInputEventAck(event.event, &event.latency);
1876 if (touch_emulator_ &&
1877 touch_emulator_->HandleTouchEventAck(event.event, ack_result)) {
1878 return;
1881 if (view_)
1882 view_->ProcessAckedTouchEvent(event, ack_result);
1885 void RenderWidgetHostImpl::OnUnexpectedEventAck(UnexpectedEventAckType type) {
1886 if (type == BAD_ACK_MESSAGE) {
1887 RecordAction(base::UserMetricsAction("BadMessageTerminate_RWH2"));
1888 process_->ReceivedBadMessage();
1889 } else if (type == UNEXPECTED_EVENT_TYPE) {
1890 suppress_next_char_events_ = false;
1894 void RenderWidgetHostImpl::OnSyntheticGestureCompleted(
1895 SyntheticGesture::Result result) {
1896 Send(new InputMsg_SyntheticGestureCompleted(GetRoutingID()));
1899 bool RenderWidgetHostImpl::IgnoreInputEvents() const {
1900 return ignore_input_events_ || process_->IgnoreInputEvents();
1903 void RenderWidgetHostImpl::StartUserGesture() {
1904 OnUserGesture();
1907 void RenderWidgetHostImpl::SetBackgroundOpaque(bool opaque) {
1908 Send(new ViewMsg_SetBackgroundOpaque(GetRoutingID(), opaque));
1911 void RenderWidgetHostImpl::SetEditCommandsForNextKeyEvent(
1912 const std::vector<EditCommand>& commands) {
1913 Send(new InputMsg_SetEditCommandsForNextKeyEvent(GetRoutingID(), commands));
1916 void RenderWidgetHostImpl::ExecuteEditCommand(const std::string& command,
1917 const std::string& value) {
1918 Send(new InputMsg_ExecuteEditCommand(GetRoutingID(), command, value));
1921 void RenderWidgetHostImpl::ScrollFocusedEditableNodeIntoRect(
1922 const gfx::Rect& rect) {
1923 Send(new InputMsg_ScrollFocusedEditableNodeIntoRect(GetRoutingID(), rect));
1926 void RenderWidgetHostImpl::MoveCaret(const gfx::Point& point) {
1927 Send(new InputMsg_MoveCaret(GetRoutingID(), point));
1930 bool RenderWidgetHostImpl::GotResponseToLockMouseRequest(bool allowed) {
1931 if (!allowed) {
1932 RejectMouseLockOrUnlockIfNecessary();
1933 return false;
1934 } else {
1935 if (!pending_mouse_lock_request_) {
1936 // This is possible, e.g., the plugin sends us an unlock request before
1937 // the user allows to lock to mouse.
1938 return false;
1941 pending_mouse_lock_request_ = false;
1942 if (!view_ || !view_->HasFocus()|| !view_->LockMouse()) {
1943 Send(new ViewMsg_LockMouse_ACK(routing_id_, false));
1944 return false;
1945 } else {
1946 Send(new ViewMsg_LockMouse_ACK(routing_id_, true));
1947 return true;
1952 // static
1953 void RenderWidgetHostImpl::SendSwapCompositorFrameAck(
1954 int32 route_id,
1955 uint32 output_surface_id,
1956 int renderer_host_id,
1957 const cc::CompositorFrameAck& ack) {
1958 RenderProcessHost* host = RenderProcessHost::FromID(renderer_host_id);
1959 if (!host)
1960 return;
1961 host->Send(new ViewMsg_SwapCompositorFrameAck(
1962 route_id, output_surface_id, ack));
1965 // static
1966 void RenderWidgetHostImpl::SendReclaimCompositorResources(
1967 int32 route_id,
1968 uint32 output_surface_id,
1969 int renderer_host_id,
1970 const cc::CompositorFrameAck& ack) {
1971 RenderProcessHost* host = RenderProcessHost::FromID(renderer_host_id);
1972 if (!host)
1973 return;
1974 host->Send(
1975 new ViewMsg_ReclaimCompositorResources(route_id, output_surface_id, ack));
1978 void RenderWidgetHostImpl::DelayedAutoResized() {
1979 gfx::Size new_size = new_auto_size_;
1980 // Clear the new_auto_size_ since the empty value is used as a flag to
1981 // indicate that no callback is in progress (i.e. without this line
1982 // DelayedAutoResized will not get called again).
1983 new_auto_size_.SetSize(0, 0);
1984 if (!auto_resize_enabled_)
1985 return;
1987 OnRenderAutoResized(new_size);
1990 void RenderWidgetHostImpl::DetachDelegate() {
1991 delegate_ = NULL;
1994 void RenderWidgetHostImpl::FrameSwapped(const ui::LatencyInfo& latency_info) {
1995 ui::LatencyInfo::LatencyComponent window_snapshot_component;
1996 if (latency_info.FindLatency(ui::WINDOW_OLD_SNAPSHOT_FRAME_NUMBER_COMPONENT,
1997 GetLatencyComponentId(),
1998 &window_snapshot_component)) {
1999 WindowOldSnapshotReachedScreen(
2000 static_cast<int>(window_snapshot_component.sequence_number));
2002 if (latency_info.FindLatency(ui::WINDOW_SNAPSHOT_FRAME_NUMBER_COMPONENT,
2003 GetLatencyComponentId(),
2004 &window_snapshot_component)) {
2005 int sequence_number = static_cast<int>(
2006 window_snapshot_component.sequence_number);
2007 #if defined(OS_MACOSX)
2008 // On Mac, when using CoreAnmation, there is a delay between when content
2009 // is drawn to the screen, and when the snapshot will actually pick up
2010 // that content. Insert a manual delay of 1/6th of a second (to simulate
2011 // 10 frames at 60 fps) before actually taking the snapshot.
2012 base::MessageLoop::current()->PostDelayedTask(
2013 FROM_HERE,
2014 base::Bind(&RenderWidgetHostImpl::WindowSnapshotReachedScreen,
2015 weak_factory_.GetWeakPtr(),
2016 sequence_number),
2017 base::TimeDelta::FromSecondsD(1. / 6));
2018 #else
2019 WindowSnapshotReachedScreen(sequence_number);
2020 #endif
2023 latency_tracker_.OnFrameSwapped(latency_info);
2026 void RenderWidgetHostImpl::DidReceiveRendererFrame() {
2027 view_->DidReceiveRendererFrame();
2030 void RenderWidgetHostImpl::WindowSnapshotAsyncCallback(
2031 int routing_id,
2032 int snapshot_id,
2033 gfx::Size snapshot_size,
2034 scoped_refptr<base::RefCountedBytes> png_data) {
2035 if (!png_data.get()) {
2036 std::vector<unsigned char> png_vector;
2037 Send(new ViewMsg_WindowSnapshotCompleted(
2038 routing_id, snapshot_id, gfx::Size(), png_vector));
2039 return;
2042 Send(new ViewMsg_WindowSnapshotCompleted(
2043 routing_id, snapshot_id, snapshot_size, png_data->data()));
2046 void RenderWidgetHostImpl::WindowOldSnapshotReachedScreen(int snapshot_id) {
2047 DCHECK(base::MessageLoopForUI::IsCurrent());
2049 std::vector<unsigned char> png;
2051 // This feature is behind the kEnableGpuBenchmarking command line switch
2052 // because it poses security concerns and should only be used for testing.
2053 const base::CommandLine& command_line =
2054 *base::CommandLine::ForCurrentProcess();
2055 if (!command_line.HasSwitch(cc::switches::kEnableGpuBenchmarking)) {
2056 Send(new ViewMsg_WindowSnapshotCompleted(
2057 GetRoutingID(), snapshot_id, gfx::Size(), png));
2058 return;
2061 gfx::Rect view_bounds = GetView()->GetViewBounds();
2062 gfx::Rect snapshot_bounds(view_bounds.size());
2063 gfx::Size snapshot_size = snapshot_bounds.size();
2065 if (ui::GrabViewSnapshot(
2066 GetView()->GetNativeView(), &png, snapshot_bounds)) {
2067 Send(new ViewMsg_WindowSnapshotCompleted(
2068 GetRoutingID(), snapshot_id, snapshot_size, png));
2069 return;
2072 ui::GrabViewSnapshotAsync(
2073 GetView()->GetNativeView(),
2074 snapshot_bounds,
2075 base::ThreadTaskRunnerHandle::Get(),
2076 base::Bind(&RenderWidgetHostImpl::WindowSnapshotAsyncCallback,
2077 weak_factory_.GetWeakPtr(),
2078 GetRoutingID(),
2079 snapshot_id,
2080 snapshot_size));
2083 void RenderWidgetHostImpl::WindowSnapshotReachedScreen(int snapshot_id) {
2084 DCHECK(base::MessageLoopForUI::IsCurrent());
2086 gfx::Rect view_bounds = GetView()->GetViewBounds();
2087 gfx::Rect snapshot_bounds(view_bounds.size());
2089 std::vector<unsigned char> png;
2090 if (ui::GrabViewSnapshot(
2091 GetView()->GetNativeView(), &png, snapshot_bounds)) {
2092 OnSnapshotDataReceived(snapshot_id, &png.front(), png.size());
2093 return;
2096 ui::GrabViewSnapshotAsync(
2097 GetView()->GetNativeView(),
2098 snapshot_bounds,
2099 base::ThreadTaskRunnerHandle::Get(),
2100 base::Bind(&RenderWidgetHostImpl::OnSnapshotDataReceivedAsync,
2101 weak_factory_.GetWeakPtr(),
2102 snapshot_id));
2105 void RenderWidgetHostImpl::OnSnapshotDataReceived(int snapshot_id,
2106 const unsigned char* data,
2107 size_t size) {
2108 // Any pending snapshots with a lower ID than the one received are considered
2109 // to be implicitly complete, and returned the same snapshot data.
2110 PendingSnapshotMap::iterator it = pending_browser_snapshots_.begin();
2111 while(it != pending_browser_snapshots_.end()) {
2112 if (it->first <= snapshot_id) {
2113 it->second.Run(data, size);
2114 pending_browser_snapshots_.erase(it++);
2115 } else {
2116 ++it;
2121 void RenderWidgetHostImpl::OnSnapshotDataReceivedAsync(
2122 int snapshot_id,
2123 scoped_refptr<base::RefCountedBytes> png_data) {
2124 if (png_data.get())
2125 OnSnapshotDataReceived(snapshot_id, png_data->front(), png_data->size());
2126 else
2127 OnSnapshotDataReceived(snapshot_id, NULL, 0);
2130 // static
2131 void RenderWidgetHostImpl::CompositorFrameDrawn(
2132 const std::vector<ui::LatencyInfo>& latency_info) {
2133 for (size_t i = 0; i < latency_info.size(); i++) {
2134 std::set<RenderWidgetHostImpl*> rwhi_set;
2135 for (ui::LatencyInfo::LatencyMap::const_iterator b =
2136 latency_info[i].latency_components.begin();
2137 b != latency_info[i].latency_components.end();
2138 ++b) {
2139 if (b->first.first == ui::INPUT_EVENT_LATENCY_BEGIN_RWH_COMPONENT ||
2140 b->first.first == ui::WINDOW_SNAPSHOT_FRAME_NUMBER_COMPONENT ||
2141 b->first.first == ui::WINDOW_OLD_SNAPSHOT_FRAME_NUMBER_COMPONENT ||
2142 b->first.first == ui::TAB_SHOW_COMPONENT) {
2143 // Matches with GetLatencyComponentId
2144 int routing_id = b->first.second & 0xffffffff;
2145 int process_id = (b->first.second >> 32) & 0xffffffff;
2146 RenderWidgetHost* rwh =
2147 RenderWidgetHost::FromID(process_id, routing_id);
2148 if (!rwh) {
2149 continue;
2151 RenderWidgetHostImpl* rwhi = RenderWidgetHostImpl::From(rwh);
2152 if (rwhi_set.insert(rwhi).second)
2153 rwhi->FrameSwapped(latency_info[i]);
2159 BrowserAccessibilityManager*
2160 RenderWidgetHostImpl::GetRootBrowserAccessibilityManager() {
2161 return delegate_ ? delegate_->GetRootBrowserAccessibilityManager() : NULL;
2164 BrowserAccessibilityManager*
2165 RenderWidgetHostImpl::GetOrCreateRootBrowserAccessibilityManager() {
2166 return delegate_ ?
2167 delegate_->GetOrCreateRootBrowserAccessibilityManager() : NULL;
2170 base::TimeDelta RenderWidgetHostImpl::GetEstimatedBrowserCompositeTime() const {
2171 return latency_tracker_.GetEstimatedBrowserCompositeTime();
2174 #if defined(OS_WIN)
2175 gfx::NativeViewAccessible
2176 RenderWidgetHostImpl::GetParentNativeViewAccessible() {
2177 return delegate_ ? delegate_->GetParentNativeViewAccessible() : NULL;
2179 #endif
2181 SkColorType RenderWidgetHostImpl::PreferredReadbackFormat() {
2182 if (view_)
2183 return view_->PreferredReadbackFormat();
2184 return kN32_SkColorType;
2187 } // namespace content