1 // Copyright (c) 2012 The Chromium Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
5 #include "content/browser/renderer_host/render_widget_host_view_aura.h"
7 #include "base/auto_reset.h"
8 #include "base/basictypes.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"
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"
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"
98 using gfx::RectToSkIRect;
99 using gfx::SkIRectToRect;
101 using blink::WebScreenInfo;
102 using blink::WebInputEvent;
103 using blink::WebGestureEvent;
104 using blink::WebTouchEvent;
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;
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;
126 // Used to associate a plugin HWND with its RenderWidgetHostViewAura instance.
127 const wchar_t kWidgetOwnerProperty[] = L"RenderWidgetHostViewAuraOwner";
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);
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());
148 BOOL CALLBACK ShowWindowsCallback(HWND window, LPARAM param) {
149 RenderWidgetHostViewAura* widget =
150 reinterpret_cast<RenderWidgetHostViewAura*>(param);
152 if (GetProp(window, kWidgetOwnerProperty) == widget &&
153 widget->GetNativeView()->GetHost()) {
154 HWND parent = widget->GetNativeView()->GetHost()->GetAcceleratedWidget();
155 SetParent(window, parent);
160 struct CutoutRectsParams {
161 RenderWidgetHostViewAura* widget;
162 std::vector<gfx::Rect> cutout_rects;
163 std::map<HWND, WebPluginGeometry>* geometry;
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);
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.
177 params->widget->GetNativeView()->GetHost()->GetAcceleratedWidget();
179 offset.x = offset.y = 0;
180 MapWindowPoints(window, parent, &offset, 1);
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) {
191 if (i == params->geometry->end()) {
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);
208 gfx::SubtractRectanglesFromRegion(hrgn, cutout_rects);
209 // If we don't have any cutout rects then no point in messing with the
211 if (cutout_rects.size())
212 SetWindowRgn(window, hrgn, TRUE);
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);
222 if (::IsWindowVisible(window)) {
223 const HWND owner = ::GetWindow(window, GW_OWNER);
224 if (toplevel_hwnd == owner) {
225 ::PostMessage(window, WM_CANCELMODE, 0, 0);
233 void UpdateWebTouchEventAfterDispatch(blink::WebTouchEvent* event,
234 blink::WebTouchPoint* point) {
235 if (point->state != blink::WebTouchPoint::StateReleased &&
236 point->state != blink::WebTouchPoint::StateCancelled)
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)
244 for (unsigned i = point - event->touches; i < new_length; ++i)
245 event->touches[i] = event->touches[i + 1];
246 event->touchesLength = new_length;
249 bool CanRendererHandleEvent(const ui::MouseEvent* event) {
250 if (event->type() == ui::ET_MOUSE_CAPTURE_CHANGED)
254 // Renderer cannot handle WM_XBUTTON or NC events.
255 switch (event->native_event().message) {
258 case WM_XBUTTONDBLCLK:
259 case WM_NCMOUSELEAVE:
261 case WM_NCLBUTTONDOWN:
263 case WM_NCLBUTTONDBLCLK:
264 case WM_NCRBUTTONDOWN:
266 case WM_NCRBUTTONDBLCLK:
267 case WM_NCMBUTTONDOWN:
269 case WM_NCMBUTTONDBLCLK:
270 case WM_NCXBUTTONDOWN:
272 case WM_NCXBUTTONDBLCLK:
277 #elif defined(USE_X11)
278 // Renderer only supports standard mouse buttons, so ignore programmable
280 switch (event->type()) {
281 case ui::ET_MOUSE_PRESSED:
282 case ui::ET_MOUSE_RELEASED:
283 return event->IsAnyButton();
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) {
295 switch (event->native_event().message) {
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.
312 results->depthPerComponent = 8;
313 results->deviceScaleFactor = display.device_scale_factor();
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;
325 results->orientationType =
326 RenderWidgetHostViewBase::GetOrientationTypeForDesktop(display);
329 bool PointerEventActivates(const ui::Event& event) {
330 if (event.type() == ui::ET_MOUSE_PRESSED)
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;
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 {
349 explicit EventFilterForPopupExit(RenderWidgetHostViewAura* rwhva)
352 aura::Env::GetInstance()->AddPreTargetHandler(this);
355 virtual ~EventFilterForPopupExit() {
356 aura::Env::GetInstance()->RemovePreTargetHandler(this);
359 // Overridden from ui::EventHandler
360 virtual void OnMouseEvent(ui::MouseEvent* event) OVERRIDE {
361 rwhva_->ApplyEventFilterForPopupExit(event);
364 virtual void OnTouchEvent(ui::TouchEvent* event) OVERRIDE {
365 rwhva_->ApplyEventFilterForPopupExit(event);
369 RenderWidgetHostViewAura* rwhva_;
371 DISALLOW_COPY_AND_ASSIGN(EventFilterForPopupExit);
374 void RenderWidgetHostViewAura::ApplyEventFilterForPopupExit(
375 ui::LocatedEvent* event) {
376 if (in_shutdown_ || is_fullscreen_ || !event->target())
379 if (event->type() != ui::ET_MOUSE_PRESSED &&
380 event->type() != ui::ET_TOUCH_PRESSED) {
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().
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 {
401 explicit WindowObserver(RenderWidgetHostViewAura* view)
403 view_->window_->AddObserver(this);
406 virtual ~WindowObserver() {
407 view_->window_->RemoveObserver(this);
410 // Overridden from aura::WindowObserver:
411 virtual void OnWindowAddedToRootWindow(aura::Window* window) OVERRIDE {
412 if (window == view_->window_)
413 view_->AddedToRootWindow();
416 virtual void OnWindowRemovingFromRootWindow(aura::Window* window,
417 aura::Window* new_root) OVERRIDE {
418 if (window == view_->window_)
419 view_->RemovingFromRootWindow();
423 RenderWidgetHostViewAura* view_;
425 DISALLOW_COPY_AND_ASSIGN(WindowObserver);
428 ////////////////////////////////////////////////////////////////////////////////
429 // RenderWidgetHostViewAura, public:
431 RenderWidgetHostViewAura::RenderWidgetHostViewAura(RenderWidgetHost* host)
432 : host_(RenderWidgetHostImpl::From(host)),
433 window_(new aura::Window(this)),
434 delegated_frame_host_(new DelegatedFrameHost(this)),
436 in_bounds_changed_(false),
437 is_fullscreen_(false),
438 popup_parent_host_view_(NULL),
439 popup_child_host_view_(NULL),
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),
448 synthetic_move_sent_(false),
449 cursor_visibility_state_in_renderer_(UNKNOWN),
451 legacy_render_widget_host_HWND_(NULL),
452 legacy_window_destroyed_(false),
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);
466 bool overscroll_enabled = base::CommandLine::ForCurrentProcess()->
467 GetSwitchValueASCII(switches::kOverscrollHistoryNavigation) != "0";
468 SetOverscrollControllerEnabled(overscroll_enabled);
471 ////////////////////////////////////////////////////////////////////////////////
472 // RenderWidgetHostViewAura, RenderWidgetHostView implementation:
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");
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);
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_;
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_);
501 old_child->popup_parent_host_view_ = NULL;
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");
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_);
518 SetBounds(bounds_in_screen);
520 #if !defined(OS_WIN) && !defined(OS_CHROMEOS)
521 if (NeedsInputGrab())
522 window_->SetCapture();
525 event_filter_for_popup_exit_.reset(new EventFilterForPopupExit(this));
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);
536 aura::Window* parent = NULL;
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);
545 gfx::Display display = gfx::Screen::GetScreenFor(window_)->
546 GetDisplayNearestWindow(reference_window);
547 parent = reference_window->GetRootWindow();
548 bounds = display.bounds();
550 aura::client::ParentWindowWithContext(window_, parent, bounds);
555 RenderWidgetHost* RenderWidgetHostViewAura::GetRenderWidgetHost() const {
559 void RenderWidgetHostViewAura::WasShown() {
561 if (!host_->is_hidden())
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);
570 renderer_latency_info.AddLatencyNumber(
571 ui::TAB_SHOW_COMPONENT, host_->GetLatencyComponentId(), 0);
573 host_->WasShown(renderer_latency_info);
575 aura::Window* root = window_->GetRootWindow();
577 aura::client::CursorClient* cursor_client =
578 aura::client::GetCursorClient(root);
580 NotifyRendererOfCursorVisibilityState(cursor_client->IsCursorVisible());
583 delegated_frame_host_->WasShown(browser_latency_info);
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());
596 LPARAM lparam = reinterpret_cast<LPARAM>(this);
597 EnumChildWindows(ui::GetHiddenWindow(), ShowWindowsCallback, lparam);
601 void RenderWidgetHostViewAura::WasHidden() {
602 if (!host_ || host_->is_hidden())
605 delegated_frame_host_->WasHidden();
608 constrained_rects_.clear();
609 aura::WindowTreeHost* host = window_->GetHost();
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());
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));
629 void RenderWidgetHostViewAura::SetBounds(const gfx::Rect& rect) {
630 gfx::Point relative_origin(rect.origin());
632 // RenderWidgetHostViewAura::SetBounds() takes screen coordinates, but
633 // Window::SetBounds() takes parent coordinates, so do the conversion here.
634 aura::Window* root = window_->GetRootWindow();
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);
644 InternalSetBounds(gfx::Rect(relative_origin, rect.size()));
647 gfx::Vector2dF RenderWidgetHostViewAura::GetLastScrollOffset() const {
648 return last_scroll_offset_;
651 gfx::NativeView RenderWidgetHostViewAura::GetNativeView() const {
655 gfx::NativeViewId RenderWidgetHostViewAura::GetNativeViewId() const {
657 aura::WindowTreeHost* host = window_->GetHost();
659 return reinterpret_cast<gfx::NativeViewId>(host->GetAcceleratedWidget());
661 return static_cast<gfx::NativeViewId>(NULL);
664 gfx::NativeViewAccessible RenderWidgetHostViewAura::GetNativeViewAccessible() {
666 aura::WindowTreeHost* host = window_->GetHost();
668 return static_cast<gfx::NativeViewAccessible>(NULL);
669 HWND hwnd = host->GetAcceleratedWidget();
670 BrowserAccessibilityManager* manager =
671 host_->GetOrCreateRootBrowserAccessibilityManager();
673 return manager->GetRoot()->ToBrowserAccessibilityWin();
677 return static_cast<gfx::NativeViewAccessible>(NULL);
680 ui::TextInputClient* RenderWidgetHostViewAura::GetTextInputClient() {
684 void RenderWidgetHostViewAura::SetKeyboardFocus() {
687 aura::WindowTreeHost* host = window_->GetHost();
689 ::SetFocus(host->GetAcceleratedWidget());
694 RenderFrameHostImpl* RenderWidgetHostViewAura::GetFocusedFrame() {
695 if (!host_->IsRenderView())
697 RenderViewHost* rvh = RenderViewHost::From(host_);
698 FrameTreeNode* focused_frame =
699 rvh->GetDelegate()->GetFrameTree()->GetFocusedFrame();
703 return focused_frame->current_frame_host();
706 void RenderWidgetHostViewAura::MovePluginWindows(
707 const std::vector<WebPluginGeometry>& plugin_window_moves) {
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());
715 HWND parent = window_->GetHost()->GetAcceleratedWidget();
716 gfx::Rect view_bounds = window_->GetBoundsInRootWindow();
717 std::vector<WebPluginGeometry> moves = plugin_window_moves;
719 gfx::Rect view_port(view_bounds.size());
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;
730 moves[i].window_rect.Offset(view_bounds.OffsetFromOrigin());
732 plugin_window_moves_[moves[i].window] = moves[i];
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);
743 MovePluginWindowsHelper(parent, moves);
745 // Make sure each plugin window (or its wrapper if it exists) has a pointer to
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);
752 if (!GetProp(window, kWidgetOwnerProperty))
753 SetProp(window, kWidgetOwnerProperty, this);
755 #endif // defined(OS_WIN)
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_);
767 void RenderWidgetHostViewAura::Blur() {
771 bool RenderWidgetHostViewAura::HasFocus() const {
772 return window_->HasFocus();
775 bool RenderWidgetHostViewAura::IsSurfaceAvailableForCopy() const {
776 return delegated_frame_host_->CanCopyToBitmap();
779 void RenderWidgetHostViewAura::Show() {
783 if (legacy_render_widget_host_HWND_)
784 legacy_render_widget_host_HWND_->Show();
788 void RenderWidgetHostViewAura::Hide() {
792 if (legacy_render_widget_host_HWND_)
793 legacy_render_widget_host_HWND_->Hide();
797 bool RenderWidgetHostViewAura::IsShowing() {
798 return window_->IsVisible();
801 gfx::Rect RenderWidgetHostViewAura::GetViewBounds() const {
802 return window_->GetBoundsInScreen();
805 void RenderWidgetHostViewAura::SetBackgroundOpaque(bool opaque) {
806 RenderWidgetHostViewBase::SetBackgroundOpaque(opaque);
807 host_->SetBackgroundOpaque(opaque);
808 window_->layer()->SetFillsBoundsOpaquely(opaque);
811 gfx::Size RenderWidgetHostViewAura::GetVisibleViewportSize() const {
812 gfx::Rect requested_rect(GetRequestedRendererSize());
813 requested_rect.Inset(insets_);
814 return requested_rect.size();
817 void RenderWidgetHostViewAura::SetInsets(const gfx::Insets& insets) {
818 if (insets != insets_) {
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();
832 void RenderWidgetHostViewAura::SetIsLoading(bool is_loading) {
833 is_loading_ = is_loading;
834 UpdateCursorIfOverSelf();
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_);
850 if (params.show_ime_if_needed && params.type != ui::TEXT_INPUT_TYPE_NONE) {
851 if (GetInputMethod())
852 GetInputMethod()->ShowImeIfNeeded();
856 void RenderWidgetHostViewAura::ImeCancelComposition() {
857 if (GetInputMethod())
858 GetInputMethod()->CancelComposition(this);
859 has_composition_text_ = false;
862 void RenderWidgetHostViewAura::ImeCompositionRangeChanged(
863 const gfx::Range& range,
864 const std::vector<gfx::Rect>& character_bounds) {
865 composition_character_bounds_ = character_bounds;
868 void RenderWidgetHostViewAura::RenderProcessGone(base::TerminationStatus status,
870 UpdateCursorIfOverSelf();
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.
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);
895 void RenderWidgetHostViewAura::SelectionChanged(const base::string16& text,
897 const gfx::Range& range) {
898 RenderWidgetHostViewBase::SelectionChanged(text, offset, range);
900 #if defined(USE_X11) && !defined(OS_CHROMEOS)
901 if (text.empty() || range.is_empty())
903 size_t pos = range.GetMin() - offset;
904 size_t n = range.length();
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.";
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)
918 gfx::Size RenderWidgetHostViewAura::GetRequestedRendererSize() const {
919 return delegated_frame_host_->GetRequestedRendererSize();
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)
928 selection_anchor_rect_ = params.anchor_rect;
929 selection_focus_rect_ = params.focus_rect;
931 if (GetInputMethod())
932 GetInputMethod()->OnCaretBoundsChanged(this);
934 if (touch_editing_client_) {
935 touch_editing_client_->OnSelectionOrCursorChanged(selection_anchor_rect_,
936 selection_focus_rect_);
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);
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);
957 bool RenderWidgetHostViewAura::CanCopyToVideoFrame() const {
958 return delegated_frame_host_->CanCopyToVideoFrame();
961 bool RenderWidgetHostViewAura::CanSubscribeFrame() const {
962 return delegated_frame_host_->CanSubscribeFrame();
965 void RenderWidgetHostViewAura::BeginFrameSubscription(
966 scoped_ptr<RenderWidgetHostViewFrameSubscriber> subscriber) {
967 delegated_frame_host_->BeginFrameSubscription(subscriber.Pass());
970 void RenderWidgetHostViewAura::EndFrameSubscription() {
971 delegated_frame_host_->EndFrameSubscription();
974 void RenderWidgetHostViewAura::AcceleratedSurfaceInitialized(int host_id,
979 bool RenderWidgetHostViewAura::UsesNativeWindowFrame() const {
980 return (legacy_render_widget_host_HWND_ != NULL);
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())
990 if (rects == constrained_rects_)
993 constrained_rects_ = rects;
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>(¶ms);
1001 EnumChildWindows(parent, SetCutoutRectsCallback, lparam);
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);
1012 void RenderWidgetHostViewAura::OnLegacyWindowDestroyed() {
1013 legacy_render_widget_host_HWND_ = NULL;
1014 legacy_window_destroyed_ = true;
1018 void RenderWidgetHostViewAura::AcceleratedSurfaceBuffersSwapped(
1019 const GpuHostMsg_AcceleratedSurfaceBuffersSwapped_Params& params_in_pixel,
1021 // Oldschool composited mode is no longer supported.
1024 void RenderWidgetHostViewAura::OnSwapCompositorFrame(
1025 uint32 output_surface_id,
1026 scoped_ptr<cc::CompositorFrame> frame) {
1027 TRACE_EVENT0("content", "RenderWidgetHostViewAura::OnSwapCompositorFrame");
1029 last_scroll_offset_ = frame->metadata.root_scroll_offset;
1030 if (frame->delegated_frame_data) {
1031 delegated_frame_host_->SwapDelegatedFrame(
1033 frame->delegated_frame_data.Pass(),
1034 frame->metadata.device_scale_factor,
1035 frame->metadata.latency_info);
1039 if (frame->software_frame_data) {
1040 DLOG(ERROR) << "Unable to use software frame in aura";
1042 base::UserMetricsAction("BadMessageTerminate_SharedMemoryAura"));
1043 host_->GetProcess()->ReceivedBadMessage();
1048 void RenderWidgetHostViewAura::DidStopFlinging() {
1049 if (touch_editing_client_)
1050 touch_editing_client_->DidStopFlinging();
1054 void RenderWidgetHostViewAura::SetParentNativeViewAccessible(
1055 gfx::NativeViewAccessible accessible_parent) {
1058 gfx::NativeViewId RenderWidgetHostViewAura::GetParentForWindowlessPlugin()
1060 if (legacy_render_widget_host_HWND_) {
1061 return reinterpret_cast<gfx::NativeViewId>(
1062 legacy_render_widget_host_HWND_->hwnd());
1068 void RenderWidgetHostViewAura::AcceleratedSurfacePostSubBuffer(
1069 const GpuHostMsg_AcceleratedSurfacePostSubBuffer_Params& params_in_pixel,
1071 // Oldschool composited mode is no longer supported.
1074 void RenderWidgetHostViewAura::AcceleratedSurfaceSuspend() {
1077 void RenderWidgetHostViewAura::AcceleratedSurfaceRelease() {
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.
1088 void RenderWidgetHostViewAura::GetScreenInfo(WebScreenInfo* results) {
1089 GetScreenInfoForWindow(results, window_->GetRootWindow() ? window_ : NULL);
1092 gfx::Rect RenderWidgetHostViewAura::GetBoundsInRootWindow() {
1093 aura::Window* top_level = window_->GetToplevelWindow();
1094 gfx::Rect bounds(top_level->GetBoundsInScreen());
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
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();
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);
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));
1119 bounds.Inset(GetSystemMetrics(SM_CXPADDEDBORDER),
1120 GetSystemMetrics(SM_CXPADDEDBORDER));
1124 bounds = gfx::win::ScreenToDIPRect(bounds);
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));
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);
1145 if (overscroll_controller_) {
1146 overscroll_controller_->ReceivedEventACK(
1147 event, (INPUT_EVENT_ACK_STATE_CONSUMED == ack_result));
1151 void RenderWidgetHostViewAura::ProcessAckedTouchEvent(
1152 const TouchEventWithLatencyInfo& touch, InputEventAckState ack_result) {
1153 ScopedVector<ui::TouchEvent> events;
1154 if (!MakeUITouchEventsFromWebTouchEvents(touch, &events,
1155 SCREEN_COORDINATES))
1158 aura::WindowTreeHost* host = window_->GetHost();
1159 // |host| is NULL during tests.
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);
1171 scoped_ptr<SyntheticGestureTarget>
1172 RenderWidgetHostViewAura::CreateSyntheticGestureTarget() {
1173 return scoped_ptr<SyntheticGestureTarget>(
1174 new SyntheticGestureTargetAura(host_));
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) {
1192 if (overscroll_controller_)
1193 consumed |= overscroll_controller_->WillHandleEvent(input_event);
1195 return consumed && !WebTouchEvent::isTouchEventType(input_event.type)
1196 ? INPUT_EVENT_ACK_STATE_CONSUMED
1197 : INPUT_EVENT_ACK_STATE_NOT_CONSUMED;
1200 BrowserAccessibilityManager*
1201 RenderWidgetHostViewAura::CreateBrowserAccessibilityManager(
1202 BrowserAccessibilityDelegate* delegate) {
1203 BrowserAccessibilityManager* manager = NULL;
1205 manager = new BrowserAccessibilityManagerWin(
1206 BrowserAccessibilityManagerWin::GetEmptyDocument(), delegate);
1208 manager = BrowserAccessibilityManager::Create(
1209 BrowserAccessibilityManager::GetEmptyDocument(), delegate);
1214 gfx::AcceleratedWidget
1215 RenderWidgetHostViewAura::AccessibilityGetAcceleratedWidget() {
1217 if (legacy_render_widget_host_HWND_)
1218 return legacy_render_widget_host_HWND_->hwnd();
1220 return gfx::kNullAcceleratedWidget;
1223 gfx::NativeViewAccessible
1224 RenderWidgetHostViewAura::AccessibilityGetNativeViewAccessible() {
1226 if (legacy_render_widget_host_HWND_)
1227 return legacy_render_widget_host_HWND_->window_accessible();
1233 gfx::GLSurfaceHandle RenderWidgetHostViewAura::GetCompositingSurface() {
1234 return ImageTransportFactory::GetInstance()->GetSharedSurfaceHandle();
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);
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)));
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_;
1255 CopyFromCompositingSurface(
1256 disambiguation_target_rect_,
1258 base::Bind(&RenderWidgetHostViewAura::DisambiguationPopupRendered,
1259 base::internal::SupportsWeakPtrBase::StaticAsWeakPtr
1260 <RenderWidgetHostViewAura>(this)),
1264 void RenderWidgetHostViewAura::DisambiguationPopupRendered(
1266 const SkBitmap& result) {
1267 if (!success || disambiguation_scroll_offset_ != last_scroll_offset_)
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;
1277 delegate_view = delegate->GetDelegateView();
1278 if (delegate_view) {
1279 delegate_view->ShowDisambiguationPopup(
1280 disambiguation_target_rect_,
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)));
1291 void RenderWidgetHostViewAura::HideDisambiguationPopup() {
1292 RenderViewHostDelegate* delegate = NULL;
1293 if (host_->IsRenderView())
1294 delegate = RenderViewHost::From(host_)->GetDelegate();
1295 RenderViewHostDelegateView* delegate_view = NULL;
1297 delegate_view = delegate->GetDelegateView();
1299 delegate_view->HideDisambiguationPopup();
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)
1311 host_->ForwardGestureEvent(web_gesture);
1314 void RenderWidgetHostViewAura::ProcessDisambiguationMouse(
1315 ui::MouseEvent* event) {
1316 blink::WebMouseEvent web_mouse = content::MakeWebMouseEvent(event);
1317 host_->ForwardMouseEvent(web_mouse);
1320 bool RenderWidgetHostViewAura::LockMouse() {
1321 aura::Window* root_window = window_->GetRootWindow();
1328 mouse_locked_ = true;
1329 #if !defined(OS_WIN)
1330 window_->SetCapture();
1332 UpdateMouseLockRegion();
1334 aura::client::CursorClient* cursor_client =
1335 aura::client::GetCursorClient(root_window);
1336 if (cursor_client) {
1337 cursor_client->HideCursor();
1338 cursor_client->LockCursor();
1341 if (ShouldMoveToCenter()) {
1342 synthetic_move_sent_ = true;
1343 window_->MoveCursorTo(gfx::Rect(window_->bounds().size()).CenterPoint());
1345 tooltip_disabler_.reset(new aura::client::ScopedTooltipDisabler(root_window));
1349 void RenderWidgetHostViewAura::UnlockMouse() {
1350 tooltip_disabler_.reset();
1352 aura::Window* root_window = window_->GetRootWindow();
1353 if (!mouse_locked_ || !root_window)
1356 mouse_locked_ = false;
1358 #if !defined(OS_WIN)
1359 window_->ReleaseCapture();
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();
1371 host_->LostMouseLock();
1374 ////////////////////////////////////////////////////////////////////////////////
1375 // RenderWidgetHostViewAura, ui::TextInputClient implementation:
1376 void RenderWidgetHostViewAura::SetCompositionText(
1377 const ui::CompositionText& composition) {
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),
1393 it->background_color));
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());
1402 has_composition_text_ = !composition.text.empty();
1405 void RenderWidgetHostViewAura::ConfirmCompositionText() {
1406 if (host_ && has_composition_text_) {
1407 host_->ImeConfirmComposition(base::string16(), gfx::Range::InvalidRange(),
1410 has_composition_text_ = false;
1413 void RenderWidgetHostViewAura::ClearCompositionText() {
1414 if (host_ && has_composition_text_)
1415 host_->ImeCancelComposition();
1416 has_composition_text_ = false;
1419 void RenderWidgetHostViewAura::InsertText(const base::string16& text) {
1420 DCHECK(text_input_type_ != ui::TEXT_INPUT_TYPE_NONE);
1422 host_->ImeConfirmComposition(text, gfx::Range::InvalidRange(), false);
1423 has_composition_text_ = false;
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);
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,
1441 ForwardKeyboardEvent(webkit_event);
1445 gfx::NativeWindow RenderWidgetHostViewAura::GetAttachedWindow() const {
1449 ui::TextInputType RenderWidgetHostViewAura::GetTextInputType() const {
1450 return text_input_type_;
1453 ui::TextInputMode RenderWidgetHostViewAura::GetTextInputMode() const {
1454 return text_input_mode_;
1457 bool RenderWidgetHostViewAura::CanComposeInline() const {
1458 return can_compose_inline_;
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());
1466 aura::Window* root_window = window_->GetRootWindow();
1469 aura::client::ScreenPositionClient* screen_position_client =
1470 aura::client::GetScreenPositionClient(root_window);
1471 if (!screen_position_client)
1473 screen_position_client->ConvertPointToScreen(window_, &origin);
1474 screen_position_client->ConvertPointToScreen(window_, &end);
1475 return gfx::Rect(origin.x(),
1477 end.x() - origin.x(),
1478 end.y() - origin.y());
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());
1486 aura::Window* root_window = window_->GetRootWindow();
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(),
1494 end.x() - origin.x(),
1495 end.y() - origin.y());
1501 gfx::Rect RenderWidgetHostViewAura::GetCaretBounds() const {
1502 const gfx::Rect rect =
1503 gfx::UnionRects(selection_anchor_rect_, selection_focus_rect_);
1504 return ConvertRectToScreen(rect);
1507 bool RenderWidgetHostViewAura::GetCompositionCharacterBounds(
1509 gfx::Rect* rect) const {
1511 if (index >= composition_character_bounds_.size())
1513 *rect = ConvertRectToScreen(composition_character_bounds_[index]);
1517 bool RenderWidgetHostViewAura::HasCompositionText() const {
1518 return has_composition_text_;
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());
1527 bool RenderWidgetHostViewAura::GetCompositionTextRange(
1528 gfx::Range* range) const {
1529 // TODO(suzhe): implement this method when fixing http://crbug.com/55130.
1534 bool RenderWidgetHostViewAura::GetSelectionRange(gfx::Range* range) const {
1535 range->set_start(selection_range_.start());
1536 range->set_end(selection_range_.end());
1540 bool RenderWidgetHostViewAura::SetSelectionRange(const gfx::Range& range) {
1541 // TODO(suzhe): implement this method when fixing http://crbug.com/55130.
1546 bool RenderWidgetHostViewAura::DeleteRange(const gfx::Range& range) {
1547 // TODO(suzhe): implement this method when fixing http://crbug.com/55130.
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());
1558 if (!selection_text_range.Contains(range)) {
1562 if (selection_text_range.EqualsIgnoringDirection(range)) {
1563 // Avoid calling substr whose performance is low.
1564 *text = selection_text_;
1566 *text = selection_text_.substr(
1567 range.GetMin() - selection_text_offset_,
1573 void RenderWidgetHostViewAura::OnInputMethodChanged() {
1577 if (GetInputMethod())
1578 host_->SetInputMethodActive(GetInputMethod()->IsActive());
1580 // TODO(suzhe): implement the newly added “locale” property of HTML DOM
1584 bool RenderWidgetHostViewAura::ChangeTextDirectionAndLayoutAlignment(
1585 base::i18n::TextDirection direction) {
1588 host_->UpdateTextDirection(
1589 direction == base::i18n::RIGHT_TO_LEFT ?
1590 blink::WebTextDirectionRightToLeft :
1591 blink::WebTextDirectionLeftToRight);
1592 host_->NotifyTextDirection();
1596 void RenderWidgetHostViewAura::ExtendSelectionAndDelete(
1597 size_t before, size_t after) {
1598 RenderFrameHostImpl* rfh = GetFocusedFrame();
1600 rfh->ExtendSelectionAndDelete(before, after);
1603 void RenderWidgetHostViewAura::EnsureCaretInRect(const gfx::Rect& rect) {
1604 gfx::Rect intersected_rect(
1605 gfx::IntersectRects(rect, window_->GetBoundsInScreen()));
1607 if (intersected_rect.IsEmpty())
1610 host_->ScrollFocusedEditableNodeIntoRect(
1611 ConvertRectFromScreen(intersected_rect));
1614 void RenderWidgetHostViewAura::OnCandidateWindowShown() {
1615 host_->CandidateWindowShown();
1618 void RenderWidgetHostViewAura::OnCandidateWindowUpdated() {
1619 host_->CandidateWindowUpdated();
1622 void RenderWidgetHostViewAura::OnCandidateWindowHidden() {
1623 host_->CandidateWindowHidden();
1626 bool RenderWidgetHostViewAura::IsEditingCommandEnabled(int command_id) {
1630 void RenderWidgetHostViewAura::ExecuteEditingCommand(int command_id) {
1633 ////////////////////////////////////////////////////////////////////////////////
1634 // RenderWidgetHostViewAura, gfx::DisplayObserver implementation:
1636 void RenderWidgetHostViewAura::OnDisplayAdded(
1637 const gfx::Display& new_display) {
1640 void RenderWidgetHostViewAura::OnDisplayRemoved(
1641 const gfx::Display& old_display) {
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();
1655 ////////////////////////////////////////////////////////////////////////////////
1656 // RenderWidgetHostViewAura, aura::WindowDelegate implementation:
1658 gfx::Size RenderWidgetHostViewAura::GetMinimumSize() const {
1662 gfx::Size RenderWidgetHostViewAura::GetMaximumSize() const {
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
1674 SetSize(new_bounds.size());
1676 if (GetInputMethod())
1677 GetInputMethod()->OnCaretBoundsChanged(this);
1680 gfx::NativeCursor RenderWidgetHostViewAura::GetCursor(const gfx::Point& point) {
1682 return ui::kCursorNone;
1683 return current_cursor_.GetNativeCursor();
1686 int RenderWidgetHostViewAura::GetNonClientComponent(
1687 const gfx::Point& point) const {
1691 bool RenderWidgetHostViewAura::ShouldDescendIntoChildForEventHandling(
1692 aura::Window* child,
1693 const gfx::Point& location) {
1697 bool RenderWidgetHostViewAura::CanFocus() {
1698 return popup_type_ == blink::WebPopupTypeNone;
1701 void RenderWidgetHostViewAura::OnCaptureLost() {
1702 host_->LostCapture();
1703 if (touch_editing_client_)
1704 touch_editing_client_->EndTouchEditing(false);
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
1711 if (window_->layer()->fills_bounds_opaquely())
1712 canvas->DrawColor(SK_ColorWHITE);
1715 void RenderWidgetHostViewAura::OnDeviceScaleFactorChanged(
1716 float device_scale_factor) {
1717 if (!host_ || !window_->GetRootWindow())
1720 UpdateScreenInfo(window_);
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();
1729 void RenderWidgetHostViewAura::OnWindowDestroying(aura::Window* window) {
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();
1737 parent = window_->GetHost()->GetAcceleratedWidget();
1739 LPARAM lparam = reinterpret_cast<LPARAM>(this);
1740 EnumChildWindows(parent, WindowDestroyingCallback, lparam);
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
1753 legacy_render_widget_host_HWND_ = NULL;
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();
1762 input_method->DetachTextInputClient(this);
1764 if (overscroll_controller_)
1765 overscroll_controller_->Reset();
1768 void RenderWidgetHostViewAura::OnWindowDestroyed(aura::Window* window) {
1769 host_->ViewDestroyed();
1773 void RenderWidgetHostViewAura::OnWindowTargetVisibilityChanged(bool visible) {
1776 bool RenderWidgetHostViewAura::HasHitTestMask() const {
1780 void RenderWidgetHostViewAura::GetHitTestMask(gfx::Path* mask) const {
1783 ////////////////////////////////////////////////////////////////////////////////
1784 // RenderWidgetHostViewAura, ui::EventHandler implementation:
1786 void RenderWidgetHostViewAura::OnKeyEvent(ui::KeyEvent* event) {
1787 TRACE_EVENT0("input", "RenderWidgetHostViewAura::OnKeyEvent");
1788 if (touch_editing_client_ && touch_editing_client_->HandleInputEvent(event))
1791 if (popup_child_host_view_ && popup_child_host_view_->NeedsInputGrab()) {
1792 popup_child_host_view_->OnKeyEvent(event);
1793 if (event->handled())
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);
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);
1810 if (!tracker.Contains(window)) {
1811 event->SetHandled();
1816 if (!in_shutdown_) {
1817 in_shutdown_ = true;
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_)
1825 // Accept return key character events between press and release events.
1826 accept_return_character_ = event->type() == ui::ET_KEY_PRESSED;
1829 // We don't have to communicate with an input method here.
1830 if (!event->HasNativeEvent()) {
1831 NativeWebKeyboardEvent webkit_event(
1834 event->is_char() ? event->GetCharacter() : event->key_code(),
1836 ui::EventTimeForNow().InSecondsF());
1837 ForwardKeyboardEvent(webkit_event);
1839 NativeWebKeyboardEvent webkit_event(event);
1840 ForwardKeyboardEvent(webkit_event);
1843 event->SetHandled();
1846 void RenderWidgetHostViewAura::OnMouseEvent(ui::MouseEvent* event) {
1847 TRACE_EVENT0("input", "RenderWidgetHostViewAura::OnMouseEvent");
1849 if (touch_editing_client_ && touch_editing_client_->HandleInputEvent(event))
1852 if (mouse_locked_) {
1853 aura::client::CursorClient* cursor_client =
1854 aura::client::GetCursorClient(window_->GetRootWindow());
1855 DCHECK(!cursor_client || !cursor_client->IsCursorVisible());
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);
1865 gfx::Point center(gfx::Rect(window_->bounds().size()).CenterPoint());
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);
1876 blink::WebMouseEvent mouse_event = MakeWebMouseEvent(event);
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();
1882 ModifyEventMovementAndCoords(&mouse_event);
1884 bool should_not_forward = is_move_to_center_event && synthetic_move_sent_;
1885 if (should_not_forward) {
1886 synthetic_move_sent_ = false;
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);
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)
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
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();
1922 if (event->type() == ui::ET_MOUSEWHEEL) {
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
1927 aura::WindowTreeHost* host = window_->GetHost();
1929 HWND parent = host->GetAcceleratedWidget();
1930 HWND toplevel_hwnd = ::GetAncestor(parent, GA_ROOT);
1931 EnumThreadWindows(GetCurrentThreadId(),
1933 reinterpret_cast<LPARAM>(toplevel_hwnd));
1936 // The Disambiguation popup does not parent itself from this window, so we
1937 // manually dismiss it.
1938 HideDisambiguationPopup();
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)
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();
1962 case ui::ET_MOUSE_RELEASED:
1963 window_->ReleaseCapture();
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);
1981 if (!IsXButtonUpEvent(event))
1982 event->SetHandled();
1985 void RenderWidgetHostViewAura::OnScrollEvent(ui::ScrollEvent* event) {
1986 TRACE_EVENT0("input", "RenderWidgetHostViewAura::OnScrollEvent");
1987 if (touch_editing_client_ && touch_editing_client_->HandleInputEvent(event))
1990 if (event->type() == ui::ET_SCROLL) {
1991 #if !defined(OS_WIN)
1993 // Investigate if this is true for Windows 8 Metro ASH as well.
1994 if (event->finger_count() != 2)
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"));
2013 event->SetHandled();
2016 void RenderWidgetHostViewAura::OnTouchEvent(ui::TouchEvent* event) {
2017 TRACE_EVENT0("input", "RenderWidgetHostViewAura::OnTouchEvent");
2018 if (touch_editing_client_ && touch_editing_client_->HandleInputEvent(event))
2021 // Update the touch event first.
2022 blink::WebTouchPoint* point = UpdateWebTouchEventFromUIEvent(*event,
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();
2035 if (host_->ShouldForwardTouchEvent())
2036 host_->ForwardTouchEventWithLatencyInfo(touch_event_, *event->latency());
2037 UpdateWebTouchEventAfterDispatch(&touch_event_, point);
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();
2050 if (touch_editing_client_ && touch_editing_client_->HandleInputEvent(event))
2053 RenderViewHostDelegate* delegate = NULL;
2054 if (host_->IsRenderView())
2055 delegate = RenderViewHost::From(host_)->GetDelegate();
2057 if (delegate && event->type() == ui::ET_GESTURE_BEGIN &&
2058 event->details().touch_points() == 1) {
2059 delegate->HandleGestureBegin();
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);
2072 if (gesture.type != blink::WebInputEvent::Undefined) {
2073 host_->ForwardGestureEventWithLatencyInfo(gesture, *event->latency());
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"));
2084 if (delegate && event->type() == ui::ET_GESTURE_END &&
2085 event->details().touch_points() == 1) {
2086 delegate->HandleGestureEnd();
2089 // If a gesture is not processed by the webpage, then WebKit processes it
2090 // (e.g. generates synthetic mouse events).
2091 event->SetHandled();
2094 ////////////////////////////////////////////////////////////////////////////////
2095 // RenderWidgetHostViewAura, aura::client::ActivationDelegate implementation:
2097 bool RenderWidgetHostViewAura::ShouldActivate() const {
2098 aura::WindowTreeHost* host = window_->GetHost();
2101 const ui::Event* event = host->dispatcher()->current_event();
2104 return is_fullscreen_;
2107 ////////////////////////////////////////////////////////////////////////////////
2108 // RenderWidgetHostViewAura,
2109 // aura::client::ActivationChangeObserver implementation:
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();
2121 ////////////////////////////////////////////////////////////////////////////////
2122 // RenderWidgetHostViewAura, aura::client::CursorClientObserver implementation:
2124 void RenderWidgetHostViewAura::OnCursorVisibilityChanged(bool is_visible) {
2125 NotifyRendererOfCursorVisibilityState(is_visible);
2128 ////////////////////////////////////////////////////////////////////////////////
2129 // RenderWidgetHostViewAura, aura::client::FocusChangeObserver implementation:
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())
2142 host_->SetActive(true);
2144 ui::InputMethod* input_method = GetInputMethod();
2146 // Ask the system-wide IME to send all TextInputClient messages to |this|
2148 input_method->SetFocusedTextInputClient(this);
2149 host_->SetInputMethodActive(input_method->IsActive());
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
2154 host_->SuppressNextCharEvents();
2156 host_->SetInputMethodActive(false);
2159 BrowserAccessibilityManager* manager =
2160 host_->GetRootBrowserAccessibilityManager();
2162 manager->OnWindowFocused();
2163 } else if (window_ == lost_focus) {
2164 host_->SetActive(false);
2167 DetachFromInputMethod();
2168 host_->SetInputMethodActive(false);
2170 if (touch_editing_client_)
2171 touch_editing_client_->EndTouchEditing(false);
2173 if (overscroll_controller_)
2174 overscroll_controller_->Cancel();
2176 BrowserAccessibilityManager* manager =
2177 host_->GetRootBrowserAccessibilityManager();
2179 manager->OnWindowBlurred();
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) {
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) {
2195 ::GetCursorPos(&point);
2196 if (screen->GetDisplayNearestWindow(window_).id() !=
2197 screen->GetDisplayNearestPoint(gfx::Point(point)).id())
2201 in_shutdown_ = true;
2207 ////////////////////////////////////////////////////////////////////////////////
2208 // RenderWidgetHostViewAura, aura::WindowTreeHostObserver implementation:
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());
2215 UpdateScreenInfo(window_);
2218 ////////////////////////////////////////////////////////////////////////////////
2219 // RenderWidgetHostViewAura, private:
2221 RenderWidgetHostViewAura::~RenderWidgetHostViewAura() {
2222 if (touch_editing_client_)
2223 touch_editing_client_->OnViewDestroyed();
2225 delegated_frame_host_.reset();
2226 window_observer_.reset();
2227 if (window_->GetHost())
2228 window_->GetHost()->RemoveObserver(this);
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;
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;
2240 event_filter_for_popup_exit_.reset();
2241 aura::client::SetTooltipText(window_, NULL);
2242 gfx::Screen::GetScreenFor(window_)->RemoveObserver(this);
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();
2250 // The LegacyRenderWidgetHostHWND window should have been destroyed in
2251 // RenderWidgetHostViewAura::OnWindowDestroying and the pointer should
2253 DCHECK(!legacy_render_widget_host_HWND_);
2257 void RenderWidgetHostViewAura::UpdateCursorIfOverSelf() {
2258 const gfx::Point screen_point =
2259 gfx::Screen::GetScreenFor(GetNativeView())->GetCursorScreenPoint();
2260 aura::Window* root_window = window_->GetRootWindow();
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);
2272 if (root_window->GetEventHandlerForPoint(root_window_point) != window_)
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;
2280 aura::client::CursorClient* cursor_client =
2281 aura::client::GetCursorClient(root_window);
2282 if (cursor_client) {
2283 cursor_client->SetCursor(cursor);
2287 ui::InputMethod* RenderWidgetHostViewAura::GetInputMethod() const {
2288 aura::Window* root_window = window_->GetRootWindow();
2291 return root_window->GetProperty(aura::client::kRootWindowInputMethodKey);
2294 bool RenderWidgetHostViewAura::NeedsInputGrab() {
2295 return popup_type_ == blink::WebPopupTypeSelect;
2298 void RenderWidgetHostViewAura::FinishImeCompositionSession() {
2299 if (!has_composition_text_)
2302 host_->ImeConfirmComposition(base::string16(), gfx::Range::InvalidRange(),
2305 ImeCancelComposition();
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);
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
2322 event->movementX = event->globalX - global_mouse_position_.x();
2323 event->movementY = event->globalY - global_mouse_position_.y();
2325 global_mouse_position_.SetPoint(event->globalX, event->globalY);
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();
2337 unlocked_mouse_position_.SetPoint(event->windowX, event->windowY);
2338 unlocked_global_mouse_position_.SetPoint(event->globalX, event->globalY);
2342 void RenderWidgetHostViewAura::NotifyRendererOfCursorVisibilityState(
2344 if (host_->is_hidden() ||
2345 (cursor_visibility_state_in_renderer_ == VISIBLE && is_visible) ||
2346 (cursor_visibility_state_in_renderer_ == NOT_VISIBLE && !is_visible))
2349 cursor_visibility_state_in_renderer_ = is_visible ? VISIBLE : NOT_VISIBLE;
2350 host_->SendCursorVisibilityState(is_visible);
2353 void RenderWidgetHostViewAura::SetOverscrollControllerEnabled(bool enabled) {
2355 overscroll_controller_.reset();
2356 else if (!overscroll_controller_)
2357 overscroll_controller_.reset(new OverscrollController());
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();
2373 snapped = window_->GetToplevelWindow();
2375 if (snapped && snapped != window_)
2376 ui::SnapLayerToPhysicalPixelBoundary(snapped->layer(), window_->layer());
2378 has_snapped_to_boundary_ = true;
2381 void RenderWidgetHostViewAura::InternalSetBounds(const gfx::Rect& rect) {
2382 if (HasDisplayPropertyChanged(window_))
2383 host_->InvalidateScreenInfo();
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_);
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
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()));
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
2420 if (!host_->is_hidden())
2421 legacy_render_widget_host_HWND_->Show();
2426 UpdateMouseLockRegion();
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);
2438 window_->SchedulePaintInRect(rect);
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;
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;
2454 void RenderWidgetHostViewAura::AddedToRootWindow() {
2455 window_->GetHost()->AddObserver(this);
2456 UpdateScreenInfo(window_);
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());
2465 ui::InputMethod* input_method = GetInputMethod();
2467 input_method->SetFocusedTextInputClient(this);
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()));
2478 delegated_frame_host_->AddedToWindow();
2481 void RenderWidgetHostViewAura::RemovingFromRootWindow() {
2482 aura::client::CursorClient* cursor_client =
2483 aura::client::GetCursorClient(window_->GetRootWindow());
2485 cursor_client->RemoveObserver(this);
2487 DetachFromInputMethod();
2489 window_->GetHost()->RemoveObserver(this);
2490 delegated_frame_host_->RemovingFromWindow();
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());
2500 void RenderWidgetHostViewAura::DetachFromInputMethod() {
2501 ui::InputMethod* input_method = GetInputMethod();
2502 if (input_method && input_method->GetTextInputClient() == this)
2503 input_method->SetFocusedTextInputClient(NULL);
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 &&
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(),
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);
2532 host_->ForwardKeyboardEvent(event);
2535 SkColorType RenderWidgetHostViewAura::PreferredReadbackFormat() {
2536 return kN32_SkColorType;
2539 ////////////////////////////////////////////////////////////////////////////////
2540 // DelegatedFrameHost, public:
2542 ui::Compositor* RenderWidgetHostViewAura::GetCompositor() const {
2543 aura::WindowTreeHost* host = window_->GetHost();
2544 return host ? host->compositor() : NULL;
2547 ui::Layer* RenderWidgetHostViewAura::GetLayer() {
2548 return window_->layer();
2551 RenderWidgetHostImpl* RenderWidgetHostViewAura::GetHost() {
2555 bool RenderWidgetHostViewAura::IsVisible() {
2559 gfx::Size RenderWidgetHostViewAura::DesiredFrameSize() {
2560 return window_->bounds().size();
2563 float RenderWidgetHostViewAura::CurrentDeviceScaleFactor() {
2564 return current_device_scale_factor_;
2567 gfx::Size RenderWidgetHostViewAura::ConvertViewSizeToPixel(
2568 const gfx::Size& size) {
2569 return content::ConvertViewSizeToPixel(this, size);
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(
2578 defer_compositor_lock,
2579 base::TimeDelta::FromMilliseconds(kResizeLockTimeoutMs)));
2582 DelegatedFrameHost* RenderWidgetHostViewAura::GetDelegatedFrameHost() const {
2583 return delegated_frame_host_.get();
2586 ////////////////////////////////////////////////////////////////////////////////
2587 // RenderWidgetHostViewBase, public:
2590 void RenderWidgetHostViewBase::GetDefaultScreenInfo(WebScreenInfo* results) {
2591 GetScreenInfoForWindow(results, NULL);
2594 } // namespace content