Upstream version 10.39.225.0
[platform/framework/web/crosswalk.git] / src / content / browser / renderer_host / render_widget_host_view_aura.cc
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.
4
5 #include "content/browser/renderer_host/render_widget_host_view_aura.h"
6
7 #include "base/auto_reset.h"
8 #include "base/basictypes.h"
9 #include "base/bind.h"
10 #include "base/callback_helpers.h"
11 #include "base/command_line.h"
12 #include "base/debug/trace_event.h"
13 #include "base/logging.h"
14 #include "base/message_loop/message_loop.h"
15 #include "base/strings/string_number_conversions.h"
16 #include "cc/layers/layer.h"
17 #include "cc/output/copy_output_request.h"
18 #include "cc/output/copy_output_result.h"
19 #include "cc/resources/texture_mailbox.h"
20 #include "cc/trees/layer_tree_settings.h"
21 #include "content/browser/accessibility/browser_accessibility_manager.h"
22 #include "content/browser/accessibility/browser_accessibility_state_impl.h"
23 #include "content/browser/frame_host/frame_tree.h"
24 #include "content/browser/frame_host/frame_tree_node.h"
25 #include "content/browser/frame_host/render_frame_host_impl.h"
26 #include "content/browser/gpu/compositor_util.h"
27 #include "content/browser/renderer_host/compositor_resize_lock_aura.h"
28 #include "content/browser/renderer_host/dip_util.h"
29 #include "content/browser/renderer_host/input/synthetic_gesture_target_aura.h"
30 #include "content/browser/renderer_host/overscroll_controller.h"
31 #include "content/browser/renderer_host/render_view_host_delegate.h"
32 #include "content/browser/renderer_host/render_view_host_delegate_view.h"
33 #include "content/browser/renderer_host/render_view_host_impl.h"
34 #include "content/browser/renderer_host/render_widget_host_impl.h"
35 #include "content/browser/renderer_host/ui_events_helper.h"
36 #include "content/browser/renderer_host/web_input_event_aura.h"
37 #include "content/common/gpu/client/gl_helper.h"
38 #include "content/common/gpu/gpu_messages.h"
39 #include "content/common/view_messages.h"
40 #include "content/public/browser/content_browser_client.h"
41 #include "content/public/browser/overscroll_configuration.h"
42 #include "content/public/browser/render_view_host.h"
43 #include "content/public/browser/render_widget_host_view_frame_subscriber.h"
44 #include "content/public/browser/user_metrics.h"
45 #include "content/public/common/content_switches.h"
46 #include "third_party/WebKit/public/platform/WebScreenInfo.h"
47 #include "third_party/WebKit/public/web/WebCompositionUnderline.h"
48 #include "third_party/WebKit/public/web/WebInputEvent.h"
49 #include "ui/aura/client/aura_constants.h"
50 #include "ui/aura/client/cursor_client.h"
51 #include "ui/aura/client/cursor_client_observer.h"
52 #include "ui/aura/client/focus_client.h"
53 #include "ui/aura/client/screen_position_client.h"
54 #include "ui/aura/client/window_tree_client.h"
55 #include "ui/aura/env.h"
56 #include "ui/aura/window.h"
57 #include "ui/aura/window_event_dispatcher.h"
58 #include "ui/aura/window_observer.h"
59 #include "ui/aura/window_tracker.h"
60 #include "ui/aura/window_tree_host.h"
61 #include "ui/base/clipboard/scoped_clipboard_writer.h"
62 #include "ui/base/hit_test.h"
63 #include "ui/base/ime/input_method.h"
64 #include "ui/base/ui_base_types.h"
65 #include "ui/compositor/compositor_vsync_manager.h"
66 #include "ui/compositor/dip_util.h"
67 #include "ui/events/event.h"
68 #include "ui/events/event_utils.h"
69 #include "ui/events/gestures/gesture_recognizer.h"
70 #include "ui/gfx/canvas.h"
71 #include "ui/gfx/display.h"
72 #include "ui/gfx/rect_conversions.h"
73 #include "ui/gfx/screen.h"
74 #include "ui/gfx/size_conversions.h"
75 #include "ui/gfx/skia_util.h"
76 #include "ui/wm/public/activation_client.h"
77 #include "ui/wm/public/scoped_tooltip_disabler.h"
78 #include "ui/wm/public/tooltip_client.h"
79 #include "ui/wm/public/transient_window_client.h"
80 #include "ui/wm/public/window_types.h"
81
82 #if defined(OS_WIN)
83 #include "content/browser/accessibility/browser_accessibility_manager_win.h"
84 #include "content/browser/accessibility/browser_accessibility_win.h"
85 #include "content/browser/renderer_host/legacy_render_widget_host_win.h"
86 #include "content/common/plugin_constants_win.h"
87 #include "ui/base/win/hidden_window.h"
88 #include "ui/gfx/gdi_util.h"
89 #include "ui/gfx/win/dpi.h"
90 #endif
91
92 #if defined(OS_LINUX) && !defined(OS_CHROMEOS)
93 #include "content/common/input_messages.h"
94 #include "ui/events/linux/text_edit_command_auralinux.h"
95 #include "ui/events/linux/text_edit_key_bindings_delegate_auralinux.h"
96 #endif
97
98 using gfx::RectToSkIRect;
99 using gfx::SkIRectToRect;
100
101 using blink::WebScreenInfo;
102 using blink::WebInputEvent;
103 using blink::WebGestureEvent;
104 using blink::WebTouchEvent;
105
106 namespace content {
107
108 namespace {
109
110 // In mouse lock mode, we need to prevent the (invisible) cursor from hitting
111 // the border of the view, in order to get valid movement information. However,
112 // forcing the cursor back to the center of the view after each mouse move
113 // doesn't work well. It reduces the frequency of useful mouse move messages
114 // significantly. Therefore, we move the cursor to the center of the view only
115 // if it approaches the border. |kMouseLockBorderPercentage| specifies the width
116 // of the border area, in percentage of the corresponding dimension.
117 const int kMouseLockBorderPercentage = 15;
118
119 // When accelerated compositing is enabled and a widget resize is pending,
120 // we delay further resizes of the UI. The following constant is the maximum
121 // length of time that we should delay further UI resizes while waiting for a
122 // resized frame from a renderer.
123 const int kResizeLockTimeoutMs = 67;
124
125 #if defined(OS_WIN)
126 // Used to associate a plugin HWND with its RenderWidgetHostViewAura instance.
127 const wchar_t kWidgetOwnerProperty[] = L"RenderWidgetHostViewAuraOwner";
128
129 BOOL CALLBACK WindowDestroyingCallback(HWND window, LPARAM param) {
130   RenderWidgetHostViewAura* widget =
131       reinterpret_cast<RenderWidgetHostViewAura*>(param);
132   if (GetProp(window, kWidgetOwnerProperty) == widget) {
133     // Properties set on HWNDs must be removed to avoid leaks.
134     RemoveProp(window, kWidgetOwnerProperty);
135     RenderWidgetHostViewBase::DetachPluginWindowsCallback(window);
136   }
137   return TRUE;
138 }
139
140 BOOL CALLBACK HideWindowsCallback(HWND window, LPARAM param) {
141   RenderWidgetHostViewAura* widget =
142       reinterpret_cast<RenderWidgetHostViewAura*>(param);
143   if (GetProp(window, kWidgetOwnerProperty) == widget)
144     SetParent(window, ui::GetHiddenWindow());
145   return TRUE;
146 }
147
148 BOOL CALLBACK ShowWindowsCallback(HWND window, LPARAM param) {
149   RenderWidgetHostViewAura* widget =
150       reinterpret_cast<RenderWidgetHostViewAura*>(param);
151
152   if (GetProp(window, kWidgetOwnerProperty) == widget &&
153       widget->GetNativeView()->GetHost()) {
154     HWND parent = widget->GetNativeView()->GetHost()->GetAcceleratedWidget();
155     SetParent(window, parent);
156   }
157   return TRUE;
158 }
159
160 struct CutoutRectsParams {
161   RenderWidgetHostViewAura* widget;
162   std::vector<gfx::Rect> cutout_rects;
163   std::map<HWND, WebPluginGeometry>* geometry;
164 };
165
166 // Used to update the region for the windowed plugin to draw in. We start with
167 // the clip rect from the renderer, then remove the cutout rects from the
168 // renderer, and then remove the transient windows from the root window and the
169 // constrained windows from the parent window.
170 BOOL CALLBACK SetCutoutRectsCallback(HWND window, LPARAM param) {
171   CutoutRectsParams* params = reinterpret_cast<CutoutRectsParams*>(param);
172
173   if (GetProp(window, kWidgetOwnerProperty) == params->widget) {
174     // First calculate the offset of this plugin from the root window, since
175     // the cutouts are relative to the root window.
176     HWND parent =
177         params->widget->GetNativeView()->GetHost()->GetAcceleratedWidget();
178     POINT offset;
179     offset.x = offset.y = 0;
180     MapWindowPoints(window, parent, &offset, 1);
181
182     // Now get the cached clip rect and cutouts for this plugin window that came
183     // from the renderer.
184     std::map<HWND, WebPluginGeometry>::iterator i = params->geometry->begin();
185     while (i != params->geometry->end() &&
186            i->second.window != window &&
187            GetParent(i->second.window) != window) {
188       ++i;
189     }
190
191     if (i == params->geometry->end()) {
192       NOTREACHED();
193       return TRUE;
194     }
195
196     HRGN hrgn = CreateRectRgn(i->second.clip_rect.x(),
197                               i->second.clip_rect.y(),
198                               i->second.clip_rect.right(),
199                               i->second.clip_rect.bottom());
200     // We start with the cutout rects that came from the renderer, then add the
201     // ones that came from transient and constrained windows.
202     std::vector<gfx::Rect> cutout_rects = i->second.cutout_rects;
203     for (size_t i = 0; i < params->cutout_rects.size(); ++i) {
204       gfx::Rect offset_cutout = params->cutout_rects[i];
205       offset_cutout.Offset(-offset.x, -offset.y);
206       cutout_rects.push_back(offset_cutout);
207     }
208     gfx::SubtractRectanglesFromRegion(hrgn, cutout_rects);
209     // If we don't have any cutout rects then no point in messing with the
210     // window region.
211     if (cutout_rects.size())
212       SetWindowRgn(window, hrgn, TRUE);
213   }
214   return TRUE;
215 }
216
217 // A callback function for EnumThreadWindows to enumerate and dismiss
218 // any owned popup windows.
219 BOOL CALLBACK DismissOwnedPopups(HWND window, LPARAM arg) {
220   const HWND toplevel_hwnd = reinterpret_cast<HWND>(arg);
221
222   if (::IsWindowVisible(window)) {
223     const HWND owner = ::GetWindow(window, GW_OWNER);
224     if (toplevel_hwnd == owner) {
225       ::PostMessage(window, WM_CANCELMODE, 0, 0);
226     }
227   }
228
229   return TRUE;
230 }
231 #endif
232
233 void UpdateWebTouchEventAfterDispatch(blink::WebTouchEvent* event,
234                                       blink::WebTouchPoint* point) {
235   if (point->state != blink::WebTouchPoint::StateReleased &&
236       point->state != blink::WebTouchPoint::StateCancelled)
237     return;
238
239   const unsigned new_length = event->touchesLength - 1;
240   // Work around a gcc 4.9 bug. crbug.com/392872
241   if (new_length >= event->touchesLengthCap)
242     return;
243
244   for (unsigned i = point - event->touches; i < new_length; ++i)
245     event->touches[i] = event->touches[i + 1];
246   event->touchesLength = new_length;
247 }
248
249 bool CanRendererHandleEvent(const ui::MouseEvent* event) {
250   if (event->type() == ui::ET_MOUSE_CAPTURE_CHANGED)
251     return false;
252
253 #if defined(OS_WIN)
254   // Renderer cannot handle WM_XBUTTON or NC events.
255   switch (event->native_event().message) {
256     case WM_XBUTTONDOWN:
257     case WM_XBUTTONUP:
258     case WM_XBUTTONDBLCLK:
259     case WM_NCMOUSELEAVE:
260     case WM_NCMOUSEMOVE:
261     case WM_NCLBUTTONDOWN:
262     case WM_NCLBUTTONUP:
263     case WM_NCLBUTTONDBLCLK:
264     case WM_NCRBUTTONDOWN:
265     case WM_NCRBUTTONUP:
266     case WM_NCRBUTTONDBLCLK:
267     case WM_NCMBUTTONDOWN:
268     case WM_NCMBUTTONUP:
269     case WM_NCMBUTTONDBLCLK:
270     case WM_NCXBUTTONDOWN:
271     case WM_NCXBUTTONUP:
272     case WM_NCXBUTTONDBLCLK:
273       return false;
274     default:
275       break;
276   }
277 #elif defined(USE_X11)
278   // Renderer only supports standard mouse buttons, so ignore programmable
279   // buttons.
280   switch (event->type()) {
281     case ui::ET_MOUSE_PRESSED:
282     case ui::ET_MOUSE_RELEASED:
283       return event->IsAnyButton();
284     default:
285       break;
286   }
287 #endif
288   return true;
289 }
290
291 // We don't mark these as handled so that they're sent back to the
292 // DefWindowProc so it can generate WM_APPCOMMAND as necessary.
293 bool IsXButtonUpEvent(const ui::MouseEvent* event) {
294 #if defined(OS_WIN)
295   switch (event->native_event().message) {
296     case WM_XBUTTONUP:
297     case WM_NCXBUTTONUP:
298       return true;
299   }
300 #endif
301   return false;
302 }
303
304 void GetScreenInfoForWindow(WebScreenInfo* results, aura::Window* window) {
305   const gfx::Display display = window ?
306       gfx::Screen::GetScreenFor(window)->GetDisplayNearestWindow(window) :
307       gfx::Screen::GetScreenFor(window)->GetPrimaryDisplay();
308   results->rect = display.bounds();
309   results->availableRect = display.work_area();
310   // TODO(derat|oshima): Don't hardcode this. Get this from display object.
311   results->depth = 24;
312   results->depthPerComponent = 8;
313   results->deviceScaleFactor = display.device_scale_factor();
314
315   // The Display rotation and the WebScreenInfo orientation are not the same
316   // angle. The former is the physical display rotation while the later is the
317   // rotation required by the content to be shown properly on the screen, in
318   // other words, relative to the physical display.
319   results->orientationAngle = display.RotationAsDegree();
320   if (results->orientationAngle == 90)
321     results->orientationAngle = 270;
322   else if (results->orientationAngle == 270)
323     results->orientationAngle = 90;
324
325   results->orientationType =
326       RenderWidgetHostViewBase::GetOrientationTypeForDesktop(display);
327 }
328
329 bool PointerEventActivates(const ui::Event& event) {
330   if (event.type() == ui::ET_MOUSE_PRESSED)
331     return true;
332
333   if (event.type() == ui::ET_GESTURE_BEGIN) {
334     const ui::GestureEvent& gesture =
335         static_cast<const ui::GestureEvent&>(event);
336     return gesture.details().touch_points() == 1;
337   }
338
339   return false;
340 }
341
342 }  // namespace
343
344 // We need to watch for mouse events outside a Web Popup or its parent
345 // and dismiss the popup for certain events.
346 class RenderWidgetHostViewAura::EventFilterForPopupExit
347     : public ui::EventHandler {
348  public:
349   explicit EventFilterForPopupExit(RenderWidgetHostViewAura* rwhva)
350       : rwhva_(rwhva) {
351     DCHECK(rwhva_);
352     aura::Env::GetInstance()->AddPreTargetHandler(this);
353   }
354
355   virtual ~EventFilterForPopupExit() {
356     aura::Env::GetInstance()->RemovePreTargetHandler(this);
357   }
358
359   // Overridden from ui::EventHandler
360   virtual void OnMouseEvent(ui::MouseEvent* event) OVERRIDE {
361     rwhva_->ApplyEventFilterForPopupExit(event);
362   }
363
364   virtual void OnTouchEvent(ui::TouchEvent* event) OVERRIDE {
365     rwhva_->ApplyEventFilterForPopupExit(event);
366   }
367
368  private:
369   RenderWidgetHostViewAura* rwhva_;
370
371   DISALLOW_COPY_AND_ASSIGN(EventFilterForPopupExit);
372 };
373
374 void RenderWidgetHostViewAura::ApplyEventFilterForPopupExit(
375     ui::LocatedEvent* event) {
376   if (in_shutdown_ || is_fullscreen_ || !event->target())
377     return;
378
379   if (event->type() != ui::ET_MOUSE_PRESSED &&
380       event->type() != ui::ET_TOUCH_PRESSED) {
381     return;
382   }
383
384   aura::Window* target = static_cast<aura::Window*>(event->target());
385   if (target != window_ &&
386       (!popup_parent_host_view_ ||
387        target != popup_parent_host_view_->window_)) {
388     // Note: popup_parent_host_view_ may be NULL when there are multiple
389     // popup children per view. See: RenderWidgetHostViewAura::InitAsPopup().
390     in_shutdown_ = true;
391     host_->Shutdown();
392   }
393 }
394
395 // We have to implement the WindowObserver interface on a separate object
396 // because clang doesn't like implementing multiple interfaces that have
397 // methods with the same name. This object is owned by the
398 // RenderWidgetHostViewAura.
399 class RenderWidgetHostViewAura::WindowObserver : public aura::WindowObserver {
400  public:
401   explicit WindowObserver(RenderWidgetHostViewAura* view)
402       : view_(view) {
403     view_->window_->AddObserver(this);
404   }
405
406   virtual ~WindowObserver() {
407     view_->window_->RemoveObserver(this);
408   }
409
410   // Overridden from aura::WindowObserver:
411   virtual void OnWindowAddedToRootWindow(aura::Window* window) OVERRIDE {
412     if (window == view_->window_)
413       view_->AddedToRootWindow();
414   }
415
416   virtual void OnWindowRemovingFromRootWindow(aura::Window* window,
417                                               aura::Window* new_root) OVERRIDE {
418     if (window == view_->window_)
419       view_->RemovingFromRootWindow();
420   }
421
422  private:
423   RenderWidgetHostViewAura* view_;
424
425   DISALLOW_COPY_AND_ASSIGN(WindowObserver);
426 };
427
428 ////////////////////////////////////////////////////////////////////////////////
429 // RenderWidgetHostViewAura, public:
430
431 RenderWidgetHostViewAura::RenderWidgetHostViewAura(RenderWidgetHost* host)
432     : host_(RenderWidgetHostImpl::From(host)),
433       window_(new aura::Window(this)),
434       delegated_frame_host_(new DelegatedFrameHost(this)),
435       in_shutdown_(false),
436       in_bounds_changed_(false),
437       is_fullscreen_(false),
438       popup_parent_host_view_(NULL),
439       popup_child_host_view_(NULL),
440       is_loading_(false),
441       text_input_type_(ui::TEXT_INPUT_TYPE_NONE),
442       text_input_mode_(ui::TEXT_INPUT_MODE_DEFAULT),
443       can_compose_inline_(true),
444       has_composition_text_(false),
445       accept_return_character_(false),
446       last_swapped_software_frame_scale_factor_(1.f),
447       paint_canvas_(NULL),
448       synthetic_move_sent_(false),
449       cursor_visibility_state_in_renderer_(UNKNOWN),
450 #if defined(OS_WIN)
451       legacy_render_widget_host_HWND_(NULL),
452       legacy_window_destroyed_(false),
453 #endif
454       has_snapped_to_boundary_(false),
455       touch_editing_client_(NULL),
456       weak_ptr_factory_(this) {
457   host_->SetView(this);
458   window_observer_.reset(new WindowObserver(this));
459   aura::client::SetTooltipText(window_, &tooltip_);
460   aura::client::SetActivationDelegate(window_, this);
461   aura::client::SetActivationChangeObserver(window_, this);
462   aura::client::SetFocusChangeObserver(window_, this);
463   window_->set_layer_owner_delegate(delegated_frame_host_.get());
464   gfx::Screen::GetScreenFor(window_)->AddObserver(this);
465
466   bool overscroll_enabled = base::CommandLine::ForCurrentProcess()->
467       GetSwitchValueASCII(switches::kOverscrollHistoryNavigation) != "0";
468   SetOverscrollControllerEnabled(overscroll_enabled);
469 }
470
471 ////////////////////////////////////////////////////////////////////////////////
472 // RenderWidgetHostViewAura, RenderWidgetHostView implementation:
473
474 void RenderWidgetHostViewAura::InitAsChild(
475     gfx::NativeView parent_view) {
476   window_->SetType(ui::wm::WINDOW_TYPE_CONTROL);
477   window_->Init(aura::WINDOW_LAYER_TEXTURED);
478   window_->SetName("RenderWidgetHostViewAura");
479 }
480
481 void RenderWidgetHostViewAura::InitAsPopup(
482     RenderWidgetHostView* parent_host_view,
483     const gfx::Rect& bounds_in_screen) {
484   popup_parent_host_view_ =
485       static_cast<RenderWidgetHostViewAura*>(parent_host_view);
486
487   // TransientWindowClient may be NULL during tests.
488   aura::client::TransientWindowClient* transient_window_client =
489       aura::client::GetTransientWindowClient();
490   RenderWidgetHostViewAura* old_child =
491       popup_parent_host_view_->popup_child_host_view_;
492   if (old_child) {
493     // TODO(jhorwich): Allow multiple popup_child_host_view_ per view, or
494     // similar mechanism to ensure a second popup doesn't cause the first one
495     // to never get a chance to filter events. See crbug.com/160589.
496     DCHECK(old_child->popup_parent_host_view_ == popup_parent_host_view_);
497     if (transient_window_client) {
498       transient_window_client->RemoveTransientChild(
499         popup_parent_host_view_->window_, old_child->window_);
500     }
501     old_child->popup_parent_host_view_ = NULL;
502   }
503   popup_parent_host_view_->popup_child_host_view_ = this;
504   window_->SetType(ui::wm::WINDOW_TYPE_MENU);
505   window_->Init(aura::WINDOW_LAYER_TEXTURED);
506   window_->SetName("RenderWidgetHostViewAura");
507
508   aura::Window* root = popup_parent_host_view_->window_->GetRootWindow();
509   aura::client::ParentWindowWithContext(window_, root, bounds_in_screen);
510   // Setting the transient child allows for the popup to get mouse events when
511   // in a system modal dialog.
512   // This fixes crbug.com/328593.
513   if (transient_window_client) {
514     transient_window_client->AddTransientChild(
515         popup_parent_host_view_->window_, window_);
516   }
517
518   SetBounds(bounds_in_screen);
519   Show();
520 #if !defined(OS_WIN) && !defined(OS_CHROMEOS)
521   if (NeedsInputGrab())
522     window_->SetCapture();
523 #endif
524
525   event_filter_for_popup_exit_.reset(new EventFilterForPopupExit(this));
526 }
527
528 void RenderWidgetHostViewAura::InitAsFullscreen(
529     RenderWidgetHostView* reference_host_view) {
530   is_fullscreen_ = true;
531   window_->SetType(ui::wm::WINDOW_TYPE_NORMAL);
532   window_->Init(aura::WINDOW_LAYER_TEXTURED);
533   window_->SetName("RenderWidgetHostViewAura");
534   window_->SetProperty(aura::client::kShowStateKey, ui::SHOW_STATE_FULLSCREEN);
535
536   aura::Window* parent = NULL;
537   gfx::Rect bounds;
538   if (reference_host_view) {
539     aura::Window* reference_window =
540         static_cast<RenderWidgetHostViewAura*>(reference_host_view)->window_;
541     if (reference_window) {
542       host_tracker_.reset(new aura::WindowTracker);
543       host_tracker_->Add(reference_window);
544     }
545     gfx::Display display = gfx::Screen::GetScreenFor(window_)->
546         GetDisplayNearestWindow(reference_window);
547     parent = reference_window->GetRootWindow();
548     bounds = display.bounds();
549   }
550   aura::client::ParentWindowWithContext(window_, parent, bounds);
551   Show();
552   Focus();
553 }
554
555 RenderWidgetHost* RenderWidgetHostViewAura::GetRenderWidgetHost() const {
556   return host_;
557 }
558
559 void RenderWidgetHostViewAura::WasShown() {
560   DCHECK(host_);
561   if (!host_->is_hidden())
562     return;
563
564   bool has_saved_frame = delegated_frame_host_->HasSavedFrame();
565   ui::LatencyInfo renderer_latency_info, browser_latency_info;
566   if (has_saved_frame) {
567     browser_latency_info.AddLatencyNumber(
568         ui::TAB_SHOW_COMPONENT, host_->GetLatencyComponentId(), 0);
569   } else {
570     renderer_latency_info.AddLatencyNumber(
571         ui::TAB_SHOW_COMPONENT, host_->GetLatencyComponentId(), 0);
572   }
573   host_->WasShown(renderer_latency_info);
574
575   aura::Window* root = window_->GetRootWindow();
576   if (root) {
577     aura::client::CursorClient* cursor_client =
578         aura::client::GetCursorClient(root);
579     if (cursor_client)
580       NotifyRendererOfCursorVisibilityState(cursor_client->IsCursorVisible());
581   }
582
583   delegated_frame_host_->WasShown(browser_latency_info);
584
585 #if defined(OS_WIN)
586   if (legacy_render_widget_host_HWND_) {
587     // Reparent the legacy Chrome_RenderWidgetHostHWND window to the parent
588     // window before reparenting any plugins. This ensures that the plugin
589     // windows stay on top of the child Zorder in the parent and receive
590     // mouse events, etc.
591     legacy_render_widget_host_HWND_->UpdateParent(
592         GetNativeView()->GetHost()->GetAcceleratedWidget());
593     legacy_render_widget_host_HWND_->SetBounds(
594         window_->GetBoundsInRootWindow());
595   }
596   LPARAM lparam = reinterpret_cast<LPARAM>(this);
597   EnumChildWindows(ui::GetHiddenWindow(), ShowWindowsCallback, lparam);
598 #endif
599 }
600
601 void RenderWidgetHostViewAura::WasHidden() {
602   if (!host_ || host_->is_hidden())
603     return;
604   host_->WasHidden();
605   delegated_frame_host_->WasHidden();
606
607 #if defined(OS_WIN)
608   constrained_rects_.clear();
609   aura::WindowTreeHost* host = window_->GetHost();
610   if (host) {
611     HWND parent = host->GetAcceleratedWidget();
612     LPARAM lparam = reinterpret_cast<LPARAM>(this);
613     EnumChildWindows(parent, HideWindowsCallback, lparam);
614     // We reparent the legacy Chrome_RenderWidgetHostHWND window to the global
615     // hidden window on the same lines as Windowed plugin windows.
616     if (legacy_render_widget_host_HWND_)
617       legacy_render_widget_host_HWND_->UpdateParent(ui::GetHiddenWindow());
618   }
619 #endif
620 }
621
622 void RenderWidgetHostViewAura::SetSize(const gfx::Size& size) {
623   // For a SetSize operation, we don't care what coordinate system the origin
624   // of the window is in, it's only important to make sure that the origin
625   // remains constant after the operation.
626   InternalSetBounds(gfx::Rect(window_->bounds().origin(), size));
627 }
628
629 void RenderWidgetHostViewAura::SetBounds(const gfx::Rect& rect) {
630   gfx::Point relative_origin(rect.origin());
631
632   // RenderWidgetHostViewAura::SetBounds() takes screen coordinates, but
633   // Window::SetBounds() takes parent coordinates, so do the conversion here.
634   aura::Window* root = window_->GetRootWindow();
635   if (root) {
636     aura::client::ScreenPositionClient* screen_position_client =
637         aura::client::GetScreenPositionClient(root);
638     if (screen_position_client) {
639       screen_position_client->ConvertPointFromScreen(
640           window_->parent(), &relative_origin);
641     }
642   }
643
644   InternalSetBounds(gfx::Rect(relative_origin, rect.size()));
645 }
646
647 gfx::Vector2dF RenderWidgetHostViewAura::GetLastScrollOffset() const {
648   return last_scroll_offset_;
649 }
650
651 gfx::NativeView RenderWidgetHostViewAura::GetNativeView() const {
652   return window_;
653 }
654
655 gfx::NativeViewId RenderWidgetHostViewAura::GetNativeViewId() const {
656 #if defined(OS_WIN)
657   aura::WindowTreeHost* host = window_->GetHost();
658   if (host)
659     return reinterpret_cast<gfx::NativeViewId>(host->GetAcceleratedWidget());
660 #endif
661   return static_cast<gfx::NativeViewId>(NULL);
662 }
663
664 gfx::NativeViewAccessible RenderWidgetHostViewAura::GetNativeViewAccessible() {
665 #if defined(OS_WIN)
666   aura::WindowTreeHost* host = window_->GetHost();
667   if (!host)
668     return static_cast<gfx::NativeViewAccessible>(NULL);
669   HWND hwnd = host->GetAcceleratedWidget();
670   BrowserAccessibilityManager* manager =
671       host_->GetOrCreateRootBrowserAccessibilityManager();
672   if (manager)
673     return manager->GetRoot()->ToBrowserAccessibilityWin();
674 #endif
675
676   NOTIMPLEMENTED();
677   return static_cast<gfx::NativeViewAccessible>(NULL);
678 }
679
680 ui::TextInputClient* RenderWidgetHostViewAura::GetTextInputClient() {
681   return this;
682 }
683
684 void RenderWidgetHostViewAura::SetKeyboardFocus() {
685 #if defined(OS_WIN)
686   if (CanFocus()) {
687     aura::WindowTreeHost* host = window_->GetHost();
688     if (host)
689       ::SetFocus(host->GetAcceleratedWidget());
690   }
691 #endif
692 }
693
694 RenderFrameHostImpl* RenderWidgetHostViewAura::GetFocusedFrame() {
695   if (!host_->IsRenderView())
696     return NULL;
697   RenderViewHost* rvh = RenderViewHost::From(host_);
698   FrameTreeNode* focused_frame =
699       rvh->GetDelegate()->GetFrameTree()->GetFocusedFrame();
700   if (!focused_frame)
701     return NULL;
702
703   return focused_frame->current_frame_host();
704 }
705
706 void RenderWidgetHostViewAura::MovePluginWindows(
707     const std::vector<WebPluginGeometry>& plugin_window_moves) {
708 #if defined(OS_WIN)
709   // We need to clip the rectangle to the tab's viewport, otherwise we will draw
710   // over the browser UI.
711   if (!window_->GetRootWindow()) {
712     DCHECK(plugin_window_moves.empty());
713     return;
714   }
715   HWND parent = window_->GetHost()->GetAcceleratedWidget();
716   gfx::Rect view_bounds = window_->GetBoundsInRootWindow();
717   std::vector<WebPluginGeometry> moves = plugin_window_moves;
718
719   gfx::Rect view_port(view_bounds.size());
720
721   for (size_t i = 0; i < moves.size(); ++i) {
722     gfx::Rect clip(moves[i].clip_rect);
723     gfx::Vector2d view_port_offset(
724         moves[i].window_rect.OffsetFromOrigin());
725     clip.Offset(view_port_offset);
726     clip.Intersect(view_port);
727     clip.Offset(-view_port_offset);
728     moves[i].clip_rect = clip;
729
730     moves[i].window_rect.Offset(view_bounds.OffsetFromOrigin());
731
732     plugin_window_moves_[moves[i].window] = moves[i];
733
734     // constrained_rects_ are relative to the root window. We want to convert
735     // them to be relative to the plugin window.
736     for (size_t j = 0; j < constrained_rects_.size(); ++j) {
737       gfx::Rect offset_cutout = constrained_rects_[j];
738       offset_cutout -= moves[i].window_rect.OffsetFromOrigin();
739       moves[i].cutout_rects.push_back(offset_cutout);
740     }
741   }
742
743   MovePluginWindowsHelper(parent, moves);
744
745   // Make sure each plugin window (or its wrapper if it exists) has a pointer to
746   // |this|.
747   for (size_t i = 0; i < moves.size(); ++i) {
748     HWND window = moves[i].window;
749     if (GetParent(window) != parent) {
750       window = GetParent(window);
751     }
752     if (!GetProp(window, kWidgetOwnerProperty))
753       SetProp(window, kWidgetOwnerProperty, this);
754   }
755 #endif  // defined(OS_WIN)
756 }
757
758 void RenderWidgetHostViewAura::Focus() {
759   // Make sure we have a FocusClient before attempting to Focus(). In some
760   // situations we may not yet be in a valid Window hierarchy (such as reloading
761   // after out of memory discarded the tab).
762   aura::client::FocusClient* client = aura::client::GetFocusClient(window_);
763   if (client)
764     window_->Focus();
765 }
766
767 void RenderWidgetHostViewAura::Blur() {
768   window_->Blur();
769 }
770
771 bool RenderWidgetHostViewAura::HasFocus() const {
772   return window_->HasFocus();
773 }
774
775 bool RenderWidgetHostViewAura::IsSurfaceAvailableForCopy() const {
776   return delegated_frame_host_->CanCopyToBitmap();
777 }
778
779 void RenderWidgetHostViewAura::Show() {
780   window_->Show();
781   WasShown();
782 #if defined(OS_WIN)
783   if (legacy_render_widget_host_HWND_)
784     legacy_render_widget_host_HWND_->Show();
785 #endif
786 }
787
788 void RenderWidgetHostViewAura::Hide() {
789   window_->Hide();
790   WasHidden();
791 #if defined(OS_WIN)
792   if (legacy_render_widget_host_HWND_)
793     legacy_render_widget_host_HWND_->Hide();
794 #endif
795 }
796
797 bool RenderWidgetHostViewAura::IsShowing() {
798   return window_->IsVisible();
799 }
800
801 gfx::Rect RenderWidgetHostViewAura::GetViewBounds() const {
802   return window_->GetBoundsInScreen();
803 }
804
805 void RenderWidgetHostViewAura::SetBackgroundOpaque(bool opaque) {
806   RenderWidgetHostViewBase::SetBackgroundOpaque(opaque);
807   host_->SetBackgroundOpaque(opaque);
808   window_->layer()->SetFillsBoundsOpaquely(opaque);
809 }
810
811 gfx::Size RenderWidgetHostViewAura::GetVisibleViewportSize() const {
812   gfx::Rect requested_rect(GetRequestedRendererSize());
813   requested_rect.Inset(insets_);
814   return requested_rect.size();
815 }
816
817 void RenderWidgetHostViewAura::SetInsets(const gfx::Insets& insets) {
818   if (insets != insets_) {
819     insets_ = insets;
820     host_->WasResized();
821   }
822 }
823
824 void RenderWidgetHostViewAura::UpdateCursor(const WebCursor& cursor) {
825   current_cursor_ = cursor;
826   const gfx::Display display = gfx::Screen::GetScreenFor(window_)->
827       GetDisplayNearestWindow(window_);
828   current_cursor_.SetDisplayInfo(display);
829   UpdateCursorIfOverSelf();
830 }
831
832 void RenderWidgetHostViewAura::SetIsLoading(bool is_loading) {
833   is_loading_ = is_loading;
834   UpdateCursorIfOverSelf();
835 }
836
837 void RenderWidgetHostViewAura::TextInputStateChanged(
838     const ViewHostMsg_TextInputState_Params& params) {
839   if (text_input_type_ != params.type ||
840       text_input_mode_ != params.mode ||
841       can_compose_inline_ != params.can_compose_inline) {
842     text_input_type_ = params.type;
843     text_input_mode_ = params.mode;
844     can_compose_inline_ = params.can_compose_inline;
845     if (GetInputMethod())
846       GetInputMethod()->OnTextInputTypeChanged(this);
847     if (touch_editing_client_)
848       touch_editing_client_->OnTextInputTypeChanged(text_input_type_);
849   }
850   if (params.show_ime_if_needed && params.type != ui::TEXT_INPUT_TYPE_NONE) {
851     if (GetInputMethod())
852       GetInputMethod()->ShowImeIfNeeded();
853   }
854 }
855
856 void RenderWidgetHostViewAura::ImeCancelComposition() {
857   if (GetInputMethod())
858     GetInputMethod()->CancelComposition(this);
859   has_composition_text_ = false;
860 }
861
862 void RenderWidgetHostViewAura::ImeCompositionRangeChanged(
863     const gfx::Range& range,
864     const std::vector<gfx::Rect>& character_bounds) {
865   composition_character_bounds_ = character_bounds;
866 }
867
868 void RenderWidgetHostViewAura::RenderProcessGone(base::TerminationStatus status,
869                                                  int error_code) {
870   UpdateCursorIfOverSelf();
871   Destroy();
872 }
873
874 void RenderWidgetHostViewAura::Destroy() {
875   // Beware, this function is not called on all destruction paths. It will
876   // implicitly end up calling ~RenderWidgetHostViewAura though, so all
877   // destruction/cleanup code should happen there, not here.
878   in_shutdown_ = true;
879   delete window_;
880 }
881
882 void RenderWidgetHostViewAura::SetTooltipText(
883     const base::string16& tooltip_text) {
884   tooltip_ = tooltip_text;
885   aura::Window* root_window = window_->GetRootWindow();
886   aura::client::TooltipClient* tooltip_client =
887       aura::client::GetTooltipClient(root_window);
888   if (tooltip_client) {
889     tooltip_client->UpdateTooltip(window_);
890     // Content tooltips should be visible indefinitely.
891     tooltip_client->SetTooltipShownTimeout(window_, 0);
892   }
893 }
894
895 void RenderWidgetHostViewAura::SelectionChanged(const base::string16& text,
896                                                 size_t offset,
897                                                 const gfx::Range& range) {
898   RenderWidgetHostViewBase::SelectionChanged(text, offset, range);
899
900 #if defined(USE_X11) && !defined(OS_CHROMEOS)
901   if (text.empty() || range.is_empty())
902     return;
903   size_t pos = range.GetMin() - offset;
904   size_t n = range.length();
905
906   DCHECK(pos + n <= text.length()) << "The text can not fully cover range.";
907   if (pos >= text.length()) {
908     NOTREACHED() << "The text can not cover range.";
909     return;
910   }
911
912   // Set the CLIPBOARD_TYPE_SELECTION to the ui::Clipboard.
913   ui::ScopedClipboardWriter clipboard_writer(ui::CLIPBOARD_TYPE_SELECTION);
914   clipboard_writer.WriteText(text.substr(pos, n));
915 #endif  // defined(USE_X11) && !defined(OS_CHROMEOS)
916 }
917
918 gfx::Size RenderWidgetHostViewAura::GetRequestedRendererSize() const {
919   return delegated_frame_host_->GetRequestedRendererSize();
920 }
921
922 void RenderWidgetHostViewAura::SelectionBoundsChanged(
923     const ViewHostMsg_SelectionBounds_Params& params) {
924   if (selection_anchor_rect_ == params.anchor_rect &&
925       selection_focus_rect_ == params.focus_rect)
926     return;
927
928   selection_anchor_rect_ = params.anchor_rect;
929   selection_focus_rect_ = params.focus_rect;
930
931   if (GetInputMethod())
932     GetInputMethod()->OnCaretBoundsChanged(this);
933
934   if (touch_editing_client_) {
935     touch_editing_client_->OnSelectionOrCursorChanged(selection_anchor_rect_,
936         selection_focus_rect_);
937   }
938 }
939
940 void RenderWidgetHostViewAura::CopyFromCompositingSurface(
941     const gfx::Rect& src_subrect,
942     const gfx::Size& dst_size,
943     CopyFromCompositingSurfaceCallback& callback,
944     const SkColorType color_type) {
945   delegated_frame_host_->CopyFromCompositingSurface(
946       src_subrect, dst_size, callback, color_type);
947 }
948
949 void RenderWidgetHostViewAura::CopyFromCompositingSurfaceToVideoFrame(
950       const gfx::Rect& src_subrect,
951       const scoped_refptr<media::VideoFrame>& target,
952       const base::Callback<void(bool)>& callback) {
953   delegated_frame_host_->CopyFromCompositingSurfaceToVideoFrame(
954       src_subrect, target, callback);
955 }
956
957 bool RenderWidgetHostViewAura::CanCopyToVideoFrame() const {
958   return delegated_frame_host_->CanCopyToVideoFrame();
959 }
960
961 bool RenderWidgetHostViewAura::CanSubscribeFrame() const {
962   return delegated_frame_host_->CanSubscribeFrame();
963 }
964
965 void RenderWidgetHostViewAura::BeginFrameSubscription(
966     scoped_ptr<RenderWidgetHostViewFrameSubscriber> subscriber) {
967   delegated_frame_host_->BeginFrameSubscription(subscriber.Pass());
968 }
969
970 void RenderWidgetHostViewAura::EndFrameSubscription() {
971   delegated_frame_host_->EndFrameSubscription();
972 }
973
974 void RenderWidgetHostViewAura::AcceleratedSurfaceInitialized(int host_id,
975                                                              int route_id) {
976 }
977
978 #if defined(OS_WIN)
979 bool RenderWidgetHostViewAura::UsesNativeWindowFrame() const {
980   return (legacy_render_widget_host_HWND_ != NULL);
981 }
982
983 void RenderWidgetHostViewAura::UpdateConstrainedWindowRects(
984     const std::vector<gfx::Rect>& rects) {
985   // Check this before setting constrained_rects_, so that next time they're set
986   // and we have a root window we don't early return.
987   if (!window_->GetHost())
988     return;
989
990   if (rects == constrained_rects_)
991     return;
992
993   constrained_rects_ = rects;
994
995   HWND parent = window_->GetHost()->GetAcceleratedWidget();
996   CutoutRectsParams params;
997   params.widget = this;
998   params.cutout_rects = constrained_rects_;
999   params.geometry = &plugin_window_moves_;
1000   LPARAM lparam = reinterpret_cast<LPARAM>(&params);
1001   EnumChildWindows(parent, SetCutoutRectsCallback, lparam);
1002 }
1003
1004 void RenderWidgetHostViewAura::UpdateMouseLockRegion() {
1005   // Clip the cursor if chrome is running on regular desktop.
1006   if (gfx::Screen::GetScreenFor(window_) == gfx::Screen::GetNativeScreen()) {
1007     RECT window_rect = window_->GetBoundsInScreen().ToRECT();
1008     ::ClipCursor(&window_rect);
1009   }
1010 }
1011
1012 void RenderWidgetHostViewAura::OnLegacyWindowDestroyed() {
1013   legacy_render_widget_host_HWND_ = NULL;
1014   legacy_window_destroyed_ = true;
1015 }
1016 #endif
1017
1018 void RenderWidgetHostViewAura::AcceleratedSurfaceBuffersSwapped(
1019     const GpuHostMsg_AcceleratedSurfaceBuffersSwapped_Params& params_in_pixel,
1020     int gpu_host_id) {
1021   // Oldschool composited mode is no longer supported.
1022 }
1023
1024 void RenderWidgetHostViewAura::OnSwapCompositorFrame(
1025     uint32 output_surface_id,
1026     scoped_ptr<cc::CompositorFrame> frame) {
1027   TRACE_EVENT0("content", "RenderWidgetHostViewAura::OnSwapCompositorFrame");
1028
1029   last_scroll_offset_ = frame->metadata.root_scroll_offset;
1030   if (frame->delegated_frame_data) {
1031     delegated_frame_host_->SwapDelegatedFrame(
1032         output_surface_id,
1033         frame->delegated_frame_data.Pass(),
1034         frame->metadata.device_scale_factor,
1035         frame->metadata.latency_info);
1036     return;
1037   }
1038
1039   if (frame->software_frame_data) {
1040     DLOG(ERROR) << "Unable to use software frame in aura";
1041     RecordAction(
1042         base::UserMetricsAction("BadMessageTerminate_SharedMemoryAura"));
1043     host_->GetProcess()->ReceivedBadMessage();
1044     return;
1045   }
1046 }
1047
1048 void RenderWidgetHostViewAura::DidStopFlinging() {
1049   if (touch_editing_client_)
1050     touch_editing_client_->DidStopFlinging();
1051 }
1052
1053 #if defined(OS_WIN)
1054 void RenderWidgetHostViewAura::SetParentNativeViewAccessible(
1055     gfx::NativeViewAccessible accessible_parent) {
1056 }
1057
1058 gfx::NativeViewId RenderWidgetHostViewAura::GetParentForWindowlessPlugin()
1059     const {
1060   if (legacy_render_widget_host_HWND_) {
1061     return reinterpret_cast<gfx::NativeViewId>(
1062         legacy_render_widget_host_HWND_->hwnd());
1063   }
1064   return NULL;
1065 }
1066 #endif
1067
1068 void RenderWidgetHostViewAura::AcceleratedSurfacePostSubBuffer(
1069     const GpuHostMsg_AcceleratedSurfacePostSubBuffer_Params& params_in_pixel,
1070     int gpu_host_id) {
1071   // Oldschool composited mode is no longer supported.
1072 }
1073
1074 void RenderWidgetHostViewAura::AcceleratedSurfaceSuspend() {
1075 }
1076
1077 void RenderWidgetHostViewAura::AcceleratedSurfaceRelease() {
1078 }
1079
1080 bool RenderWidgetHostViewAura::HasAcceleratedSurface(
1081     const gfx::Size& desired_size) {
1082   // Aura doesn't use GetBackingStore for accelerated pages, so it doesn't
1083   // matter what is returned here as GetBackingStore is the only caller of this
1084   // method. TODO(jbates) implement this if other Aura code needs it.
1085   return false;
1086 }
1087
1088 void RenderWidgetHostViewAura::GetScreenInfo(WebScreenInfo* results) {
1089   GetScreenInfoForWindow(results, window_->GetRootWindow() ? window_ : NULL);
1090 }
1091
1092 gfx::Rect RenderWidgetHostViewAura::GetBoundsInRootWindow() {
1093   aura::Window* top_level = window_->GetToplevelWindow();
1094   gfx::Rect bounds(top_level->GetBoundsInScreen());
1095
1096 #if defined(OS_WIN)
1097   // TODO(zturner,iyengar): This will break when we remove support for NPAPI and
1098   // remove the legacy hwnd, so a better fix will need to be decided when that
1099   // happens.
1100   if (UsesNativeWindowFrame()) {
1101     // aura::Window doesn't take into account non-client area of native windows
1102     // (e.g. HWNDs), so for that case ask Windows directly what the bounds are.
1103     aura::WindowTreeHost* host = top_level->GetHost();
1104     if (!host)
1105       return top_level->GetBoundsInScreen();
1106     RECT window_rect = {0};
1107     HWND hwnd = host->GetAcceleratedWidget();
1108     ::GetWindowRect(hwnd, &window_rect);
1109     bounds = gfx::Rect(window_rect);
1110
1111     // Maximized windows are outdented from the work area by the frame thickness
1112     // even though this "frame" is not painted.  This confuses code (and people)
1113     // that think of a maximized window as corresponding exactly to the work
1114     // area.  Correct for this by subtracting the frame thickness back off.
1115     if (::IsZoomed(hwnd)) {
1116       bounds.Inset(GetSystemMetrics(SM_CXSIZEFRAME),
1117                    GetSystemMetrics(SM_CYSIZEFRAME));
1118
1119       bounds.Inset(GetSystemMetrics(SM_CXPADDEDBORDER),
1120                    GetSystemMetrics(SM_CXPADDEDBORDER));
1121     }
1122   }
1123
1124   bounds = gfx::win::ScreenToDIPRect(bounds);
1125 #endif
1126
1127   return bounds;
1128 }
1129
1130 void RenderWidgetHostViewAura::WheelEventAck(
1131     const blink::WebMouseWheelEvent& event,
1132     InputEventAckState ack_result) {
1133   if (overscroll_controller_) {
1134     overscroll_controller_->ReceivedEventACK(
1135         event, (INPUT_EVENT_ACK_STATE_CONSUMED == ack_result));
1136   }
1137 }
1138
1139 void RenderWidgetHostViewAura::GestureEventAck(
1140     const blink::WebGestureEvent& event,
1141     InputEventAckState ack_result) {
1142   if (touch_editing_client_)
1143     touch_editing_client_->GestureEventAck(event.type);
1144
1145   if (overscroll_controller_) {
1146     overscroll_controller_->ReceivedEventACK(
1147         event, (INPUT_EVENT_ACK_STATE_CONSUMED == ack_result));
1148   }
1149 }
1150
1151 void RenderWidgetHostViewAura::ProcessAckedTouchEvent(
1152     const TouchEventWithLatencyInfo& touch, InputEventAckState ack_result) {
1153   ScopedVector<ui::TouchEvent> events;
1154   if (!MakeUITouchEventsFromWebTouchEvents(touch, &events,
1155                                            SCREEN_COORDINATES))
1156     return;
1157
1158   aura::WindowTreeHost* host = window_->GetHost();
1159   // |host| is NULL during tests.
1160   if (!host)
1161     return;
1162
1163   ui::EventResult result = (ack_result ==
1164       INPUT_EVENT_ACK_STATE_CONSUMED) ? ui::ER_HANDLED : ui::ER_UNHANDLED;
1165   for (ScopedVector<ui::TouchEvent>::iterator iter = events.begin(),
1166       end = events.end(); iter != end; ++iter) {
1167     host->dispatcher()->ProcessedTouchEvent((*iter), window_, result);
1168   }
1169 }
1170
1171 scoped_ptr<SyntheticGestureTarget>
1172 RenderWidgetHostViewAura::CreateSyntheticGestureTarget() {
1173   return scoped_ptr<SyntheticGestureTarget>(
1174       new SyntheticGestureTargetAura(host_));
1175 }
1176
1177 InputEventAckState RenderWidgetHostViewAura::FilterInputEvent(
1178     const blink::WebInputEvent& input_event) {
1179   bool consumed = false;
1180   if (input_event.type == WebInputEvent::GestureFlingStart) {
1181     const WebGestureEvent& gesture_event =
1182         static_cast<const WebGestureEvent&>(input_event);
1183     // Zero-velocity touchpad flings are an Aura-specific signal that the
1184     // touchpad scroll has ended, and should not be forwarded to the renderer.
1185     if (gesture_event.sourceDevice == blink::WebGestureDeviceTouchpad &&
1186         !gesture_event.data.flingStart.velocityX &&
1187         !gesture_event.data.flingStart.velocityY) {
1188       consumed = true;
1189     }
1190   }
1191
1192   if (overscroll_controller_)
1193     consumed |= overscroll_controller_->WillHandleEvent(input_event);
1194
1195   return consumed && !WebTouchEvent::isTouchEventType(input_event.type)
1196              ? INPUT_EVENT_ACK_STATE_CONSUMED
1197              : INPUT_EVENT_ACK_STATE_NOT_CONSUMED;
1198 }
1199
1200 BrowserAccessibilityManager*
1201 RenderWidgetHostViewAura::CreateBrowserAccessibilityManager(
1202     BrowserAccessibilityDelegate* delegate) {
1203   BrowserAccessibilityManager* manager = NULL;
1204 #if defined(OS_WIN)
1205   manager = new BrowserAccessibilityManagerWin(
1206       BrowserAccessibilityManagerWin::GetEmptyDocument(), delegate);
1207 #else
1208   manager = BrowserAccessibilityManager::Create(
1209       BrowserAccessibilityManager::GetEmptyDocument(), delegate);
1210 #endif
1211   return manager;
1212 }
1213
1214 gfx::AcceleratedWidget
1215 RenderWidgetHostViewAura::AccessibilityGetAcceleratedWidget() {
1216 #if defined(OS_WIN)
1217   if (legacy_render_widget_host_HWND_)
1218     return legacy_render_widget_host_HWND_->hwnd();
1219 #endif
1220   return gfx::kNullAcceleratedWidget;
1221 }
1222
1223 gfx::NativeViewAccessible
1224 RenderWidgetHostViewAura::AccessibilityGetNativeViewAccessible() {
1225 #if defined(OS_WIN)
1226   if (legacy_render_widget_host_HWND_)
1227     return legacy_render_widget_host_HWND_->window_accessible();
1228 #endif
1229   return NULL;
1230
1231 }
1232
1233 gfx::GLSurfaceHandle RenderWidgetHostViewAura::GetCompositingSurface() {
1234   return ImageTransportFactory::GetInstance()->GetSharedSurfaceHandle();
1235 }
1236
1237 void RenderWidgetHostViewAura::ShowDisambiguationPopup(
1238     const gfx::Rect& rect_pixels,
1239     const SkBitmap& zoomed_bitmap) {
1240   // |target_rect| is provided in pixels, not DIPs. So we convert it to DIPs
1241   // by scaling it by the inverse of the device scale factor.
1242   gfx::RectF screen_target_rect_f(rect_pixels);
1243   screen_target_rect_f.Scale(1.0f / current_device_scale_factor_);
1244   disambiguation_target_rect_ = gfx::ToEnclosingRect(screen_target_rect_f);
1245
1246   float scale = static_cast<float>(zoomed_bitmap.width()) /
1247                 static_cast<float>(rect_pixels.width());
1248   gfx::Size zoomed_size(gfx::ToCeiledSize(
1249       gfx::ScaleSize(disambiguation_target_rect_.size(), scale)));
1250
1251   // Save of a copy of the |last_scroll_offset_| for comparison when the copy
1252   // callback fires, to ensure that we haven't scrolled.
1253   disambiguation_scroll_offset_ = last_scroll_offset_;
1254
1255   CopyFromCompositingSurface(
1256       disambiguation_target_rect_,
1257       zoomed_size,
1258       base::Bind(&RenderWidgetHostViewAura::DisambiguationPopupRendered,
1259           base::internal::SupportsWeakPtrBase::StaticAsWeakPtr
1260               <RenderWidgetHostViewAura>(this)),
1261       kN32_SkColorType);
1262 }
1263
1264 void RenderWidgetHostViewAura::DisambiguationPopupRendered(
1265     bool success,
1266     const SkBitmap& result) {
1267   if (!success || disambiguation_scroll_offset_ != last_scroll_offset_)
1268     return;
1269
1270   // Use RenderViewHostDelegate to get to the WebContentsViewAura, which will
1271   // actually show the delegate.
1272   RenderViewHostDelegate* delegate = NULL;
1273   if (host_->IsRenderView())
1274     delegate = RenderViewHost::From(host_)->GetDelegate();
1275   RenderViewHostDelegateView* delegate_view = NULL;
1276   if (delegate)
1277     delegate_view = delegate->GetDelegateView();
1278   if (delegate_view) {
1279     delegate_view->ShowDisambiguationPopup(
1280         disambiguation_target_rect_,
1281         result,
1282         base::Bind(&RenderWidgetHostViewAura::ProcessDisambiguationGesture,
1283             base::internal::SupportsWeakPtrBase::StaticAsWeakPtr
1284                 <RenderWidgetHostViewAura>(this)),
1285         base::Bind(&RenderWidgetHostViewAura::ProcessDisambiguationMouse,
1286             base::internal::SupportsWeakPtrBase::StaticAsWeakPtr
1287                 <RenderWidgetHostViewAura>(this)));
1288   }
1289 }
1290
1291 void RenderWidgetHostViewAura::HideDisambiguationPopup() {
1292   RenderViewHostDelegate* delegate = NULL;
1293   if (host_->IsRenderView())
1294     delegate = RenderViewHost::From(host_)->GetDelegate();
1295   RenderViewHostDelegateView* delegate_view = NULL;
1296   if (delegate)
1297     delegate_view = delegate->GetDelegateView();
1298   if (delegate_view)
1299     delegate_view->HideDisambiguationPopup();
1300 }
1301
1302 void RenderWidgetHostViewAura::ProcessDisambiguationGesture(
1303     ui::GestureEvent* event) {
1304   blink::WebGestureEvent web_gesture = content::MakeWebGestureEvent(event);
1305   // If we fail to make a WebGestureEvent that is a Tap from the provided event,
1306   // don't forward it to Blink.
1307   if (web_gesture.type < blink::WebInputEvent::Type::GestureTap ||
1308       web_gesture.type > blink::WebInputEvent::Type::GestureTapCancel)
1309     return;
1310
1311   host_->ForwardGestureEvent(web_gesture);
1312 }
1313
1314 void RenderWidgetHostViewAura::ProcessDisambiguationMouse(
1315     ui::MouseEvent* event) {
1316   blink::WebMouseEvent web_mouse = content::MakeWebMouseEvent(event);
1317   host_->ForwardMouseEvent(web_mouse);
1318 }
1319
1320 bool RenderWidgetHostViewAura::LockMouse() {
1321   aura::Window* root_window = window_->GetRootWindow();
1322   if (!root_window)
1323     return false;
1324
1325   if (mouse_locked_)
1326     return true;
1327
1328   mouse_locked_ = true;
1329 #if !defined(OS_WIN)
1330   window_->SetCapture();
1331 #else
1332   UpdateMouseLockRegion();
1333 #endif
1334   aura::client::CursorClient* cursor_client =
1335       aura::client::GetCursorClient(root_window);
1336   if (cursor_client) {
1337     cursor_client->HideCursor();
1338     cursor_client->LockCursor();
1339   }
1340
1341   if (ShouldMoveToCenter()) {
1342     synthetic_move_sent_ = true;
1343     window_->MoveCursorTo(gfx::Rect(window_->bounds().size()).CenterPoint());
1344   }
1345   tooltip_disabler_.reset(new aura::client::ScopedTooltipDisabler(root_window));
1346   return true;
1347 }
1348
1349 void RenderWidgetHostViewAura::UnlockMouse() {
1350   tooltip_disabler_.reset();
1351
1352   aura::Window* root_window = window_->GetRootWindow();
1353   if (!mouse_locked_ || !root_window)
1354     return;
1355
1356   mouse_locked_ = false;
1357
1358 #if !defined(OS_WIN)
1359   window_->ReleaseCapture();
1360 #else
1361   ::ClipCursor(NULL);
1362 #endif
1363   window_->MoveCursorTo(unlocked_mouse_position_);
1364   aura::client::CursorClient* cursor_client =
1365       aura::client::GetCursorClient(root_window);
1366   if (cursor_client) {
1367     cursor_client->UnlockCursor();
1368     cursor_client->ShowCursor();
1369   }
1370
1371   host_->LostMouseLock();
1372 }
1373
1374 ////////////////////////////////////////////////////////////////////////////////
1375 // RenderWidgetHostViewAura, ui::TextInputClient implementation:
1376 void RenderWidgetHostViewAura::SetCompositionText(
1377     const ui::CompositionText& composition) {
1378   if (!host_)
1379     return;
1380
1381   // TODO(suzhe): convert both renderer_host and renderer to use
1382   // ui::CompositionText.
1383   std::vector<blink::WebCompositionUnderline> underlines;
1384   underlines.reserve(composition.underlines.size());
1385   for (std::vector<ui::CompositionUnderline>::const_iterator it =
1386            composition.underlines.begin();
1387        it != composition.underlines.end(); ++it) {
1388     underlines.push_back(
1389         blink::WebCompositionUnderline(static_cast<unsigned>(it->start_offset),
1390                                        static_cast<unsigned>(it->end_offset),
1391                                        it->color,
1392                                        it->thick,
1393                                        it->background_color));
1394   }
1395
1396   // TODO(suzhe): due to a bug of webkit, we can't use selection range with
1397   // composition string. See: https://bugs.webkit.org/show_bug.cgi?id=37788
1398   host_->ImeSetComposition(composition.text, underlines,
1399                            composition.selection.end(),
1400                            composition.selection.end());
1401
1402   has_composition_text_ = !composition.text.empty();
1403 }
1404
1405 void RenderWidgetHostViewAura::ConfirmCompositionText() {
1406   if (host_ && has_composition_text_) {
1407     host_->ImeConfirmComposition(base::string16(), gfx::Range::InvalidRange(),
1408                                  false);
1409   }
1410   has_composition_text_ = false;
1411 }
1412
1413 void RenderWidgetHostViewAura::ClearCompositionText() {
1414   if (host_ && has_composition_text_)
1415     host_->ImeCancelComposition();
1416   has_composition_text_ = false;
1417 }
1418
1419 void RenderWidgetHostViewAura::InsertText(const base::string16& text) {
1420   DCHECK(text_input_type_ != ui::TEXT_INPUT_TYPE_NONE);
1421   if (host_)
1422     host_->ImeConfirmComposition(text, gfx::Range::InvalidRange(), false);
1423   has_composition_text_ = false;
1424 }
1425
1426 void RenderWidgetHostViewAura::InsertChar(base::char16 ch, int flags) {
1427   if (popup_child_host_view_ && popup_child_host_view_->NeedsInputGrab()) {
1428     popup_child_host_view_->InsertChar(ch, flags);
1429     return;
1430   }
1431
1432   // Ignore character messages for VKEY_RETURN sent on CTRL+M. crbug.com/315547
1433   if (host_ && (accept_return_character_ || ch != ui::VKEY_RETURN)) {
1434     double now = ui::EventTimeForNow().InSecondsF();
1435     // Send a blink::WebInputEvent::Char event to |host_|.
1436     NativeWebKeyboardEvent webkit_event(ui::ET_KEY_PRESSED,
1437                                         true /* is_char */,
1438                                         ch,
1439                                         flags,
1440                                         now);
1441     ForwardKeyboardEvent(webkit_event);
1442   }
1443 }
1444
1445 gfx::NativeWindow RenderWidgetHostViewAura::GetAttachedWindow() const {
1446   return window_;
1447 }
1448
1449 ui::TextInputType RenderWidgetHostViewAura::GetTextInputType() const {
1450   return text_input_type_;
1451 }
1452
1453 ui::TextInputMode RenderWidgetHostViewAura::GetTextInputMode() const {
1454   return text_input_mode_;
1455 }
1456
1457 bool RenderWidgetHostViewAura::CanComposeInline() const {
1458   return can_compose_inline_;
1459 }
1460
1461 gfx::Rect RenderWidgetHostViewAura::ConvertRectToScreen(
1462     const gfx::Rect& rect) const {
1463   gfx::Point origin = rect.origin();
1464   gfx::Point end = gfx::Point(rect.right(), rect.bottom());
1465
1466   aura::Window* root_window = window_->GetRootWindow();
1467   if (!root_window)
1468     return rect;
1469   aura::client::ScreenPositionClient* screen_position_client =
1470       aura::client::GetScreenPositionClient(root_window);
1471   if (!screen_position_client)
1472     return rect;
1473   screen_position_client->ConvertPointToScreen(window_, &origin);
1474   screen_position_client->ConvertPointToScreen(window_, &end);
1475   return gfx::Rect(origin.x(),
1476                    origin.y(),
1477                    end.x() - origin.x(),
1478                    end.y() - origin.y());
1479 }
1480
1481 gfx::Rect RenderWidgetHostViewAura::ConvertRectFromScreen(
1482     const gfx::Rect& rect) const {
1483   gfx::Point origin = rect.origin();
1484   gfx::Point end = gfx::Point(rect.right(), rect.bottom());
1485
1486   aura::Window* root_window = window_->GetRootWindow();
1487   if (root_window) {
1488     aura::client::ScreenPositionClient* screen_position_client =
1489         aura::client::GetScreenPositionClient(root_window);
1490     screen_position_client->ConvertPointFromScreen(window_, &origin);
1491     screen_position_client->ConvertPointFromScreen(window_, &end);
1492     return gfx::Rect(origin.x(),
1493                      origin.y(),
1494                      end.x() - origin.x(),
1495                      end.y() - origin.y());
1496   }
1497
1498   return rect;
1499 }
1500
1501 gfx::Rect RenderWidgetHostViewAura::GetCaretBounds() const {
1502   const gfx::Rect rect =
1503       gfx::UnionRects(selection_anchor_rect_, selection_focus_rect_);
1504   return ConvertRectToScreen(rect);
1505 }
1506
1507 bool RenderWidgetHostViewAura::GetCompositionCharacterBounds(
1508     uint32 index,
1509     gfx::Rect* rect) const {
1510   DCHECK(rect);
1511   if (index >= composition_character_bounds_.size())
1512     return false;
1513   *rect = ConvertRectToScreen(composition_character_bounds_[index]);
1514   return true;
1515 }
1516
1517 bool RenderWidgetHostViewAura::HasCompositionText() const {
1518   return has_composition_text_;
1519 }
1520
1521 bool RenderWidgetHostViewAura::GetTextRange(gfx::Range* range) const {
1522   range->set_start(selection_text_offset_);
1523   range->set_end(selection_text_offset_ + selection_text_.length());
1524   return true;
1525 }
1526
1527 bool RenderWidgetHostViewAura::GetCompositionTextRange(
1528     gfx::Range* range) const {
1529   // TODO(suzhe): implement this method when fixing http://crbug.com/55130.
1530   NOTIMPLEMENTED();
1531   return false;
1532 }
1533
1534 bool RenderWidgetHostViewAura::GetSelectionRange(gfx::Range* range) const {
1535   range->set_start(selection_range_.start());
1536   range->set_end(selection_range_.end());
1537   return true;
1538 }
1539
1540 bool RenderWidgetHostViewAura::SetSelectionRange(const gfx::Range& range) {
1541   // TODO(suzhe): implement this method when fixing http://crbug.com/55130.
1542   NOTIMPLEMENTED();
1543   return false;
1544 }
1545
1546 bool RenderWidgetHostViewAura::DeleteRange(const gfx::Range& range) {
1547   // TODO(suzhe): implement this method when fixing http://crbug.com/55130.
1548   NOTIMPLEMENTED();
1549   return false;
1550 }
1551
1552 bool RenderWidgetHostViewAura::GetTextFromRange(
1553     const gfx::Range& range,
1554     base::string16* text) const {
1555   gfx::Range selection_text_range(selection_text_offset_,
1556       selection_text_offset_ + selection_text_.length());
1557
1558   if (!selection_text_range.Contains(range)) {
1559     text->clear();
1560     return false;
1561   }
1562   if (selection_text_range.EqualsIgnoringDirection(range)) {
1563     // Avoid calling substr whose performance is low.
1564     *text = selection_text_;
1565   } else {
1566     *text = selection_text_.substr(
1567         range.GetMin() - selection_text_offset_,
1568         range.length());
1569   }
1570   return true;
1571 }
1572
1573 void RenderWidgetHostViewAura::OnInputMethodChanged() {
1574   if (!host_)
1575     return;
1576
1577   if (GetInputMethod())
1578     host_->SetInputMethodActive(GetInputMethod()->IsActive());
1579
1580   // TODO(suzhe): implement the newly added “locale” property of HTML DOM
1581   // TextEvent.
1582 }
1583
1584 bool RenderWidgetHostViewAura::ChangeTextDirectionAndLayoutAlignment(
1585       base::i18n::TextDirection direction) {
1586   if (!host_)
1587     return false;
1588   host_->UpdateTextDirection(
1589       direction == base::i18n::RIGHT_TO_LEFT ?
1590       blink::WebTextDirectionRightToLeft :
1591       blink::WebTextDirectionLeftToRight);
1592   host_->NotifyTextDirection();
1593   return true;
1594 }
1595
1596 void RenderWidgetHostViewAura::ExtendSelectionAndDelete(
1597     size_t before, size_t after) {
1598   RenderFrameHostImpl* rfh = GetFocusedFrame();
1599   if (rfh)
1600     rfh->ExtendSelectionAndDelete(before, after);
1601 }
1602
1603 void RenderWidgetHostViewAura::EnsureCaretInRect(const gfx::Rect& rect) {
1604   gfx::Rect intersected_rect(
1605       gfx::IntersectRects(rect, window_->GetBoundsInScreen()));
1606
1607   if (intersected_rect.IsEmpty())
1608     return;
1609
1610   host_->ScrollFocusedEditableNodeIntoRect(
1611       ConvertRectFromScreen(intersected_rect));
1612 }
1613
1614 void RenderWidgetHostViewAura::OnCandidateWindowShown() {
1615   host_->CandidateWindowShown();
1616 }
1617
1618 void RenderWidgetHostViewAura::OnCandidateWindowUpdated() {
1619   host_->CandidateWindowUpdated();
1620 }
1621
1622 void RenderWidgetHostViewAura::OnCandidateWindowHidden() {
1623   host_->CandidateWindowHidden();
1624 }
1625
1626 bool RenderWidgetHostViewAura::IsEditingCommandEnabled(int command_id) {
1627   return false;
1628 }
1629
1630 void RenderWidgetHostViewAura::ExecuteEditingCommand(int command_id) {
1631 }
1632
1633 ////////////////////////////////////////////////////////////////////////////////
1634 // RenderWidgetHostViewAura, gfx::DisplayObserver implementation:
1635
1636 void RenderWidgetHostViewAura::OnDisplayAdded(
1637     const gfx::Display& new_display) {
1638 }
1639
1640 void RenderWidgetHostViewAura::OnDisplayRemoved(
1641     const gfx::Display& old_display) {
1642 }
1643
1644 void RenderWidgetHostViewAura::OnDisplayMetricsChanged(
1645     const gfx::Display& display, uint32_t metrics) {
1646   // The screen info should be updated regardless of the metric change.
1647   gfx::Screen* screen = gfx::Screen::GetScreenFor(window_);
1648   if (display.id() == screen->GetDisplayNearestWindow(window_).id()) {
1649     UpdateScreenInfo(window_);
1650     current_cursor_.SetDisplayInfo(display);
1651     UpdateCursorIfOverSelf();
1652   }
1653 }
1654
1655 ////////////////////////////////////////////////////////////////////////////////
1656 // RenderWidgetHostViewAura, aura::WindowDelegate implementation:
1657
1658 gfx::Size RenderWidgetHostViewAura::GetMinimumSize() const {
1659   return gfx::Size();
1660 }
1661
1662 gfx::Size RenderWidgetHostViewAura::GetMaximumSize() const {
1663   return gfx::Size();
1664 }
1665
1666 void RenderWidgetHostViewAura::OnBoundsChanged(const gfx::Rect& old_bounds,
1667                                                const gfx::Rect& new_bounds) {
1668   base::AutoReset<bool> in_bounds_changed(&in_bounds_changed_, true);
1669   // We care about this whenever RenderWidgetHostViewAura is not owned by a
1670   // WebContentsViewAura since changes to the Window's bounds need to be
1671   // messaged to the renderer.  WebContentsViewAura invokes SetSize() or
1672   // SetBounds() itself.  No matter how we got here, any redundant calls are
1673   // harmless.
1674   SetSize(new_bounds.size());
1675
1676   if (GetInputMethod())
1677     GetInputMethod()->OnCaretBoundsChanged(this);
1678 }
1679
1680 gfx::NativeCursor RenderWidgetHostViewAura::GetCursor(const gfx::Point& point) {
1681   if (mouse_locked_)
1682     return ui::kCursorNone;
1683   return current_cursor_.GetNativeCursor();
1684 }
1685
1686 int RenderWidgetHostViewAura::GetNonClientComponent(
1687     const gfx::Point& point) const {
1688   return HTCLIENT;
1689 }
1690
1691 bool RenderWidgetHostViewAura::ShouldDescendIntoChildForEventHandling(
1692     aura::Window* child,
1693     const gfx::Point& location) {
1694   return true;
1695 }
1696
1697 bool RenderWidgetHostViewAura::CanFocus() {
1698   return popup_type_ == blink::WebPopupTypeNone;
1699 }
1700
1701 void RenderWidgetHostViewAura::OnCaptureLost() {
1702   host_->LostCapture();
1703   if (touch_editing_client_)
1704     touch_editing_client_->EndTouchEditing(false);
1705 }
1706
1707 void RenderWidgetHostViewAura::OnPaint(gfx::Canvas* canvas) {
1708   // For non-opaque windows, we don't draw anything, since we depend on the
1709   // canvas coming from the compositor to already be initialized as
1710   // transparent.
1711   if (window_->layer()->fills_bounds_opaquely())
1712     canvas->DrawColor(SK_ColorWHITE);
1713 }
1714
1715 void RenderWidgetHostViewAura::OnDeviceScaleFactorChanged(
1716     float device_scale_factor) {
1717   if (!host_ || !window_->GetRootWindow())
1718     return;
1719
1720   UpdateScreenInfo(window_);
1721
1722   const gfx::Display display = gfx::Screen::GetScreenFor(window_)->
1723       GetDisplayNearestWindow(window_);
1724   DCHECK_EQ(device_scale_factor, display.device_scale_factor());
1725   current_cursor_.SetDisplayInfo(display);
1726   SnapToPhysicalPixelBoundary();
1727 }
1728
1729 void RenderWidgetHostViewAura::OnWindowDestroying(aura::Window* window) {
1730 #if defined(OS_WIN)
1731   HWND parent = NULL;
1732   // If the tab was hidden and it's closed, host_->is_hidden would have been
1733   // reset to false in RenderWidgetHostImpl::RendererExited.
1734   if (!window_->GetRootWindow() || host_->is_hidden()) {
1735     parent = ui::GetHiddenWindow();
1736   } else {
1737     parent = window_->GetHost()->GetAcceleratedWidget();
1738   }
1739   LPARAM lparam = reinterpret_cast<LPARAM>(this);
1740   EnumChildWindows(parent, WindowDestroyingCallback, lparam);
1741
1742   // The LegacyRenderWidgetHostHWND instance is destroyed when its window is
1743   // destroyed. Normally we control when that happens via the Destroy call
1744   // in the dtor. However there may be cases where the window is destroyed
1745   // by Windows, i.e. the parent window is destroyed before the
1746   // RenderWidgetHostViewAura instance goes away etc. To avoid that we
1747   // destroy the LegacyRenderWidgetHostHWND instance here.
1748   if (legacy_render_widget_host_HWND_) {
1749     legacy_render_widget_host_HWND_->set_host(NULL);
1750     legacy_render_widget_host_HWND_->Destroy();
1751     // The Destroy call above will delete the LegacyRenderWidgetHostHWND
1752     // instance.
1753     legacy_render_widget_host_HWND_ = NULL;
1754   }
1755 #endif
1756
1757   // Make sure that the input method no longer references to this object before
1758   // this object is removed from the root window (i.e. this object loses access
1759   // to the input method).
1760   ui::InputMethod* input_method = GetInputMethod();
1761   if (input_method)
1762     input_method->DetachTextInputClient(this);
1763
1764   if (overscroll_controller_)
1765     overscroll_controller_->Reset();
1766 }
1767
1768 void RenderWidgetHostViewAura::OnWindowDestroyed(aura::Window* window) {
1769   host_->ViewDestroyed();
1770   delete this;
1771 }
1772
1773 void RenderWidgetHostViewAura::OnWindowTargetVisibilityChanged(bool visible) {
1774 }
1775
1776 bool RenderWidgetHostViewAura::HasHitTestMask() const {
1777   return false;
1778 }
1779
1780 void RenderWidgetHostViewAura::GetHitTestMask(gfx::Path* mask) const {
1781 }
1782
1783 ////////////////////////////////////////////////////////////////////////////////
1784 // RenderWidgetHostViewAura, ui::EventHandler implementation:
1785
1786 void RenderWidgetHostViewAura::OnKeyEvent(ui::KeyEvent* event) {
1787   TRACE_EVENT0("input", "RenderWidgetHostViewAura::OnKeyEvent");
1788   if (touch_editing_client_ && touch_editing_client_->HandleInputEvent(event))
1789     return;
1790
1791   if (popup_child_host_view_ && popup_child_host_view_->NeedsInputGrab()) {
1792     popup_child_host_view_->OnKeyEvent(event);
1793     if (event->handled())
1794       return;
1795   }
1796
1797   // We need to handle the Escape key for Pepper Flash.
1798   if (is_fullscreen_ && event->key_code() == ui::VKEY_ESCAPE) {
1799     // Focus the window we were created from.
1800     if (host_tracker_.get() && !host_tracker_->windows().empty()) {
1801       aura::Window* host = *(host_tracker_->windows().begin());
1802       aura::client::FocusClient* client = aura::client::GetFocusClient(host);
1803       if (client) {
1804         // Calling host->Focus() may delete |this|. We create a local observer
1805         // for that. In that case we exit without further access to any members.
1806         aura::WindowTracker tracker;
1807         aura::Window* window = window_;
1808         tracker.Add(window);
1809         host->Focus();
1810         if (!tracker.Contains(window)) {
1811           event->SetHandled();
1812           return;
1813         }
1814       }
1815     }
1816     if (!in_shutdown_) {
1817       in_shutdown_ = true;
1818       host_->Shutdown();
1819     }
1820   } else {
1821     if (event->key_code() == ui::VKEY_RETURN) {
1822       // Do not forward return key release events if no press event was handled.
1823       if (event->type() == ui::ET_KEY_RELEASED && !accept_return_character_)
1824         return;
1825       // Accept return key character events between press and release events.
1826       accept_return_character_ = event->type() == ui::ET_KEY_PRESSED;
1827     }
1828
1829     // We don't have to communicate with an input method here.
1830     if (!event->HasNativeEvent()) {
1831       NativeWebKeyboardEvent webkit_event(
1832           event->type(),
1833           event->is_char(),
1834           event->is_char() ? event->GetCharacter() : event->key_code(),
1835           event->flags(),
1836           ui::EventTimeForNow().InSecondsF());
1837       ForwardKeyboardEvent(webkit_event);
1838     } else {
1839       NativeWebKeyboardEvent webkit_event(event);
1840       ForwardKeyboardEvent(webkit_event);
1841     }
1842   }
1843   event->SetHandled();
1844 }
1845
1846 void RenderWidgetHostViewAura::OnMouseEvent(ui::MouseEvent* event) {
1847   TRACE_EVENT0("input", "RenderWidgetHostViewAura::OnMouseEvent");
1848
1849   if (touch_editing_client_ && touch_editing_client_->HandleInputEvent(event))
1850     return;
1851
1852   if (mouse_locked_) {
1853     aura::client::CursorClient* cursor_client =
1854         aura::client::GetCursorClient(window_->GetRootWindow());
1855     DCHECK(!cursor_client || !cursor_client->IsCursorVisible());
1856
1857     if (event->type() == ui::ET_MOUSEWHEEL) {
1858       blink::WebMouseWheelEvent mouse_wheel_event =
1859           MakeWebMouseWheelEvent(static_cast<ui::MouseWheelEvent*>(event));
1860       if (mouse_wheel_event.deltaX != 0 || mouse_wheel_event.deltaY != 0)
1861         host_->ForwardWheelEvent(mouse_wheel_event);
1862       return;
1863     }
1864
1865     gfx::Point center(gfx::Rect(window_->bounds().size()).CenterPoint());
1866
1867     // If we receive non client mouse messages while we are in the locked state
1868     // it probably means that the mouse left the borders of our window and
1869     // needs to be moved back to the center.
1870     if (event->flags() & ui::EF_IS_NON_CLIENT) {
1871       synthetic_move_sent_ = true;
1872       window_->MoveCursorTo(center);
1873       return;
1874     }
1875
1876     blink::WebMouseEvent mouse_event = MakeWebMouseEvent(event);
1877
1878     bool is_move_to_center_event = (event->type() == ui::ET_MOUSE_MOVED ||
1879         event->type() == ui::ET_MOUSE_DRAGGED) &&
1880         mouse_event.x == center.x() && mouse_event.y == center.y();
1881
1882     ModifyEventMovementAndCoords(&mouse_event);
1883
1884     bool should_not_forward = is_move_to_center_event && synthetic_move_sent_;
1885     if (should_not_forward) {
1886       synthetic_move_sent_ = false;
1887     } else {
1888       // Check if the mouse has reached the border and needs to be centered.
1889       if (ShouldMoveToCenter()) {
1890         synthetic_move_sent_ = true;
1891         window_->MoveCursorTo(center);
1892       }
1893       // Forward event to renderer.
1894       if (CanRendererHandleEvent(event) &&
1895           !(event->flags() & ui::EF_FROM_TOUCH)) {
1896         host_->ForwardMouseEvent(mouse_event);
1897         // Ensure that we get keyboard focus on mouse down as a plugin window
1898         // may have grabbed keyboard focus.
1899         if (event->type() == ui::ET_MOUSE_PRESSED)
1900           SetKeyboardFocus();
1901       }
1902     }
1903     return;
1904   }
1905
1906   // As the overscroll is handled during scroll events from the trackpad, the
1907   // RWHVA window is transformed by the overscroll controller. This transform
1908   // triggers a synthetic mouse-move event to be generated (by the aura
1909   // RootWindow). But this event interferes with the overscroll gesture. So,
1910   // ignore such synthetic mouse-move events if an overscroll gesture is in
1911   // progress.
1912   if (overscroll_controller_ &&
1913       overscroll_controller_->overscroll_mode() != OVERSCROLL_NONE &&
1914       event->flags() & ui::EF_IS_SYNTHESIZED &&
1915       (event->type() == ui::ET_MOUSE_ENTERED ||
1916        event->type() == ui::ET_MOUSE_EXITED ||
1917        event->type() == ui::ET_MOUSE_MOVED)) {
1918     event->StopPropagation();
1919     return;
1920   }
1921
1922   if (event->type() == ui::ET_MOUSEWHEEL) {
1923 #if defined(OS_WIN)
1924     // We get mouse wheel/scroll messages even if we are not in the foreground.
1925     // So here we check if we have any owned popup windows in the foreground and
1926     // dismiss them.
1927     aura::WindowTreeHost* host = window_->GetHost();
1928     if (host) {
1929       HWND parent = host->GetAcceleratedWidget();
1930       HWND toplevel_hwnd = ::GetAncestor(parent, GA_ROOT);
1931       EnumThreadWindows(GetCurrentThreadId(),
1932                         DismissOwnedPopups,
1933                         reinterpret_cast<LPARAM>(toplevel_hwnd));
1934     }
1935 #endif
1936     // The Disambiguation popup does not parent itself from this window, so we
1937     // manually dismiss it.
1938     HideDisambiguationPopup();
1939
1940     blink::WebMouseWheelEvent mouse_wheel_event =
1941         MakeWebMouseWheelEvent(static_cast<ui::MouseWheelEvent*>(event));
1942     if (mouse_wheel_event.deltaX != 0 || mouse_wheel_event.deltaY != 0)
1943       host_->ForwardWheelEvent(mouse_wheel_event);
1944   } else if (CanRendererHandleEvent(event) &&
1945              !(event->flags() & ui::EF_FROM_TOUCH)) {
1946     blink::WebMouseEvent mouse_event = MakeWebMouseEvent(event);
1947     ModifyEventMovementAndCoords(&mouse_event);
1948     host_->ForwardMouseEvent(mouse_event);
1949     // Ensure that we get keyboard focus on mouse down as a plugin window may
1950     // have grabbed keyboard focus.
1951     if (event->type() == ui::ET_MOUSE_PRESSED)
1952       SetKeyboardFocus();
1953   }
1954
1955   switch (event->type()) {
1956     case ui::ET_MOUSE_PRESSED:
1957       window_->SetCapture();
1958       // Confirm existing composition text on mouse click events, to make sure
1959       // the input caret won't be moved with an ongoing composition text.
1960       FinishImeCompositionSession();
1961       break;
1962     case ui::ET_MOUSE_RELEASED:
1963       window_->ReleaseCapture();
1964       break;
1965     default:
1966       break;
1967   }
1968
1969   // Needed to propagate mouse event to |window_->parent()->delegate()|, but
1970   // note that it might be something other than a WebContentsViewAura instance.
1971   // TODO(pkotwicz): Find a better way of doing this.
1972   // In fullscreen mode which is typically used by flash, don't forward
1973   // the mouse events to the parent. The renderer and the plugin process
1974   // handle these events.
1975   if (!is_fullscreen_ && window_->parent()->delegate() &&
1976       !(event->flags() & ui::EF_FROM_TOUCH)) {
1977     event->ConvertLocationToTarget(window_, window_->parent());
1978     window_->parent()->delegate()->OnMouseEvent(event);
1979   }
1980
1981   if (!IsXButtonUpEvent(event))
1982     event->SetHandled();
1983 }
1984
1985 void RenderWidgetHostViewAura::OnScrollEvent(ui::ScrollEvent* event) {
1986   TRACE_EVENT0("input", "RenderWidgetHostViewAura::OnScrollEvent");
1987   if (touch_editing_client_ && touch_editing_client_->HandleInputEvent(event))
1988     return;
1989
1990   if (event->type() == ui::ET_SCROLL) {
1991 #if !defined(OS_WIN)
1992     // TODO(ananta)
1993     // Investigate if this is true for Windows 8 Metro ASH as well.
1994     if (event->finger_count() != 2)
1995       return;
1996 #endif
1997     blink::WebGestureEvent gesture_event =
1998         MakeWebGestureEventFlingCancel();
1999     host_->ForwardGestureEvent(gesture_event);
2000     blink::WebMouseWheelEvent mouse_wheel_event =
2001         MakeWebMouseWheelEvent(event);
2002     host_->ForwardWheelEvent(mouse_wheel_event);
2003     RecordAction(base::UserMetricsAction("TrackpadScroll"));
2004   } else if (event->type() == ui::ET_SCROLL_FLING_START ||
2005              event->type() == ui::ET_SCROLL_FLING_CANCEL) {
2006     blink::WebGestureEvent gesture_event =
2007         MakeWebGestureEvent(event);
2008     host_->ForwardGestureEvent(gesture_event);
2009     if (event->type() == ui::ET_SCROLL_FLING_START)
2010       RecordAction(base::UserMetricsAction("TrackpadScrollFling"));
2011   }
2012
2013   event->SetHandled();
2014 }
2015
2016 void RenderWidgetHostViewAura::OnTouchEvent(ui::TouchEvent* event) {
2017   TRACE_EVENT0("input", "RenderWidgetHostViewAura::OnTouchEvent");
2018   if (touch_editing_client_ && touch_editing_client_->HandleInputEvent(event))
2019     return;
2020
2021   // Update the touch event first.
2022   blink::WebTouchPoint* point = UpdateWebTouchEventFromUIEvent(*event,
2023                                                                 &touch_event_);
2024
2025   // Forward the touch event only if a touch point was updated, and there's a
2026   // touch-event handler in the page, and no other touch-event is in the queue.
2027   // It is important to always consume the event if there is a touch-event
2028   // handler in the page, or some touch-event is already in the queue, even if
2029   // no point has been updated, to make sure that this event does not get
2030   // processed by the gesture recognizer before the events in the queue.
2031   if (host_->ShouldForwardTouchEvent())
2032     event->StopPropagation();
2033
2034   if (point) {
2035     if (host_->ShouldForwardTouchEvent())
2036       host_->ForwardTouchEventWithLatencyInfo(touch_event_, *event->latency());
2037     UpdateWebTouchEventAfterDispatch(&touch_event_, point);
2038   }
2039 }
2040
2041 void RenderWidgetHostViewAura::OnGestureEvent(ui::GestureEvent* event) {
2042   TRACE_EVENT0("input", "RenderWidgetHostViewAura::OnGestureEvent");
2043   if ((event->type() == ui::ET_GESTURE_PINCH_BEGIN ||
2044       event->type() == ui::ET_GESTURE_PINCH_UPDATE ||
2045       event->type() == ui::ET_GESTURE_PINCH_END) && !pinch_zoom_enabled_) {
2046     event->SetHandled();
2047     return;
2048   }
2049
2050   if (touch_editing_client_ && touch_editing_client_->HandleInputEvent(event))
2051     return;
2052
2053   RenderViewHostDelegate* delegate = NULL;
2054   if (host_->IsRenderView())
2055     delegate = RenderViewHost::From(host_)->GetDelegate();
2056
2057   if (delegate && event->type() == ui::ET_GESTURE_BEGIN &&
2058       event->details().touch_points() == 1) {
2059     delegate->HandleGestureBegin();
2060   }
2061
2062   blink::WebGestureEvent gesture = MakeWebGestureEvent(event);
2063   if (event->type() == ui::ET_GESTURE_TAP_DOWN) {
2064     // Webkit does not stop a fling-scroll on tap-down. So explicitly send an
2065     // event to stop any in-progress flings.
2066     blink::WebGestureEvent fling_cancel = gesture;
2067     fling_cancel.type = blink::WebInputEvent::GestureFlingCancel;
2068     fling_cancel.sourceDevice = blink::WebGestureDeviceTouchscreen;
2069     host_->ForwardGestureEvent(fling_cancel);
2070   }
2071
2072   if (gesture.type != blink::WebInputEvent::Undefined) {
2073     host_->ForwardGestureEventWithLatencyInfo(gesture, *event->latency());
2074
2075     if (event->type() == ui::ET_GESTURE_SCROLL_BEGIN ||
2076         event->type() == ui::ET_GESTURE_SCROLL_UPDATE ||
2077         event->type() == ui::ET_GESTURE_SCROLL_END) {
2078       RecordAction(base::UserMetricsAction("TouchscreenScroll"));
2079     } else if (event->type() == ui::ET_SCROLL_FLING_START) {
2080       RecordAction(base::UserMetricsAction("TouchscreenScrollFling"));
2081     }
2082   }
2083
2084   if (delegate && event->type() == ui::ET_GESTURE_END &&
2085       event->details().touch_points() == 1) {
2086     delegate->HandleGestureEnd();
2087   }
2088
2089   // If a gesture is not processed by the webpage, then WebKit processes it
2090   // (e.g. generates synthetic mouse events).
2091   event->SetHandled();
2092 }
2093
2094 ////////////////////////////////////////////////////////////////////////////////
2095 // RenderWidgetHostViewAura, aura::client::ActivationDelegate implementation:
2096
2097 bool RenderWidgetHostViewAura::ShouldActivate() const {
2098   aura::WindowTreeHost* host = window_->GetHost();
2099   if (!host)
2100     return true;
2101   const ui::Event* event = host->dispatcher()->current_event();
2102   if (!event)
2103     return true;
2104   return is_fullscreen_;
2105 }
2106
2107 ////////////////////////////////////////////////////////////////////////////////
2108 // RenderWidgetHostViewAura,
2109 //     aura::client::ActivationChangeObserver implementation:
2110
2111 void RenderWidgetHostViewAura::OnWindowActivated(aura::Window* gained_active,
2112                                                  aura::Window* lost_active) {
2113   DCHECK(window_ == gained_active || window_ == lost_active);
2114   if (window_ == gained_active) {
2115     const ui::Event* event = window_->GetHost()->dispatcher()->current_event();
2116     if (event && PointerEventActivates(*event))
2117       host_->OnPointerEventActivate();
2118   }
2119 }
2120
2121 ////////////////////////////////////////////////////////////////////////////////
2122 // RenderWidgetHostViewAura, aura::client::CursorClientObserver implementation:
2123
2124 void RenderWidgetHostViewAura::OnCursorVisibilityChanged(bool is_visible) {
2125   NotifyRendererOfCursorVisibilityState(is_visible);
2126 }
2127
2128 ////////////////////////////////////////////////////////////////////////////////
2129 // RenderWidgetHostViewAura, aura::client::FocusChangeObserver implementation:
2130
2131 void RenderWidgetHostViewAura::OnWindowFocused(aura::Window* gained_focus,
2132                                                aura::Window* lost_focus) {
2133   DCHECK(window_ == gained_focus || window_ == lost_focus);
2134   if (window_ == gained_focus) {
2135     // We need to honor input bypass if the associated tab is does not want
2136     // input. This gives the current focused window a chance to be the text
2137     // input client and handle events.
2138     if (host_->ignore_input_events())
2139       return;
2140
2141     host_->GotFocus();
2142     host_->SetActive(true);
2143
2144     ui::InputMethod* input_method = GetInputMethod();
2145     if (input_method) {
2146       // Ask the system-wide IME to send all TextInputClient messages to |this|
2147       // object.
2148       input_method->SetFocusedTextInputClient(this);
2149       host_->SetInputMethodActive(input_method->IsActive());
2150
2151       // Often the application can set focus to the view in response to a key
2152       // down. However the following char event shouldn't be sent to the web
2153       // page.
2154       host_->SuppressNextCharEvents();
2155     } else {
2156       host_->SetInputMethodActive(false);
2157     }
2158
2159     BrowserAccessibilityManager* manager =
2160         host_->GetRootBrowserAccessibilityManager();
2161     if (manager)
2162       manager->OnWindowFocused();
2163   } else if (window_ == lost_focus) {
2164     host_->SetActive(false);
2165     host_->Blur();
2166
2167     DetachFromInputMethod();
2168     host_->SetInputMethodActive(false);
2169
2170     if (touch_editing_client_)
2171       touch_editing_client_->EndTouchEditing(false);
2172
2173     if (overscroll_controller_)
2174       overscroll_controller_->Cancel();
2175
2176     BrowserAccessibilityManager* manager =
2177         host_->GetRootBrowserAccessibilityManager();
2178     if (manager)
2179       manager->OnWindowBlurred();
2180
2181     // If we lose the focus while fullscreen, close the window; Pepper Flash
2182     // won't do it for us (unlike NPAPI Flash). However, we do not close the
2183     // window if we lose the focus to a window on another display.
2184     gfx::Screen* screen = gfx::Screen::GetScreenFor(window_);
2185     bool focusing_other_display =
2186         gained_focus && screen->GetNumDisplays() > 1 &&
2187         (screen->GetDisplayNearestWindow(window_).id() !=
2188          screen->GetDisplayNearestWindow(gained_focus).id());
2189     if (is_fullscreen_ && !in_shutdown_ && !focusing_other_display) {
2190 #if defined(OS_WIN)
2191       // On Windows, if we are switching to a non Aura Window on a different
2192       // screen we should not close the fullscreen window.
2193       if (!gained_focus) {
2194         POINT point = {0};
2195         ::GetCursorPos(&point);
2196         if (screen->GetDisplayNearestWindow(window_).id() !=
2197             screen->GetDisplayNearestPoint(gfx::Point(point)).id())
2198           return;
2199       }
2200 #endif
2201       in_shutdown_ = true;
2202       host_->Shutdown();
2203     }
2204   }
2205 }
2206
2207 ////////////////////////////////////////////////////////////////////////////////
2208 // RenderWidgetHostViewAura, aura::WindowTreeHostObserver implementation:
2209
2210 void RenderWidgetHostViewAura::OnHostMoved(const aura::WindowTreeHost* host,
2211                                            const gfx::Point& new_origin) {
2212   TRACE_EVENT1("ui", "RenderWidgetHostViewAura::OnHostMoved",
2213                "new_origin", new_origin.ToString());
2214
2215   UpdateScreenInfo(window_);
2216 }
2217
2218 ////////////////////////////////////////////////////////////////////////////////
2219 // RenderWidgetHostViewAura, private:
2220
2221 RenderWidgetHostViewAura::~RenderWidgetHostViewAura() {
2222   if (touch_editing_client_)
2223     touch_editing_client_->OnViewDestroyed();
2224
2225   delegated_frame_host_.reset();
2226   window_observer_.reset();
2227   if (window_->GetHost())
2228     window_->GetHost()->RemoveObserver(this);
2229   UnlockMouse();
2230   if (popup_parent_host_view_) {
2231     DCHECK(popup_parent_host_view_->popup_child_host_view_ == NULL ||
2232            popup_parent_host_view_->popup_child_host_view_ == this);
2233     popup_parent_host_view_->popup_child_host_view_ = NULL;
2234   }
2235   if (popup_child_host_view_) {
2236     DCHECK(popup_child_host_view_->popup_parent_host_view_ == NULL ||
2237            popup_child_host_view_->popup_parent_host_view_ == this);
2238     popup_child_host_view_->popup_parent_host_view_ = NULL;
2239   }
2240   event_filter_for_popup_exit_.reset();
2241   aura::client::SetTooltipText(window_, NULL);
2242   gfx::Screen::GetScreenFor(window_)->RemoveObserver(this);
2243
2244   // This call is usually no-op since |this| object is already removed from the
2245   // Aura root window and we don't have a way to get an input method object
2246   // associated with the window, but just in case.
2247   DetachFromInputMethod();
2248
2249 #if defined(OS_WIN)
2250   // The LegacyRenderWidgetHostHWND window should have been destroyed in
2251   // RenderWidgetHostViewAura::OnWindowDestroying and the pointer should
2252   // be set to NULL.
2253   DCHECK(!legacy_render_widget_host_HWND_);
2254 #endif
2255 }
2256
2257 void RenderWidgetHostViewAura::UpdateCursorIfOverSelf() {
2258   const gfx::Point screen_point =
2259       gfx::Screen::GetScreenFor(GetNativeView())->GetCursorScreenPoint();
2260   aura::Window* root_window = window_->GetRootWindow();
2261   if (!root_window)
2262     return;
2263
2264   gfx::Point root_window_point = screen_point;
2265   aura::client::ScreenPositionClient* screen_position_client =
2266       aura::client::GetScreenPositionClient(root_window);
2267   if (screen_position_client) {
2268     screen_position_client->ConvertPointFromScreen(
2269         root_window, &root_window_point);
2270   }
2271
2272   if (root_window->GetEventHandlerForPoint(root_window_point) != window_)
2273     return;
2274
2275   gfx::NativeCursor cursor = current_cursor_.GetNativeCursor();
2276   // Do not show loading cursor when the cursor is currently hidden.
2277   if (is_loading_ && cursor != ui::kCursorNone)
2278     cursor = ui::kCursorPointer;
2279
2280   aura::client::CursorClient* cursor_client =
2281       aura::client::GetCursorClient(root_window);
2282   if (cursor_client) {
2283     cursor_client->SetCursor(cursor);
2284   }
2285 }
2286
2287 ui::InputMethod* RenderWidgetHostViewAura::GetInputMethod() const {
2288   aura::Window* root_window = window_->GetRootWindow();
2289   if (!root_window)
2290     return NULL;
2291   return root_window->GetProperty(aura::client::kRootWindowInputMethodKey);
2292 }
2293
2294 bool RenderWidgetHostViewAura::NeedsInputGrab() {
2295   return popup_type_ == blink::WebPopupTypeSelect;
2296 }
2297
2298 void RenderWidgetHostViewAura::FinishImeCompositionSession() {
2299   if (!has_composition_text_)
2300     return;
2301   if (host_) {
2302     host_->ImeConfirmComposition(base::string16(), gfx::Range::InvalidRange(),
2303                                  false);
2304   }
2305   ImeCancelComposition();
2306 }
2307
2308 void RenderWidgetHostViewAura::ModifyEventMovementAndCoords(
2309     blink::WebMouseEvent* event) {
2310   // If the mouse has just entered, we must report zero movementX/Y. Hence we
2311   // reset any global_mouse_position set previously.
2312   if (event->type == blink::WebInputEvent::MouseEnter ||
2313       event->type == blink::WebInputEvent::MouseLeave)
2314     global_mouse_position_.SetPoint(event->globalX, event->globalY);
2315
2316   // Movement is computed by taking the difference of the new cursor position
2317   // and the previous. Under mouse lock the cursor will be warped back to the
2318   // center so that we are not limited by clipping boundaries.
2319   // We do not measure movement as the delta from cursor to center because
2320   // we may receive more mouse movement events before our warp has taken
2321   // effect.
2322   event->movementX = event->globalX - global_mouse_position_.x();
2323   event->movementY = event->globalY - global_mouse_position_.y();
2324
2325   global_mouse_position_.SetPoint(event->globalX, event->globalY);
2326
2327   // Under mouse lock, coordinates of mouse are locked to what they were when
2328   // mouse lock was entered.
2329   if (mouse_locked_) {
2330     event->x = unlocked_mouse_position_.x();
2331     event->y = unlocked_mouse_position_.y();
2332     event->windowX = unlocked_mouse_position_.x();
2333     event->windowY = unlocked_mouse_position_.y();
2334     event->globalX = unlocked_global_mouse_position_.x();
2335     event->globalY = unlocked_global_mouse_position_.y();
2336   } else {
2337     unlocked_mouse_position_.SetPoint(event->windowX, event->windowY);
2338     unlocked_global_mouse_position_.SetPoint(event->globalX, event->globalY);
2339   }
2340 }
2341
2342 void RenderWidgetHostViewAura::NotifyRendererOfCursorVisibilityState(
2343     bool is_visible) {
2344   if (host_->is_hidden() ||
2345       (cursor_visibility_state_in_renderer_ == VISIBLE && is_visible) ||
2346       (cursor_visibility_state_in_renderer_ == NOT_VISIBLE && !is_visible))
2347     return;
2348
2349   cursor_visibility_state_in_renderer_ = is_visible ? VISIBLE : NOT_VISIBLE;
2350   host_->SendCursorVisibilityState(is_visible);
2351 }
2352
2353 void RenderWidgetHostViewAura::SetOverscrollControllerEnabled(bool enabled) {
2354   if (!enabled)
2355     overscroll_controller_.reset();
2356   else if (!overscroll_controller_)
2357     overscroll_controller_.reset(new OverscrollController());
2358 }
2359
2360 void RenderWidgetHostViewAura::SnapToPhysicalPixelBoundary() {
2361   // The top left corner of our view in window coordinates might not land on a
2362   // device pixel boundary if we have a non-integer device scale. In that case,
2363   // to avoid the web contents area looking blurry we translate the web contents
2364   // in the +x, +y direction to land on the nearest pixel boundary. This may
2365   // cause the bottom and right edges to be clipped slightly, but that's ok.
2366   aura::Window* snapped = NULL;
2367   // On desktop, use the root window. On alternative environment (ash),
2368   // use the toplevel window which must be already snapped.
2369   if (gfx::Screen::GetScreenFor(window_) !=
2370       gfx::Screen::GetScreenByType(gfx::SCREEN_TYPE_ALTERNATE)) {
2371     snapped = window_->GetRootWindow();
2372   } else {
2373     snapped = window_->GetToplevelWindow();
2374   }
2375   if (snapped && snapped != window_)
2376     ui::SnapLayerToPhysicalPixelBoundary(snapped->layer(), window_->layer());
2377
2378   has_snapped_to_boundary_ = true;
2379 }
2380
2381 void RenderWidgetHostViewAura::InternalSetBounds(const gfx::Rect& rect) {
2382   if (HasDisplayPropertyChanged(window_))
2383     host_->InvalidateScreenInfo();
2384
2385   SnapToPhysicalPixelBoundary();
2386   // Don't recursively call SetBounds if this bounds update is the result of
2387   // a Window::SetBoundsInternal call.
2388   if (!in_bounds_changed_)
2389     window_->SetBounds(rect);
2390   host_->WasResized();
2391   delegated_frame_host_->WasResized();
2392   if (touch_editing_client_) {
2393     touch_editing_client_->OnSelectionOrCursorChanged(selection_anchor_rect_,
2394       selection_focus_rect_);
2395   }
2396 #if defined(OS_WIN)
2397   // Create the legacy dummy window which corresponds to the bounds of the
2398   // webcontents. This will be passed as the container window for windowless
2399   // plugins.
2400   // Plugins like Flash assume the container window which is returned via the
2401   // NPNVnetscapeWindow property corresponds to the bounds of the webpage.
2402   // This is not true in Aura where we have only HWND which is the main Aura
2403   // window. If we return this window to plugins like Flash then it causes the
2404   // coordinate translations done by these plugins to break.
2405   // Additonally the legacy dummy window is needed for accessibility and for
2406   // scrolling to work in legacy drivers for trackpoints/trackpads, etc.
2407   if (!legacy_window_destroyed_ && GetNativeViewId()) {
2408     if (!legacy_render_widget_host_HWND_) {
2409       legacy_render_widget_host_HWND_ = LegacyRenderWidgetHostHWND::Create(
2410           reinterpret_cast<HWND>(GetNativeViewId()));
2411     }
2412     if (legacy_render_widget_host_HWND_) {
2413       legacy_render_widget_host_HWND_->set_host(this);
2414       legacy_render_widget_host_HWND_->SetBounds(
2415           window_->GetBoundsInRootWindow());
2416       // There are cases where the parent window is created, made visible and
2417       // the associated RenderWidget is also visible before the
2418       // LegacyRenderWidgetHostHWND instace is created. Ensure that it is shown
2419       // here.
2420       if (!host_->is_hidden())
2421         legacy_render_widget_host_HWND_->Show();
2422     }
2423   }
2424
2425   if (mouse_locked_)
2426     UpdateMouseLockRegion();
2427 #endif
2428 }
2429
2430 void RenderWidgetHostViewAura::SchedulePaintIfNotInClip(
2431     const gfx::Rect& rect,
2432     const gfx::Rect& clip) {
2433   if (!clip.IsEmpty()) {
2434     gfx::Rect to_paint = gfx::SubtractRects(rect, clip);
2435     if (!to_paint.IsEmpty())
2436       window_->SchedulePaintInRect(to_paint);
2437   } else {
2438     window_->SchedulePaintInRect(rect);
2439   }
2440 }
2441
2442 bool RenderWidgetHostViewAura::ShouldMoveToCenter() {
2443   gfx::Rect rect = window_->bounds();
2444   rect = ConvertRectToScreen(rect);
2445   int border_x = rect.width() * kMouseLockBorderPercentage / 100;
2446   int border_y = rect.height() * kMouseLockBorderPercentage / 100;
2447
2448   return global_mouse_position_.x() < rect.x() + border_x ||
2449       global_mouse_position_.x() > rect.right() - border_x ||
2450       global_mouse_position_.y() < rect.y() + border_y ||
2451       global_mouse_position_.y() > rect.bottom() - border_y;
2452 }
2453
2454 void RenderWidgetHostViewAura::AddedToRootWindow() {
2455   window_->GetHost()->AddObserver(this);
2456   UpdateScreenInfo(window_);
2457
2458   aura::client::CursorClient* cursor_client =
2459       aura::client::GetCursorClient(window_->GetRootWindow());
2460   if (cursor_client) {
2461     cursor_client->AddObserver(this);
2462     NotifyRendererOfCursorVisibilityState(cursor_client->IsCursorVisible());
2463   }
2464   if (HasFocus()) {
2465     ui::InputMethod* input_method = GetInputMethod();
2466     if (input_method)
2467       input_method->SetFocusedTextInputClient(this);
2468   }
2469
2470 #if defined(OS_WIN)
2471   // The parent may have changed here. Ensure that the legacy window is
2472   // reparented accordingly.
2473   if (legacy_render_widget_host_HWND_)
2474     legacy_render_widget_host_HWND_->UpdateParent(
2475         reinterpret_cast<HWND>(GetNativeViewId()));
2476 #endif
2477
2478   delegated_frame_host_->AddedToWindow();
2479 }
2480
2481 void RenderWidgetHostViewAura::RemovingFromRootWindow() {
2482   aura::client::CursorClient* cursor_client =
2483       aura::client::GetCursorClient(window_->GetRootWindow());
2484   if (cursor_client)
2485     cursor_client->RemoveObserver(this);
2486
2487   DetachFromInputMethod();
2488
2489   window_->GetHost()->RemoveObserver(this);
2490   delegated_frame_host_->RemovingFromWindow();
2491
2492 #if defined(OS_WIN)
2493   // Update the legacy window's parent temporarily to the desktop window. It
2494   // will eventually get reparented to the right root.
2495   if (legacy_render_widget_host_HWND_)
2496     legacy_render_widget_host_HWND_->UpdateParent(::GetDesktopWindow());
2497 #endif
2498 }
2499
2500 void RenderWidgetHostViewAura::DetachFromInputMethod() {
2501   ui::InputMethod* input_method = GetInputMethod();
2502   if (input_method && input_method->GetTextInputClient() == this)
2503     input_method->SetFocusedTextInputClient(NULL);
2504 }
2505
2506 void RenderWidgetHostViewAura::ForwardKeyboardEvent(
2507     const NativeWebKeyboardEvent& event) {
2508 #if defined(OS_LINUX) && !defined(OS_CHROMEOS)
2509   ui::TextEditKeyBindingsDelegateAuraLinux* keybinding_delegate =
2510       ui::GetTextEditKeyBindingsDelegate();
2511   std::vector<ui::TextEditCommandAuraLinux> commands;
2512   if (!event.skip_in_browser &&
2513       keybinding_delegate &&
2514       event.os_event &&
2515       keybinding_delegate->MatchEvent(*event.os_event, &commands)) {
2516     // Transform from ui/ types to content/ types.
2517     EditCommands edit_commands;
2518     for (std::vector<ui::TextEditCommandAuraLinux>::const_iterator it =
2519              commands.begin(); it != commands.end(); ++it) {
2520       edit_commands.push_back(EditCommand(it->GetCommandString(),
2521                                           it->argument()));
2522     }
2523     host_->Send(new InputMsg_SetEditCommandsForNextKeyEvent(
2524         host_->GetRoutingID(), edit_commands));
2525     NativeWebKeyboardEvent copy_event(event);
2526     copy_event.match_edit_command = true;
2527     host_->ForwardKeyboardEvent(copy_event);
2528     return;
2529   }
2530 #endif
2531
2532   host_->ForwardKeyboardEvent(event);
2533 }
2534
2535 SkColorType RenderWidgetHostViewAura::PreferredReadbackFormat() {
2536   return kN32_SkColorType;
2537 }
2538
2539 ////////////////////////////////////////////////////////////////////////////////
2540 // DelegatedFrameHost, public:
2541
2542 ui::Compositor* RenderWidgetHostViewAura::GetCompositor() const {
2543   aura::WindowTreeHost* host = window_->GetHost();
2544   return host ? host->compositor() : NULL;
2545 }
2546
2547 ui::Layer* RenderWidgetHostViewAura::GetLayer() {
2548   return window_->layer();
2549 }
2550
2551 RenderWidgetHostImpl* RenderWidgetHostViewAura::GetHost() {
2552   return host_;
2553 }
2554
2555 bool RenderWidgetHostViewAura::IsVisible() {
2556   return IsShowing();
2557 }
2558
2559 gfx::Size RenderWidgetHostViewAura::DesiredFrameSize() {
2560   return window_->bounds().size();
2561 }
2562
2563 float RenderWidgetHostViewAura::CurrentDeviceScaleFactor() {
2564   return current_device_scale_factor_;
2565 }
2566
2567 gfx::Size RenderWidgetHostViewAura::ConvertViewSizeToPixel(
2568     const gfx::Size& size) {
2569   return content::ConvertViewSizeToPixel(this, size);
2570 }
2571
2572 scoped_ptr<ResizeLock> RenderWidgetHostViewAura::CreateResizeLock(
2573     bool defer_compositor_lock) {
2574   gfx::Size desired_size = window_->bounds().size();
2575   return scoped_ptr<ResizeLock>(new CompositorResizeLock(
2576       window_->GetHost(),
2577       desired_size,
2578       defer_compositor_lock,
2579       base::TimeDelta::FromMilliseconds(kResizeLockTimeoutMs)));
2580 }
2581
2582 DelegatedFrameHost* RenderWidgetHostViewAura::GetDelegatedFrameHost() const {
2583   return delegated_frame_host_.get();
2584 }
2585
2586 ////////////////////////////////////////////////////////////////////////////////
2587 // RenderWidgetHostViewBase, public:
2588
2589 // static
2590 void RenderWidgetHostViewBase::GetDefaultScreenInfo(WebScreenInfo* results) {
2591   GetScreenInfoForWindow(results, NULL);
2592 }
2593
2594 }  // namespace content