DevTools: cut host and port from webSocketDebuggerUrl in addition to ws:// prefix
[chromium-blink-merge.git] / content / browser / renderer_host / render_widget_host_view_aura.cc
blob009ce15549f746c3aa636c6872e0539cb1ebeb25
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 <set>
9 #include "base/auto_reset.h"
10 #include "base/basictypes.h"
11 #include "base/bind.h"
12 #include "base/callback_helpers.h"
13 #include "base/command_line.h"
14 #include "base/logging.h"
15 #include "base/message_loop/message_loop.h"
16 #include "base/strings/string_number_conversions.h"
17 #include "base/trace_event/trace_event.h"
18 #include "cc/layers/layer.h"
19 #include "cc/output/copy_output_request.h"
20 #include "cc/output/copy_output_result.h"
21 #include "cc/resources/texture_mailbox.h"
22 #include "cc/trees/layer_tree_settings.h"
23 #include "content/browser/accessibility/browser_accessibility_manager.h"
24 #include "content/browser/accessibility/browser_accessibility_state_impl.h"
25 #include "content/browser/bad_message.h"
26 #include "content/browser/frame_host/frame_tree.h"
27 #include "content/browser/frame_host/frame_tree_node.h"
28 #include "content/browser/frame_host/render_frame_host_impl.h"
29 #include "content/browser/gpu/compositor_util.h"
30 #include "content/browser/renderer_host/compositor_resize_lock_aura.h"
31 #include "content/browser/renderer_host/dip_util.h"
32 #include "content/browser/renderer_host/input/synthetic_gesture_target_aura.h"
33 #include "content/browser/renderer_host/input/web_input_event_util.h"
34 #include "content/browser/renderer_host/overscroll_controller.h"
35 #include "content/browser/renderer_host/render_view_host_delegate.h"
36 #include "content/browser/renderer_host/render_view_host_delegate_view.h"
37 #include "content/browser/renderer_host/render_view_host_impl.h"
38 #include "content/browser/renderer_host/render_widget_host_impl.h"
39 #include "content/browser/renderer_host/ui_events_helper.h"
40 #include "content/browser/renderer_host/web_input_event_aura.h"
41 #include "content/common/gpu/client/gl_helper.h"
42 #include "content/common/gpu/gpu_messages.h"
43 #include "content/common/view_messages.h"
44 #include "content/public/browser/content_browser_client.h"
45 #include "content/public/browser/overscroll_configuration.h"
46 #include "content/public/browser/render_view_host.h"
47 #include "content/public/browser/render_widget_host_view_frame_subscriber.h"
48 #include "content/public/browser/user_metrics.h"
49 #include "content/public/common/content_switches.h"
50 #include "third_party/WebKit/public/platform/WebScreenInfo.h"
51 #include "third_party/WebKit/public/web/WebCompositionUnderline.h"
52 #include "third_party/WebKit/public/web/WebInputEvent.h"
53 #include "ui/aura/client/aura_constants.h"
54 #include "ui/aura/client/cursor_client.h"
55 #include "ui/aura/client/cursor_client_observer.h"
56 #include "ui/aura/client/focus_client.h"
57 #include "ui/aura/client/screen_position_client.h"
58 #include "ui/aura/client/window_tree_client.h"
59 #include "ui/aura/env.h"
60 #include "ui/aura/window.h"
61 #include "ui/aura/window_event_dispatcher.h"
62 #include "ui/aura/window_observer.h"
63 #include "ui/aura/window_tracker.h"
64 #include "ui/aura/window_tree_host.h"
65 #include "ui/base/clipboard/scoped_clipboard_writer.h"
66 #include "ui/base/hit_test.h"
67 #include "ui/base/ime/input_method.h"
68 #include "ui/base/ui_base_types.h"
69 #include "ui/compositor/compositor_vsync_manager.h"
70 #include "ui/compositor/dip_util.h"
71 #include "ui/events/blink/blink_event_util.h"
72 #include "ui/events/event.h"
73 #include "ui/events/event_utils.h"
74 #include "ui/events/gestures/gesture_recognizer.h"
75 #include "ui/gfx/canvas.h"
76 #include "ui/gfx/display.h"
77 #include "ui/gfx/geometry/rect_conversions.h"
78 #include "ui/gfx/geometry/size_conversions.h"
79 #include "ui/gfx/screen.h"
80 #include "ui/gfx/skia_util.h"
81 #include "ui/wm/public/activation_client.h"
82 #include "ui/wm/public/scoped_tooltip_disabler.h"
83 #include "ui/wm/public/tooltip_client.h"
84 #include "ui/wm/public/transient_window_client.h"
85 #include "ui/wm/public/window_types.h"
87 #if defined(OS_WIN)
88 #include "content/browser/accessibility/browser_accessibility_manager_win.h"
89 #include "content/browser/accessibility/browser_accessibility_win.h"
90 #include "content/browser/renderer_host/legacy_render_widget_host_win.h"
91 #include "content/common/plugin_constants_win.h"
92 #include "ui/base/win/hidden_window.h"
93 #include "ui/gfx/gdi_util.h"
94 #include "ui/gfx/win/dpi.h"
95 #endif
97 #if defined(OS_LINUX) && !defined(OS_CHROMEOS)
98 #include "content/common/input_messages.h"
99 #include "ui/events/linux/text_edit_command_auralinux.h"
100 #include "ui/events/linux/text_edit_key_bindings_delegate_auralinux.h"
101 #endif
103 using gfx::RectToSkIRect;
104 using gfx::SkIRectToRect;
106 using blink::WebScreenInfo;
107 using blink::WebInputEvent;
108 using blink::WebGestureEvent;
109 using blink::WebTouchEvent;
111 namespace content {
113 namespace {
115 // In mouse lock mode, we need to prevent the (invisible) cursor from hitting
116 // the border of the view, in order to get valid movement information. However,
117 // forcing the cursor back to the center of the view after each mouse move
118 // doesn't work well. It reduces the frequency of useful mouse move messages
119 // significantly. Therefore, we move the cursor to the center of the view only
120 // if it approaches the border. |kMouseLockBorderPercentage| specifies the width
121 // of the border area, in percentage of the corresponding dimension.
122 const int kMouseLockBorderPercentage = 15;
124 // When accelerated compositing is enabled and a widget resize is pending,
125 // we delay further resizes of the UI. The following constant is the maximum
126 // length of time that we should delay further UI resizes while waiting for a
127 // resized frame from a renderer.
128 const int kResizeLockTimeoutMs = 67;
130 #if defined(OS_WIN)
131 // Used to associate a plugin HWND with its RenderWidgetHostViewAura instance.
132 const wchar_t kWidgetOwnerProperty[] = L"RenderWidgetHostViewAuraOwner";
134 BOOL CALLBACK WindowDestroyingCallback(HWND window, LPARAM param) {
135 RenderWidgetHostViewAura* widget =
136 reinterpret_cast<RenderWidgetHostViewAura*>(param);
137 if (GetProp(window, kWidgetOwnerProperty) == widget) {
138 // Properties set on HWNDs must be removed to avoid leaks.
139 RemoveProp(window, kWidgetOwnerProperty);
140 RenderWidgetHostViewBase::DetachPluginWindowsCallback(window);
142 return TRUE;
145 BOOL CALLBACK HideWindowsCallback(HWND window, LPARAM param) {
146 RenderWidgetHostViewAura* widget =
147 reinterpret_cast<RenderWidgetHostViewAura*>(param);
148 if (GetProp(window, kWidgetOwnerProperty) == widget)
149 SetParent(window, ui::GetHiddenWindow());
150 return TRUE;
153 BOOL CALLBACK ShowWindowsCallback(HWND window, LPARAM param) {
154 RenderWidgetHostViewAura* widget =
155 reinterpret_cast<RenderWidgetHostViewAura*>(param);
157 if (GetProp(window, kWidgetOwnerProperty) == widget &&
158 widget->GetNativeView()->GetHost()) {
159 HWND parent = widget->GetNativeView()->GetHost()->GetAcceleratedWidget();
160 SetParent(window, parent);
162 return TRUE;
165 struct CutoutRectsParams {
166 RenderWidgetHostViewAura* widget;
167 std::vector<gfx::Rect> cutout_rects;
168 std::map<HWND, WebPluginGeometry>* geometry;
171 // Used to update the region for the windowed plugin to draw in. We start with
172 // the clip rect from the renderer, then remove the cutout rects from the
173 // renderer, and then remove the transient windows from the root window and the
174 // constrained windows from the parent window.
175 BOOL CALLBACK SetCutoutRectsCallback(HWND window, LPARAM param) {
176 CutoutRectsParams* params = reinterpret_cast<CutoutRectsParams*>(param);
178 if (GetProp(window, kWidgetOwnerProperty) == params->widget) {
179 // First calculate the offset of this plugin from the root window, since
180 // the cutouts are relative to the root window.
181 HWND parent =
182 params->widget->GetNativeView()->GetHost()->GetAcceleratedWidget();
183 POINT offset;
184 offset.x = offset.y = 0;
185 MapWindowPoints(window, parent, &offset, 1);
187 // Now get the cached clip rect and cutouts for this plugin window that came
188 // from the renderer.
189 std::map<HWND, WebPluginGeometry>::iterator i = params->geometry->begin();
190 while (i != params->geometry->end() &&
191 i->second.window != window &&
192 GetParent(i->second.window) != window) {
193 ++i;
196 if (i == params->geometry->end()) {
197 NOTREACHED();
198 return TRUE;
201 HRGN hrgn = CreateRectRgn(i->second.clip_rect.x(),
202 i->second.clip_rect.y(),
203 i->second.clip_rect.right(),
204 i->second.clip_rect.bottom());
205 // We start with the cutout rects that came from the renderer, then add the
206 // ones that came from transient and constrained windows.
207 std::vector<gfx::Rect> cutout_rects = i->second.cutout_rects;
208 for (size_t i = 0; i < params->cutout_rects.size(); ++i) {
209 gfx::Rect offset_cutout = params->cutout_rects[i];
210 offset_cutout.Offset(-offset.x, -offset.y);
211 cutout_rects.push_back(offset_cutout);
213 gfx::SubtractRectanglesFromRegion(hrgn, cutout_rects);
214 // If we don't have any cutout rects then no point in messing with the
215 // window region.
216 if (cutout_rects.size())
217 SetWindowRgn(window, hrgn, TRUE);
219 return TRUE;
222 // A callback function for EnumThreadWindows to enumerate and dismiss
223 // any owned popup windows.
224 BOOL CALLBACK DismissOwnedPopups(HWND window, LPARAM arg) {
225 const HWND toplevel_hwnd = reinterpret_cast<HWND>(arg);
227 if (::IsWindowVisible(window)) {
228 const HWND owner = ::GetWindow(window, GW_OWNER);
229 if (toplevel_hwnd == owner) {
230 ::PostMessage(window, WM_CANCELMODE, 0, 0);
234 return TRUE;
236 #endif
238 // We don't mark these as handled so that they're sent back to the
239 // DefWindowProc so it can generate WM_APPCOMMAND as necessary.
240 bool IsXButtonUpEvent(const ui::MouseEvent* event) {
241 #if defined(OS_WIN)
242 switch (event->native_event().message) {
243 case WM_XBUTTONUP:
244 case WM_NCXBUTTONUP:
245 return true;
247 #endif
248 return false;
251 void GetScreenInfoForWindow(WebScreenInfo* results, aura::Window* window) {
252 const gfx::Display display = window ?
253 gfx::Screen::GetScreenFor(window)->GetDisplayNearestWindow(window) :
254 gfx::Screen::GetScreenFor(window)->GetPrimaryDisplay();
255 results->rect = display.bounds();
256 results->availableRect = display.work_area();
257 // TODO(derat|oshima): Don't hardcode this. Get this from display object.
258 results->depth = 24;
259 results->depthPerComponent = 8;
260 results->deviceScaleFactor = display.device_scale_factor();
262 // The Display rotation and the WebScreenInfo orientation are not the same
263 // angle. The former is the physical display rotation while the later is the
264 // rotation required by the content to be shown properly on the screen, in
265 // other words, relative to the physical display.
266 results->orientationAngle = display.RotationAsDegree();
267 if (results->orientationAngle == 90)
268 results->orientationAngle = 270;
269 else if (results->orientationAngle == 270)
270 results->orientationAngle = 90;
272 results->orientationType =
273 RenderWidgetHostViewBase::GetOrientationTypeForDesktop(display);
276 bool IsFractionalScaleFactor(float scale_factor) {
277 return (scale_factor - static_cast<int>(scale_factor)) > 0;
280 // Reset unchanged touch point to StateStationary for touchmove and
281 // touchcancel.
282 void MarkUnchangedTouchPointsAsStationary(
283 blink::WebTouchEvent* event,
284 int changed_touch_id) {
285 if (event->type == blink::WebInputEvent::TouchMove ||
286 event->type == blink::WebInputEvent::TouchCancel) {
287 for (size_t i = 0; i < event->touchesLength; ++i) {
288 if (event->touches[i].id != changed_touch_id)
289 event->touches[i].state = blink::WebTouchPoint::StateStationary;
294 } // namespace
296 // We need to watch for mouse events outside a Web Popup or its parent
297 // and dismiss the popup for certain events.
298 class RenderWidgetHostViewAura::EventFilterForPopupExit
299 : public ui::EventHandler {
300 public:
301 explicit EventFilterForPopupExit(RenderWidgetHostViewAura* rwhva)
302 : rwhva_(rwhva) {
303 DCHECK(rwhva_);
304 aura::Env::GetInstance()->AddPreTargetHandler(this);
307 ~EventFilterForPopupExit() override {
308 aura::Env::GetInstance()->RemovePreTargetHandler(this);
311 // Overridden from ui::EventHandler
312 void OnMouseEvent(ui::MouseEvent* event) override {
313 rwhva_->ApplyEventFilterForPopupExit(event);
316 void OnTouchEvent(ui::TouchEvent* event) override {
317 rwhva_->ApplyEventFilterForPopupExit(event);
320 private:
321 RenderWidgetHostViewAura* rwhva_;
323 DISALLOW_COPY_AND_ASSIGN(EventFilterForPopupExit);
326 void RenderWidgetHostViewAura::ApplyEventFilterForPopupExit(
327 ui::LocatedEvent* event) {
328 if (in_shutdown_ || is_fullscreen_ || !event->target())
329 return;
331 if (event->type() != ui::ET_MOUSE_PRESSED &&
332 event->type() != ui::ET_TOUCH_PRESSED) {
333 return;
336 aura::Window* target = static_cast<aura::Window*>(event->target());
337 if (target != window_ &&
338 (!popup_parent_host_view_ ||
339 target != popup_parent_host_view_->window_)) {
340 // If we enter this code path it means that we did not receive any focus
341 // lost notifications for the popup window. Ensure that blink is aware
342 // of the fact that focus was lost for the host window by sending a Blur
343 // notification.
344 if (popup_parent_host_view_ && popup_parent_host_view_->host_)
345 popup_parent_host_view_->host_->Blur();
346 // Note: popup_parent_host_view_ may be NULL when there are multiple
347 // popup children per view. See: RenderWidgetHostViewAura::InitAsPopup().
348 Shutdown();
352 // We have to implement the WindowObserver interface on a separate object
353 // because clang doesn't like implementing multiple interfaces that have
354 // methods with the same name. This object is owned by the
355 // RenderWidgetHostViewAura.
356 class RenderWidgetHostViewAura::WindowObserver : public aura::WindowObserver {
357 public:
358 explicit WindowObserver(RenderWidgetHostViewAura* view)
359 : view_(view) {
360 view_->window_->AddObserver(this);
363 ~WindowObserver() override { view_->window_->RemoveObserver(this); }
365 // Overridden from aura::WindowObserver:
366 void OnWindowAddedToRootWindow(aura::Window* window) override {
367 if (window == view_->window_)
368 view_->AddedToRootWindow();
371 void OnWindowRemovingFromRootWindow(aura::Window* window,
372 aura::Window* new_root) override {
373 if (window == view_->window_)
374 view_->RemovingFromRootWindow();
377 void OnWindowHierarchyChanged(const HierarchyChangeParams& params) override {
378 view_->ParentHierarchyChanged();
381 private:
382 RenderWidgetHostViewAura* view_;
384 DISALLOW_COPY_AND_ASSIGN(WindowObserver);
387 // This class provides functionality to observe the ancestors of the RWHVA for
388 // bounds changes. This is done to snap the RWHVA window to a pixel boundary,
389 // which could change when the bounds relative to the root changes.
390 // An example where this happens is below:-
391 // The fast resize code path for bookmarks where in the parent of RWHVA which
392 // is WCV has its bounds changed before the bookmark is hidden. This results in
393 // the traditional bounds change notification for the WCV reporting the old
394 // bounds as the bookmark is still around. Observing all the ancestors of the
395 // RWHVA window enables us to know when the bounds of the window relative to
396 // root changes and allows us to snap accordingly.
397 class RenderWidgetHostViewAura::WindowAncestorObserver
398 : public aura::WindowObserver {
399 public:
400 explicit WindowAncestorObserver(RenderWidgetHostViewAura* view)
401 : view_(view) {
402 aura::Window* parent = view_->window_->parent();
403 while (parent) {
404 parent->AddObserver(this);
405 ancestors_.insert(parent);
406 parent = parent->parent();
410 ~WindowAncestorObserver() override {
411 RemoveAncestorObservers();
414 void OnWindowBoundsChanged(aura::Window* window,
415 const gfx::Rect& old_bounds,
416 const gfx::Rect& new_bounds) override {
417 DCHECK(ancestors_.find(window) != ancestors_.end());
418 if (new_bounds.origin() != old_bounds.origin())
419 view_->HandleParentBoundsChanged();
422 private:
423 void RemoveAncestorObservers() {
424 for (auto ancestor : ancestors_)
425 ancestor->RemoveObserver(this);
426 ancestors_.clear();
429 RenderWidgetHostViewAura* view_;
430 std::set<aura::Window*> ancestors_;
432 DISALLOW_COPY_AND_ASSIGN(WindowAncestorObserver);
435 ////////////////////////////////////////////////////////////////////////////////
436 // RenderWidgetHostViewAura, public:
438 RenderWidgetHostViewAura::RenderWidgetHostViewAura(RenderWidgetHost* host,
439 bool is_guest_view_hack)
440 : host_(RenderWidgetHostImpl::From(host)),
441 window_(new aura::Window(this)),
442 delegated_frame_host_(new DelegatedFrameHost(this)),
443 in_shutdown_(false),
444 in_bounds_changed_(false),
445 is_fullscreen_(false),
446 popup_parent_host_view_(NULL),
447 popup_child_host_view_(NULL),
448 is_loading_(false),
449 text_input_type_(ui::TEXT_INPUT_TYPE_NONE),
450 text_input_mode_(ui::TEXT_INPUT_MODE_DEFAULT),
451 text_input_flags_(0),
452 can_compose_inline_(true),
453 has_composition_text_(false),
454 accept_return_character_(false),
455 last_swapped_software_frame_scale_factor_(1.f),
456 paint_canvas_(NULL),
457 synthetic_move_sent_(false),
458 cursor_visibility_state_in_renderer_(UNKNOWN),
459 #if defined(OS_WIN)
460 legacy_render_widget_host_HWND_(NULL),
461 legacy_window_destroyed_(false),
462 showing_context_menu_(false),
463 #endif
464 has_snapped_to_boundary_(false),
465 touch_editing_client_(NULL),
466 is_guest_view_hack_(is_guest_view_hack),
467 begin_frame_observer_proxy_(this),
468 weak_ptr_factory_(this) {
469 if (!is_guest_view_hack_)
470 host_->SetView(this);
472 window_observer_.reset(new WindowObserver(this));
474 aura::client::SetTooltipText(window_, &tooltip_);
475 aura::client::SetActivationDelegate(window_, this);
476 aura::client::SetFocusChangeObserver(window_, this);
477 window_->set_layer_owner_delegate(delegated_frame_host_.get());
478 gfx::Screen::GetScreenFor(window_)->AddObserver(this);
480 bool overscroll_enabled = base::CommandLine::ForCurrentProcess()->
481 GetSwitchValueASCII(switches::kOverscrollHistoryNavigation) != "0";
482 SetOverscrollControllerEnabled(overscroll_enabled);
485 ////////////////////////////////////////////////////////////////////////////////
486 // RenderWidgetHostViewAura, RenderWidgetHostView implementation:
488 bool RenderWidgetHostViewAura::OnMessageReceived(
489 const IPC::Message& message) {
490 bool handled = true;
491 IPC_BEGIN_MESSAGE_MAP(RenderWidgetHostViewAura, message)
492 // TODO(kevers): Move to RenderWidgetHostViewImpl and consolidate IPC
493 // messages for TextInput<State|Type>Changed. Corresponding code in
494 // RenderWidgetHostViewAndroid should also be moved at the same time.
495 IPC_MESSAGE_HANDLER(ViewHostMsg_TextInputStateChanged,
496 OnTextInputStateChanged)
497 IPC_MESSAGE_HANDLER(ViewHostMsg_SetNeedsBeginFrames,
498 OnSetNeedsBeginFrames)
499 IPC_MESSAGE_UNHANDLED(handled = false)
500 IPC_END_MESSAGE_MAP()
501 return handled;
504 void RenderWidgetHostViewAura::InitAsChild(
505 gfx::NativeView parent_view) {
506 window_->SetType(ui::wm::WINDOW_TYPE_CONTROL);
507 window_->Init(ui::LAYER_SOLID_COLOR);
508 window_->SetName("RenderWidgetHostViewAura");
509 window_->layer()->SetColor(background_color_);
512 void RenderWidgetHostViewAura::InitAsPopup(
513 RenderWidgetHostView* parent_host_view,
514 const gfx::Rect& bounds_in_screen) {
515 popup_parent_host_view_ =
516 static_cast<RenderWidgetHostViewAura*>(parent_host_view);
518 // TransientWindowClient may be NULL during tests.
519 aura::client::TransientWindowClient* transient_window_client =
520 aura::client::GetTransientWindowClient();
521 RenderWidgetHostViewAura* old_child =
522 popup_parent_host_view_->popup_child_host_view_;
523 if (old_child) {
524 // TODO(jhorwich): Allow multiple popup_child_host_view_ per view, or
525 // similar mechanism to ensure a second popup doesn't cause the first one
526 // to never get a chance to filter events. See crbug.com/160589.
527 DCHECK(old_child->popup_parent_host_view_ == popup_parent_host_view_);
528 if (transient_window_client) {
529 transient_window_client->RemoveTransientChild(
530 popup_parent_host_view_->window_, old_child->window_);
532 old_child->popup_parent_host_view_ = NULL;
534 popup_parent_host_view_->popup_child_host_view_ = this;
535 window_->SetType(ui::wm::WINDOW_TYPE_MENU);
536 window_->Init(ui::LAYER_SOLID_COLOR);
537 window_->SetName("RenderWidgetHostViewAura");
538 window_->layer()->SetColor(background_color_);
540 // Setting the transient child allows for the popup to get mouse events when
541 // in a system modal dialog. Do this before calling ParentWindowWithContext
542 // below so that the transient parent is visible to WindowTreeClient.
543 // This fixes crbug.com/328593.
544 if (transient_window_client) {
545 transient_window_client->AddTransientChild(
546 popup_parent_host_view_->window_, window_);
549 aura::Window* root = popup_parent_host_view_->window_->GetRootWindow();
550 aura::client::ParentWindowWithContext(window_, root, bounds_in_screen);
552 SetBounds(bounds_in_screen);
553 Show();
554 if (NeedsMouseCapture())
555 window_->SetCapture();
557 event_filter_for_popup_exit_.reset(new EventFilterForPopupExit(this));
560 void RenderWidgetHostViewAura::InitAsFullscreen(
561 RenderWidgetHostView* reference_host_view) {
562 is_fullscreen_ = true;
563 window_->SetType(ui::wm::WINDOW_TYPE_NORMAL);
564 window_->Init(ui::LAYER_SOLID_COLOR);
565 window_->SetName("RenderWidgetHostViewAura");
566 window_->SetProperty(aura::client::kShowStateKey, ui::SHOW_STATE_FULLSCREEN);
567 window_->layer()->SetColor(background_color_);
569 aura::Window* parent = NULL;
570 gfx::Rect bounds;
571 if (reference_host_view) {
572 aura::Window* reference_window =
573 static_cast<RenderWidgetHostViewAura*>(reference_host_view)->window_;
574 if (reference_window) {
575 host_tracker_.reset(new aura::WindowTracker);
576 host_tracker_->Add(reference_window);
578 gfx::Display display = gfx::Screen::GetScreenFor(window_)->
579 GetDisplayNearestWindow(reference_window);
580 parent = reference_window->GetRootWindow();
581 bounds = display.bounds();
583 aura::client::ParentWindowWithContext(window_, parent, bounds);
584 Show();
585 Focus();
588 RenderWidgetHost* RenderWidgetHostViewAura::GetRenderWidgetHost() const {
589 return host_;
592 void RenderWidgetHostViewAura::Show() {
593 window_->Show();
595 DCHECK(host_);
596 if (!host_->is_hidden())
597 return;
599 bool has_saved_frame = delegated_frame_host_->HasSavedFrame();
600 ui::LatencyInfo renderer_latency_info, browser_latency_info;
601 if (has_saved_frame) {
602 browser_latency_info.AddLatencyNumber(
603 ui::TAB_SHOW_COMPONENT, host_->GetLatencyComponentId(), 0);
604 } else {
605 renderer_latency_info.AddLatencyNumber(
606 ui::TAB_SHOW_COMPONENT, host_->GetLatencyComponentId(), 0);
608 host_->WasShown(renderer_latency_info);
610 aura::Window* root = window_->GetRootWindow();
611 if (root) {
612 aura::client::CursorClient* cursor_client =
613 aura::client::GetCursorClient(root);
614 if (cursor_client)
615 NotifyRendererOfCursorVisibilityState(cursor_client->IsCursorVisible());
618 delegated_frame_host_->WasShown(browser_latency_info);
620 #if defined(OS_WIN)
621 if (legacy_render_widget_host_HWND_) {
622 // Reparent the legacy Chrome_RenderWidgetHostHWND window to the parent
623 // window before reparenting any plugins. This ensures that the plugin
624 // windows stay on top of the child Zorder in the parent and receive
625 // mouse events, etc.
626 legacy_render_widget_host_HWND_->UpdateParent(
627 GetNativeView()->GetHost()->GetAcceleratedWidget());
628 legacy_render_widget_host_HWND_->SetBounds(
629 window_->GetBoundsInRootWindow());
631 LPARAM lparam = reinterpret_cast<LPARAM>(this);
632 EnumChildWindows(ui::GetHiddenWindow(), ShowWindowsCallback, lparam);
634 if (legacy_render_widget_host_HWND_)
635 legacy_render_widget_host_HWND_->Show();
636 #endif
639 void RenderWidgetHostViewAura::Hide() {
640 window_->Hide();
642 if (host_ && !host_->is_hidden()) {
643 host_->WasHidden();
644 delegated_frame_host_->WasHidden();
646 #if defined(OS_WIN)
647 constrained_rects_.clear();
648 aura::WindowTreeHost* host = window_->GetHost();
649 if (host) {
650 HWND parent = host->GetAcceleratedWidget();
651 LPARAM lparam = reinterpret_cast<LPARAM>(this);
652 EnumChildWindows(parent, HideWindowsCallback, lparam);
653 // We reparent the legacy Chrome_RenderWidgetHostHWND window to the global
654 // hidden window on the same lines as Windowed plugin windows.
655 if (legacy_render_widget_host_HWND_)
656 legacy_render_widget_host_HWND_->UpdateParent(ui::GetHiddenWindow());
658 #endif
661 #if defined(OS_WIN)
662 if (legacy_render_widget_host_HWND_)
663 legacy_render_widget_host_HWND_->Hide();
664 #endif
667 void RenderWidgetHostViewAura::SetSize(const gfx::Size& size) {
668 // For a SetSize operation, we don't care what coordinate system the origin
669 // of the window is in, it's only important to make sure that the origin
670 // remains constant after the operation.
671 InternalSetBounds(gfx::Rect(window_->bounds().origin(), size));
674 void RenderWidgetHostViewAura::SetBounds(const gfx::Rect& rect) {
675 gfx::Point relative_origin(rect.origin());
677 // RenderWidgetHostViewAura::SetBounds() takes screen coordinates, but
678 // Window::SetBounds() takes parent coordinates, so do the conversion here.
679 aura::Window* root = window_->GetRootWindow();
680 if (root) {
681 aura::client::ScreenPositionClient* screen_position_client =
682 aura::client::GetScreenPositionClient(root);
683 if (screen_position_client) {
684 screen_position_client->ConvertPointFromScreen(
685 window_->parent(), &relative_origin);
689 InternalSetBounds(gfx::Rect(relative_origin, rect.size()));
692 gfx::Vector2dF RenderWidgetHostViewAura::GetLastScrollOffset() const {
693 return last_scroll_offset_;
696 gfx::NativeView RenderWidgetHostViewAura::GetNativeView() const {
697 return window_;
700 gfx::NativeViewId RenderWidgetHostViewAura::GetNativeViewId() const {
701 #if defined(OS_WIN)
702 aura::WindowTreeHost* host = window_->GetHost();
703 if (host)
704 return reinterpret_cast<gfx::NativeViewId>(host->GetAcceleratedWidget());
705 #endif
706 return static_cast<gfx::NativeViewId>(NULL);
709 gfx::NativeViewAccessible RenderWidgetHostViewAura::GetNativeViewAccessible() {
710 #if defined(OS_WIN)
711 aura::WindowTreeHost* host = window_->GetHost();
712 if (!host)
713 return static_cast<gfx::NativeViewAccessible>(NULL);
714 BrowserAccessibilityManager* manager =
715 host_->GetOrCreateRootBrowserAccessibilityManager();
716 if (manager)
717 return manager->GetRoot()->ToBrowserAccessibilityWin();
718 #endif
720 NOTIMPLEMENTED();
721 return static_cast<gfx::NativeViewAccessible>(NULL);
724 ui::TextInputClient* RenderWidgetHostViewAura::GetTextInputClient() {
725 return this;
728 void RenderWidgetHostViewAura::OnSetNeedsBeginFrames(bool needs_begin_frames) {
729 begin_frame_observer_proxy_.SetNeedsBeginFrames(needs_begin_frames);
732 void RenderWidgetHostViewAura::SendBeginFrame(const cc::BeginFrameArgs& args) {
733 delegated_frame_host_->SetVSyncParameters(args.frame_time, args.interval);
734 host_->Send(new ViewMsg_BeginFrame(host_->GetRoutingID(), args));
737 void RenderWidgetHostViewAura::SetKeyboardFocus() {
738 #if defined(OS_WIN)
739 if (CanFocus()) {
740 aura::WindowTreeHost* host = window_->GetHost();
741 if (host)
742 ::SetFocus(host->GetAcceleratedWidget());
744 #endif
747 RenderFrameHostImpl* RenderWidgetHostViewAura::GetFocusedFrame() {
748 if (!host_->IsRenderView())
749 return NULL;
750 RenderViewHost* rvh = RenderViewHost::From(host_);
751 FrameTreeNode* focused_frame =
752 rvh->GetDelegate()->GetFrameTree()->GetFocusedFrame();
753 if (!focused_frame)
754 return NULL;
756 return focused_frame->current_frame_host();
759 bool RenderWidgetHostViewAura::CanRendererHandleEvent(
760 const ui::MouseEvent* event,
761 bool mouse_locked,
762 bool selection_popup) {
763 #if defined(OS_WIN)
764 bool showing_context_menu = showing_context_menu_;
765 showing_context_menu_ = false;
766 #endif
768 if (event->type() == ui::ET_MOUSE_CAPTURE_CHANGED)
769 return false;
771 if ((mouse_locked || selection_popup) &&
772 (event->type() == ui::ET_MOUSE_EXITED))
773 return false;
775 #if defined(OS_WIN)
776 // Don't forward the mouse leave message which is received when the context
777 // menu is displayed by the page. This confuses the page and causes state
778 // changes.
779 if (showing_context_menu) {
780 if (event->type() == ui::ET_MOUSE_EXITED)
781 return false;
783 // Renderer cannot handle WM_XBUTTON or NC events.
784 switch (event->native_event().message) {
785 case WM_XBUTTONDOWN:
786 case WM_XBUTTONUP:
787 case WM_XBUTTONDBLCLK:
788 case WM_NCMOUSELEAVE:
789 case WM_NCMOUSEMOVE:
790 case WM_NCLBUTTONDOWN:
791 case WM_NCLBUTTONUP:
792 case WM_NCLBUTTONDBLCLK:
793 case WM_NCRBUTTONDOWN:
794 case WM_NCRBUTTONUP:
795 case WM_NCRBUTTONDBLCLK:
796 case WM_NCMBUTTONDOWN:
797 case WM_NCMBUTTONUP:
798 case WM_NCMBUTTONDBLCLK:
799 case WM_NCXBUTTONDOWN:
800 case WM_NCXBUTTONUP:
801 case WM_NCXBUTTONDBLCLK:
802 return false;
803 default:
804 break;
806 #elif defined(USE_X11)
807 // Renderer only supports standard mouse buttons, so ignore programmable
808 // buttons.
809 switch (event->type()) {
810 case ui::ET_MOUSE_PRESSED:
811 case ui::ET_MOUSE_RELEASED: {
812 const int kAllowedButtons = ui::EF_LEFT_MOUSE_BUTTON |
813 ui::EF_MIDDLE_MOUSE_BUTTON |
814 ui::EF_RIGHT_MOUSE_BUTTON;
815 return (event->flags() & kAllowedButtons) != 0;
817 default:
818 break;
820 #endif
821 return true;
824 void RenderWidgetHostViewAura::HandleParentBoundsChanged() {
825 SnapToPhysicalPixelBoundary();
826 #if defined(OS_WIN)
827 if (legacy_render_widget_host_HWND_) {
828 legacy_render_widget_host_HWND_->SetBounds(
829 window_->GetBoundsInRootWindow());
831 #endif
832 if (!in_shutdown_)
833 host_->SendScreenRects();
836 void RenderWidgetHostViewAura::ParentHierarchyChanged() {
837 ancestor_window_observer_.reset(new WindowAncestorObserver(this));
838 // Snap when we receive a hierarchy changed. http://crbug.com/388908.
839 HandleParentBoundsChanged();
842 void RenderWidgetHostViewAura::MovePluginWindows(
843 const std::vector<WebPluginGeometry>& plugin_window_moves) {
844 #if defined(OS_WIN)
845 // We need to clip the rectangle to the tab's viewport, otherwise we will draw
846 // over the browser UI.
847 if (!window_->GetRootWindow()) {
848 DCHECK(plugin_window_moves.empty());
849 return;
851 HWND parent = window_->GetHost()->GetAcceleratedWidget();
852 gfx::Rect view_bounds = window_->GetBoundsInRootWindow();
853 std::vector<WebPluginGeometry> moves = plugin_window_moves;
855 gfx::Rect view_port(view_bounds.size());
857 for (size_t i = 0; i < moves.size(); ++i) {
858 gfx::Rect clip(moves[i].clip_rect);
859 gfx::Vector2d view_port_offset(
860 moves[i].window_rect.OffsetFromOrigin());
861 clip.Offset(view_port_offset);
862 clip.Intersect(view_port);
863 clip.Offset(-view_port_offset);
864 moves[i].clip_rect = clip;
866 moves[i].window_rect.Offset(view_bounds.OffsetFromOrigin());
868 plugin_window_moves_[moves[i].window] = moves[i];
870 // constrained_rects_ are relative to the root window. We want to convert
871 // them to be relative to the plugin window.
872 for (size_t j = 0; j < constrained_rects_.size(); ++j) {
873 gfx::Rect offset_cutout = constrained_rects_[j];
874 offset_cutout -= moves[i].window_rect.OffsetFromOrigin();
875 moves[i].cutout_rects.push_back(offset_cutout);
879 MovePluginWindowsHelper(parent, moves);
881 // Make sure each plugin window (or its wrapper if it exists) has a pointer to
882 // |this|.
883 for (size_t i = 0; i < moves.size(); ++i) {
884 HWND window = moves[i].window;
885 if (GetParent(window) != parent) {
886 window = GetParent(window);
888 if (!GetProp(window, kWidgetOwnerProperty))
889 SetProp(window, kWidgetOwnerProperty, this);
891 #endif // defined(OS_WIN)
894 void RenderWidgetHostViewAura::Focus() {
895 // Make sure we have a FocusClient before attempting to Focus(). In some
896 // situations we may not yet be in a valid Window hierarchy (such as reloading
897 // after out of memory discarded the tab).
898 aura::client::FocusClient* client = aura::client::GetFocusClient(window_);
899 if (client)
900 window_->Focus();
903 bool RenderWidgetHostViewAura::HasFocus() const {
904 return window_->HasFocus();
907 bool RenderWidgetHostViewAura::IsSurfaceAvailableForCopy() const {
908 return delegated_frame_host_->CanCopyToBitmap();
911 bool RenderWidgetHostViewAura::IsShowing() {
912 return window_->IsVisible();
915 gfx::Rect RenderWidgetHostViewAura::GetViewBounds() const {
916 return window_->GetBoundsInScreen();
919 void RenderWidgetHostViewAura::SetBackgroundColor(SkColor color) {
920 RenderWidgetHostViewBase::SetBackgroundColor(color);
921 bool opaque = GetBackgroundOpaque();
922 host_->SetBackgroundOpaque(opaque);
923 window_->layer()->SetFillsBoundsOpaquely(opaque);
924 window_->layer()->SetColor(color);
927 gfx::Size RenderWidgetHostViewAura::GetVisibleViewportSize() const {
928 gfx::Rect requested_rect(GetRequestedRendererSize());
929 requested_rect.Inset(insets_);
930 return requested_rect.size();
933 void RenderWidgetHostViewAura::SetInsets(const gfx::Insets& insets) {
934 if (insets != insets_) {
935 insets_ = insets;
936 host_->WasResized();
940 void RenderWidgetHostViewAura::UpdateCursor(const WebCursor& cursor) {
941 current_cursor_ = cursor;
942 const gfx::Display display = gfx::Screen::GetScreenFor(window_)->
943 GetDisplayNearestWindow(window_);
944 current_cursor_.SetDisplayInfo(display);
945 UpdateCursorIfOverSelf();
948 void RenderWidgetHostViewAura::SetIsLoading(bool is_loading) {
949 is_loading_ = is_loading;
950 UpdateCursorIfOverSelf();
953 void RenderWidgetHostViewAura::TextInputTypeChanged(
954 ui::TextInputType type,
955 ui::TextInputMode input_mode,
956 bool can_compose_inline,
957 int flags) {
958 if (text_input_type_ != type ||
959 text_input_mode_ != input_mode ||
960 can_compose_inline_ != can_compose_inline ||
961 text_input_flags_ != flags) {
962 text_input_type_ = type;
963 text_input_mode_ = input_mode;
964 can_compose_inline_ = can_compose_inline;
965 text_input_flags_ = flags;
966 if (GetInputMethod())
967 GetInputMethod()->OnTextInputTypeChanged(this);
968 if (touch_editing_client_)
969 touch_editing_client_->OnTextInputTypeChanged(text_input_type_);
973 void RenderWidgetHostViewAura::OnTextInputStateChanged(
974 const ViewHostMsg_TextInputState_Params& params) {
975 text_input_flags_ = params.flags;
976 if (params.show_ime_if_needed && params.type != ui::TEXT_INPUT_TYPE_NONE) {
977 if (GetInputMethod())
978 GetInputMethod()->ShowImeIfNeeded();
982 void RenderWidgetHostViewAura::ImeCancelComposition() {
983 if (GetInputMethod())
984 GetInputMethod()->CancelComposition(this);
985 has_composition_text_ = false;
988 void RenderWidgetHostViewAura::ImeCompositionRangeChanged(
989 const gfx::Range& range,
990 const std::vector<gfx::Rect>& character_bounds) {
991 composition_character_bounds_ = character_bounds;
994 void RenderWidgetHostViewAura::RenderProcessGone(base::TerminationStatus status,
995 int error_code) {
996 UpdateCursorIfOverSelf();
997 Destroy();
1000 void RenderWidgetHostViewAura::Destroy() {
1001 // Beware, this function is not called on all destruction paths. It will
1002 // implicitly end up calling ~RenderWidgetHostViewAura though, so all
1003 // destruction/cleanup code should happen there, not here.
1004 in_shutdown_ = true;
1005 delete window_;
1008 void RenderWidgetHostViewAura::SetTooltipText(
1009 const base::string16& tooltip_text) {
1010 tooltip_ = tooltip_text;
1011 aura::Window* root_window = window_->GetRootWindow();
1012 aura::client::TooltipClient* tooltip_client =
1013 aura::client::GetTooltipClient(root_window);
1014 if (tooltip_client) {
1015 tooltip_client->UpdateTooltip(window_);
1016 // Content tooltips should be visible indefinitely.
1017 tooltip_client->SetTooltipShownTimeout(window_, 0);
1021 void RenderWidgetHostViewAura::SelectionChanged(const base::string16& text,
1022 size_t offset,
1023 const gfx::Range& range) {
1024 RenderWidgetHostViewBase::SelectionChanged(text, offset, range);
1026 #if defined(USE_X11) && !defined(OS_CHROMEOS)
1027 if (text.empty() || range.is_empty())
1028 return;
1029 size_t pos = range.GetMin() - offset;
1030 size_t n = range.length();
1032 DCHECK(pos + n <= text.length()) << "The text can not fully cover range.";
1033 if (pos >= text.length()) {
1034 NOTREACHED() << "The text can not cover range.";
1035 return;
1038 // Set the CLIPBOARD_TYPE_SELECTION to the ui::Clipboard.
1039 ui::ScopedClipboardWriter clipboard_writer(ui::CLIPBOARD_TYPE_SELECTION);
1040 clipboard_writer.WriteText(text.substr(pos, n));
1041 #endif // defined(USE_X11) && !defined(OS_CHROMEOS)
1044 gfx::Size RenderWidgetHostViewAura::GetRequestedRendererSize() const {
1045 return delegated_frame_host_->GetRequestedRendererSize();
1048 void RenderWidgetHostViewAura::SelectionBoundsChanged(
1049 const ViewHostMsg_SelectionBounds_Params& params) {
1050 ui::SelectionBound anchor_bound, focus_bound;
1051 anchor_bound.SetEdge(params.anchor_rect.origin(),
1052 params.anchor_rect.bottom_left());
1053 focus_bound.SetEdge(params.focus_rect.origin(),
1054 params.focus_rect.bottom_left());
1056 if (params.anchor_rect == params.focus_rect) {
1057 anchor_bound.set_type(ui::SelectionBound::CENTER);
1058 focus_bound.set_type(ui::SelectionBound::CENTER);
1059 } else {
1060 // Whether text is LTR at the anchor handle.
1061 bool anchor_LTR = params.anchor_dir == blink::WebTextDirectionLeftToRight;
1062 // Whether text is LTR at the focus handle.
1063 bool focus_LTR = params.focus_dir == blink::WebTextDirectionLeftToRight;
1065 if ((params.is_anchor_first && anchor_LTR) ||
1066 (!params.is_anchor_first && !anchor_LTR)) {
1067 anchor_bound.set_type(ui::SelectionBound::LEFT);
1068 } else {
1069 anchor_bound.set_type(ui::SelectionBound::RIGHT);
1071 if ((params.is_anchor_first && focus_LTR) ||
1072 (!params.is_anchor_first && !focus_LTR)) {
1073 focus_bound.set_type(ui::SelectionBound::RIGHT);
1074 } else {
1075 focus_bound.set_type(ui::SelectionBound::LEFT);
1079 if (anchor_bound == selection_anchor_ && focus_bound == selection_focus_)
1080 return;
1082 selection_anchor_ = anchor_bound;
1083 selection_focus_ = focus_bound;
1084 if (GetInputMethod())
1085 GetInputMethod()->OnCaretBoundsChanged(this);
1087 if (touch_editing_client_) {
1088 touch_editing_client_->OnSelectionOrCursorChanged(
1089 anchor_bound, focus_bound);
1093 void RenderWidgetHostViewAura::CopyFromCompositingSurface(
1094 const gfx::Rect& src_subrect,
1095 const gfx::Size& dst_size,
1096 ReadbackRequestCallback& callback,
1097 const SkColorType preferred_color_type) {
1098 delegated_frame_host_->CopyFromCompositingSurface(
1099 src_subrect, dst_size, callback, preferred_color_type);
1102 void RenderWidgetHostViewAura::CopyFromCompositingSurfaceToVideoFrame(
1103 const gfx::Rect& src_subrect,
1104 const scoped_refptr<media::VideoFrame>& target,
1105 const base::Callback<void(bool)>& callback) {
1106 delegated_frame_host_->CopyFromCompositingSurfaceToVideoFrame(
1107 src_subrect, target, callback);
1110 bool RenderWidgetHostViewAura::CanCopyToVideoFrame() const {
1111 return delegated_frame_host_->CanCopyToVideoFrame();
1114 bool RenderWidgetHostViewAura::CanSubscribeFrame() const {
1115 return delegated_frame_host_->CanSubscribeFrame();
1118 void RenderWidgetHostViewAura::BeginFrameSubscription(
1119 scoped_ptr<RenderWidgetHostViewFrameSubscriber> subscriber) {
1120 delegated_frame_host_->BeginFrameSubscription(subscriber.Pass());
1123 void RenderWidgetHostViewAura::EndFrameSubscription() {
1124 delegated_frame_host_->EndFrameSubscription();
1127 #if defined(OS_WIN)
1128 bool RenderWidgetHostViewAura::UsesNativeWindowFrame() const {
1129 return (legacy_render_widget_host_HWND_ != NULL);
1132 void RenderWidgetHostViewAura::UpdateConstrainedWindowRects(
1133 const std::vector<gfx::Rect>& rects) {
1134 // Check this before setting constrained_rects_, so that next time they're set
1135 // and we have a root window we don't early return.
1136 if (!window_->GetHost())
1137 return;
1139 if (rects == constrained_rects_)
1140 return;
1142 constrained_rects_ = rects;
1144 HWND parent = window_->GetHost()->GetAcceleratedWidget();
1145 CutoutRectsParams params;
1146 params.widget = this;
1147 params.cutout_rects = constrained_rects_;
1148 params.geometry = &plugin_window_moves_;
1149 LPARAM lparam = reinterpret_cast<LPARAM>(&params);
1150 EnumChildWindows(parent, SetCutoutRectsCallback, lparam);
1153 void RenderWidgetHostViewAura::UpdateMouseLockRegion() {
1154 // Clip the cursor if chrome is running on regular desktop.
1155 if (gfx::Screen::GetScreenFor(window_) == gfx::Screen::GetNativeScreen()) {
1156 RECT window_rect =
1157 gfx::win::DIPToScreenRect(window_->GetBoundsInScreen()).ToRECT();
1158 ::ClipCursor(&window_rect);
1162 void RenderWidgetHostViewAura::OnLegacyWindowDestroyed() {
1163 legacy_render_widget_host_HWND_ = NULL;
1164 legacy_window_destroyed_ = true;
1166 #endif
1168 void RenderWidgetHostViewAura::OnSwapCompositorFrame(
1169 uint32 output_surface_id,
1170 scoped_ptr<cc::CompositorFrame> frame) {
1171 TRACE_EVENT0("content", "RenderWidgetHostViewAura::OnSwapCompositorFrame");
1173 last_scroll_offset_ = frame->metadata.root_scroll_offset;
1174 if (frame->delegated_frame_data) {
1175 delegated_frame_host_->SwapDelegatedFrame(
1176 output_surface_id,
1177 frame->delegated_frame_data.Pass(),
1178 frame->metadata.device_scale_factor,
1179 frame->metadata.latency_info);
1180 return;
1183 if (frame->software_frame_data) {
1184 DLOG(ERROR) << "Unable to use software frame in aura";
1185 bad_message::ReceivedBadMessage(host_->GetProcess(),
1186 bad_message::RWHVA_SHARED_MEMORY);
1187 return;
1191 void RenderWidgetHostViewAura::DidStopFlinging() {
1192 if (touch_editing_client_)
1193 touch_editing_client_->DidStopFlinging();
1196 #if defined(OS_WIN)
1197 void RenderWidgetHostViewAura::SetParentNativeViewAccessible(
1198 gfx::NativeViewAccessible accessible_parent) {
1201 gfx::NativeViewId RenderWidgetHostViewAura::GetParentForWindowlessPlugin()
1202 const {
1203 if (legacy_render_widget_host_HWND_) {
1204 return reinterpret_cast<gfx::NativeViewId>(
1205 legacy_render_widget_host_HWND_->hwnd());
1207 return NULL;
1209 #endif
1211 bool RenderWidgetHostViewAura::HasAcceleratedSurface(
1212 const gfx::Size& desired_size) {
1213 // Aura doesn't use GetBackingStore for accelerated pages, so it doesn't
1214 // matter what is returned here as GetBackingStore is the only caller of this
1215 // method. TODO(jbates) implement this if other Aura code needs it.
1216 return false;
1219 void RenderWidgetHostViewAura::GetScreenInfo(WebScreenInfo* results) {
1220 GetScreenInfoForWindow(results, window_->GetRootWindow() ? window_ : NULL);
1223 gfx::Rect RenderWidgetHostViewAura::GetBoundsInRootWindow() {
1224 aura::Window* top_level = window_->GetToplevelWindow();
1225 gfx::Rect bounds(top_level->GetBoundsInScreen());
1227 #if defined(OS_WIN)
1228 // TODO(zturner,iyengar): This will break when we remove support for NPAPI and
1229 // remove the legacy hwnd, so a better fix will need to be decided when that
1230 // happens.
1231 if (UsesNativeWindowFrame()) {
1232 // aura::Window doesn't take into account non-client area of native windows
1233 // (e.g. HWNDs), so for that case ask Windows directly what the bounds are.
1234 aura::WindowTreeHost* host = top_level->GetHost();
1235 if (!host)
1236 return top_level->GetBoundsInScreen();
1237 RECT window_rect = {0};
1238 HWND hwnd = host->GetAcceleratedWidget();
1239 ::GetWindowRect(hwnd, &window_rect);
1240 bounds = gfx::Rect(window_rect);
1242 // Maximized windows are outdented from the work area by the frame thickness
1243 // even though this "frame" is not painted. This confuses code (and people)
1244 // that think of a maximized window as corresponding exactly to the work
1245 // area. Correct for this by subtracting the frame thickness back off.
1246 if (::IsZoomed(hwnd)) {
1247 bounds.Inset(GetSystemMetrics(SM_CXSIZEFRAME),
1248 GetSystemMetrics(SM_CYSIZEFRAME));
1250 bounds.Inset(GetSystemMetrics(SM_CXPADDEDBORDER),
1251 GetSystemMetrics(SM_CXPADDEDBORDER));
1255 bounds = gfx::win::ScreenToDIPRect(bounds);
1256 #endif
1258 return bounds;
1261 void RenderWidgetHostViewAura::WheelEventAck(
1262 const blink::WebMouseWheelEvent& event,
1263 InputEventAckState ack_result) {
1264 if (overscroll_controller_) {
1265 overscroll_controller_->ReceivedEventACK(
1266 event, (INPUT_EVENT_ACK_STATE_CONSUMED == ack_result));
1270 void RenderWidgetHostViewAura::GestureEventAck(
1271 const blink::WebGestureEvent& event,
1272 InputEventAckState ack_result) {
1273 if (touch_editing_client_)
1274 touch_editing_client_->GestureEventAck(event.type);
1276 if (overscroll_controller_) {
1277 overscroll_controller_->ReceivedEventACK(
1278 event, (INPUT_EVENT_ACK_STATE_CONSUMED == ack_result));
1282 void RenderWidgetHostViewAura::ProcessAckedTouchEvent(
1283 const TouchEventWithLatencyInfo& touch,
1284 InputEventAckState ack_result) {
1285 ScopedVector<ui::TouchEvent> events;
1286 aura::WindowTreeHost* host = window_->GetHost();
1287 // |host| is NULL during tests.
1288 if (!host)
1289 return;
1291 ui::EventResult result = (ack_result == INPUT_EVENT_ACK_STATE_CONSUMED)
1292 ? ui::ER_HANDLED
1293 : ui::ER_UNHANDLED;
1295 blink::WebTouchPoint::State required_state;
1296 switch (touch.event.type) {
1297 case blink::WebInputEvent::TouchStart:
1298 required_state = blink::WebTouchPoint::StatePressed;
1299 break;
1300 case blink::WebInputEvent::TouchEnd:
1301 required_state = blink::WebTouchPoint::StateReleased;
1302 break;
1303 case blink::WebInputEvent::TouchMove:
1304 required_state = blink::WebTouchPoint::StateMoved;
1305 break;
1306 case blink::WebInputEvent::TouchCancel:
1307 required_state = blink::WebTouchPoint::StateCancelled;
1308 break;
1309 default:
1310 required_state = blink::WebTouchPoint::StateUndefined;
1311 NOTREACHED();
1312 break;
1315 // Only send acks for one changed touch point.
1316 bool sent_ack = false;
1317 for (size_t i = 0; i < touch.event.touchesLength; ++i) {
1318 if (touch.event.touches[i].state == required_state) {
1319 DCHECK(!sent_ack);
1320 host->dispatcher()->ProcessedTouchEvent(touch.event.uniqueTouchEventId,
1321 window_, result);
1322 sent_ack = true;
1327 scoped_ptr<SyntheticGestureTarget>
1328 RenderWidgetHostViewAura::CreateSyntheticGestureTarget() {
1329 return scoped_ptr<SyntheticGestureTarget>(
1330 new SyntheticGestureTargetAura(host_));
1333 InputEventAckState RenderWidgetHostViewAura::FilterInputEvent(
1334 const blink::WebInputEvent& input_event) {
1335 bool consumed = false;
1336 if (input_event.type == WebInputEvent::GestureFlingStart) {
1337 const WebGestureEvent& gesture_event =
1338 static_cast<const WebGestureEvent&>(input_event);
1339 // Zero-velocity touchpad flings are an Aura-specific signal that the
1340 // touchpad scroll has ended, and should not be forwarded to the renderer.
1341 if (gesture_event.sourceDevice == blink::WebGestureDeviceTouchpad &&
1342 !gesture_event.data.flingStart.velocityX &&
1343 !gesture_event.data.flingStart.velocityY) {
1344 consumed = true;
1348 if (overscroll_controller_)
1349 consumed |= overscroll_controller_->WillHandleEvent(input_event);
1351 // Touch events should always propagate to the renderer.
1352 if (WebTouchEvent::isTouchEventType(input_event.type))
1353 return INPUT_EVENT_ACK_STATE_NOT_CONSUMED;
1355 // Reporting consumed for a fling suggests that there's now an *active* fling
1356 // that requires both animation and a fling-end notification. However, the
1357 // OverscrollController consumes a fling to stop its propagation; it doesn't
1358 // actually tick a fling animation. Report no consumer to convey this.
1359 if (consumed && input_event.type == blink::WebInputEvent::GestureFlingStart)
1360 return INPUT_EVENT_ACK_STATE_NO_CONSUMER_EXISTS;
1362 return consumed ? INPUT_EVENT_ACK_STATE_CONSUMED
1363 : INPUT_EVENT_ACK_STATE_NOT_CONSUMED;
1366 BrowserAccessibilityManager*
1367 RenderWidgetHostViewAura::CreateBrowserAccessibilityManager(
1368 BrowserAccessibilityDelegate* delegate) {
1369 BrowserAccessibilityManager* manager = NULL;
1370 #if defined(OS_WIN)
1371 manager = new BrowserAccessibilityManagerWin(
1372 BrowserAccessibilityManagerWin::GetEmptyDocument(), delegate);
1373 #else
1374 manager = BrowserAccessibilityManager::Create(
1375 BrowserAccessibilityManager::GetEmptyDocument(), delegate);
1376 #endif
1377 return manager;
1380 gfx::AcceleratedWidget
1381 RenderWidgetHostViewAura::AccessibilityGetAcceleratedWidget() {
1382 #if defined(OS_WIN)
1383 if (legacy_render_widget_host_HWND_)
1384 return legacy_render_widget_host_HWND_->hwnd();
1385 #endif
1386 return gfx::kNullAcceleratedWidget;
1389 gfx::NativeViewAccessible
1390 RenderWidgetHostViewAura::AccessibilityGetNativeViewAccessible() {
1391 #if defined(OS_WIN)
1392 if (legacy_render_widget_host_HWND_)
1393 return legacy_render_widget_host_HWND_->window_accessible();
1394 #endif
1395 return NULL;
1399 gfx::GLSurfaceHandle RenderWidgetHostViewAura::GetCompositingSurface() {
1400 return ImageTransportFactory::GetInstance()->GetSharedSurfaceHandle();
1403 void RenderWidgetHostViewAura::ShowDisambiguationPopup(
1404 const gfx::Rect& rect_pixels,
1405 const SkBitmap& zoomed_bitmap) {
1406 RenderViewHostDelegate* delegate = NULL;
1407 if (host_->IsRenderView())
1408 delegate = RenderViewHost::From(host_)->GetDelegate();
1409 // Suppress the link disambiguation popup if the virtual keyboard is currently
1410 // requested, as it doesn't interact well with the keyboard.
1411 if (delegate && delegate->IsVirtualKeyboardRequested())
1412 return;
1414 // |target_rect| is provided in pixels, not DIPs. So we convert it to DIPs
1415 // by scaling it by the inverse of the device scale factor.
1416 gfx::RectF screen_target_rect_f(rect_pixels);
1417 screen_target_rect_f.Scale(1.0f / current_device_scale_factor_);
1418 disambiguation_target_rect_ = gfx::ToEnclosingRect(screen_target_rect_f);
1420 float scale = static_cast<float>(zoomed_bitmap.width()) /
1421 static_cast<float>(rect_pixels.width());
1422 gfx::Size zoomed_size(gfx::ToCeiledSize(
1423 gfx::ScaleSize(disambiguation_target_rect_.size(), scale)));
1425 // Save of a copy of the |last_scroll_offset_| for comparison when the copy
1426 // callback fires, to ensure that we haven't scrolled.
1427 disambiguation_scroll_offset_ = last_scroll_offset_;
1429 CopyFromCompositingSurface(
1430 disambiguation_target_rect_,
1431 zoomed_size,
1432 base::Bind(&RenderWidgetHostViewAura::DisambiguationPopupRendered,
1433 weak_ptr_factory_.GetWeakPtr()),
1434 kN32_SkColorType);
1437 void RenderWidgetHostViewAura::DisambiguationPopupRendered(
1438 const SkBitmap& result,
1439 ReadbackResponse response) {
1440 if ((response != READBACK_SUCCESS) ||
1441 disambiguation_scroll_offset_ != last_scroll_offset_)
1442 return;
1444 // Use RenderViewHostDelegate to get to the WebContentsViewAura, which will
1445 // actually show the disambiguation popup.
1446 RenderViewHostDelegate* delegate = NULL;
1447 if (host_->IsRenderView())
1448 delegate = RenderViewHost::From(host_)->GetDelegate();
1449 RenderViewHostDelegateView* delegate_view = NULL;
1450 if (delegate) {
1451 delegate_view = delegate->GetDelegateView();
1452 if (delegate->IsVirtualKeyboardRequested())
1453 return;
1455 if (delegate_view) {
1456 delegate_view->ShowDisambiguationPopup(
1457 disambiguation_target_rect_,
1458 result,
1459 base::Bind(&RenderWidgetHostViewAura::ProcessDisambiguationGesture,
1460 weak_ptr_factory_.GetWeakPtr()),
1461 base::Bind(&RenderWidgetHostViewAura::ProcessDisambiguationMouse,
1462 weak_ptr_factory_.GetWeakPtr()));
1466 void RenderWidgetHostViewAura::HideDisambiguationPopup() {
1467 RenderViewHostDelegate* delegate = NULL;
1468 if (host_->IsRenderView())
1469 delegate = RenderViewHost::From(host_)->GetDelegate();
1470 RenderViewHostDelegateView* delegate_view = NULL;
1471 if (delegate)
1472 delegate_view = delegate->GetDelegateView();
1473 if (delegate_view)
1474 delegate_view->HideDisambiguationPopup();
1477 void RenderWidgetHostViewAura::ProcessDisambiguationGesture(
1478 ui::GestureEvent* event) {
1479 blink::WebGestureEvent web_gesture = content::MakeWebGestureEvent(*event);
1480 // If we fail to make a WebGestureEvent that is a Tap from the provided event,
1481 // don't forward it to Blink.
1482 if (web_gesture.type < blink::WebInputEvent::Type::GestureTap ||
1483 web_gesture.type > blink::WebInputEvent::Type::GestureTapCancel)
1484 return;
1486 host_->ForwardGestureEvent(web_gesture);
1489 void RenderWidgetHostViewAura::ProcessDisambiguationMouse(
1490 ui::MouseEvent* event) {
1491 blink::WebMouseEvent web_mouse = content::MakeWebMouseEvent(*event);
1492 host_->ForwardMouseEvent(web_mouse);
1495 bool RenderWidgetHostViewAura::LockMouse() {
1496 aura::Window* root_window = window_->GetRootWindow();
1497 if (!root_window)
1498 return false;
1500 if (mouse_locked_)
1501 return true;
1503 mouse_locked_ = true;
1504 #if !defined(OS_WIN)
1505 window_->SetCapture();
1506 #else
1507 UpdateMouseLockRegion();
1508 #endif
1509 aura::client::CursorClient* cursor_client =
1510 aura::client::GetCursorClient(root_window);
1511 if (cursor_client) {
1512 cursor_client->HideCursor();
1513 cursor_client->LockCursor();
1516 if (ShouldMoveToCenter()) {
1517 synthetic_move_sent_ = true;
1518 window_->MoveCursorTo(gfx::Rect(window_->bounds().size()).CenterPoint());
1520 tooltip_disabler_.reset(new aura::client::ScopedTooltipDisabler(root_window));
1521 return true;
1524 void RenderWidgetHostViewAura::UnlockMouse() {
1525 tooltip_disabler_.reset();
1527 aura::Window* root_window = window_->GetRootWindow();
1528 if (!mouse_locked_ || !root_window)
1529 return;
1531 mouse_locked_ = false;
1533 #if !defined(OS_WIN)
1534 window_->ReleaseCapture();
1535 #else
1536 ::ClipCursor(NULL);
1537 #endif
1538 window_->MoveCursorTo(unlocked_mouse_position_);
1539 aura::client::CursorClient* cursor_client =
1540 aura::client::GetCursorClient(root_window);
1541 if (cursor_client) {
1542 cursor_client->UnlockCursor();
1543 cursor_client->ShowCursor();
1546 host_->LostMouseLock();
1549 ////////////////////////////////////////////////////////////////////////////////
1550 // RenderWidgetHostViewAura, ui::TextInputClient implementation:
1551 void RenderWidgetHostViewAura::SetCompositionText(
1552 const ui::CompositionText& composition) {
1553 if (!host_)
1554 return;
1556 // TODO(suzhe): convert both renderer_host and renderer to use
1557 // ui::CompositionText.
1558 std::vector<blink::WebCompositionUnderline> underlines;
1559 underlines.reserve(composition.underlines.size());
1560 for (std::vector<ui::CompositionUnderline>::const_iterator it =
1561 composition.underlines.begin();
1562 it != composition.underlines.end(); ++it) {
1563 underlines.push_back(
1564 blink::WebCompositionUnderline(static_cast<unsigned>(it->start_offset),
1565 static_cast<unsigned>(it->end_offset),
1566 it->color,
1567 it->thick,
1568 it->background_color));
1571 // TODO(suzhe): due to a bug of webkit, we can't use selection range with
1572 // composition string. See: https://bugs.webkit.org/show_bug.cgi?id=37788
1573 host_->ImeSetComposition(composition.text, underlines,
1574 composition.selection.end(),
1575 composition.selection.end());
1577 has_composition_text_ = !composition.text.empty();
1580 void RenderWidgetHostViewAura::ConfirmCompositionText() {
1581 if (host_ && has_composition_text_) {
1582 host_->ImeConfirmComposition(base::string16(), gfx::Range::InvalidRange(),
1583 false);
1585 has_composition_text_ = false;
1588 void RenderWidgetHostViewAura::ClearCompositionText() {
1589 if (host_ && has_composition_text_)
1590 host_->ImeCancelComposition();
1591 has_composition_text_ = false;
1594 void RenderWidgetHostViewAura::InsertText(const base::string16& text) {
1595 DCHECK(text_input_type_ != ui::TEXT_INPUT_TYPE_NONE);
1596 if (host_)
1597 host_->ImeConfirmComposition(text, gfx::Range::InvalidRange(), false);
1598 has_composition_text_ = false;
1601 void RenderWidgetHostViewAura::InsertChar(base::char16 ch, int flags) {
1602 if (popup_child_host_view_ && popup_child_host_view_->NeedsInputGrab()) {
1603 popup_child_host_view_->InsertChar(ch, flags);
1604 return;
1607 // Ignore character messages for VKEY_RETURN sent on CTRL+M. crbug.com/315547
1608 if (host_ && (accept_return_character_ || ch != ui::VKEY_RETURN)) {
1609 double now = ui::EventTimeForNow().InSecondsF();
1610 // Send a blink::WebInputEvent::Char event to |host_|.
1611 NativeWebKeyboardEvent webkit_event(ui::ET_KEY_PRESSED,
1612 true /* is_char */,
1614 flags,
1615 now);
1616 ForwardKeyboardEvent(webkit_event);
1620 ui::TextInputType RenderWidgetHostViewAura::GetTextInputType() const {
1621 return text_input_type_;
1624 ui::TextInputMode RenderWidgetHostViewAura::GetTextInputMode() const {
1625 return text_input_mode_;
1628 int RenderWidgetHostViewAura::GetTextInputFlags() const {
1629 return text_input_flags_;
1632 bool RenderWidgetHostViewAura::CanComposeInline() const {
1633 return can_compose_inline_;
1636 gfx::Rect RenderWidgetHostViewAura::ConvertRectToScreen(
1637 const gfx::Rect& rect) const {
1638 gfx::Point origin = rect.origin();
1639 gfx::Point end = gfx::Point(rect.right(), rect.bottom());
1641 aura::Window* root_window = window_->GetRootWindow();
1642 if (!root_window)
1643 return rect;
1644 aura::client::ScreenPositionClient* screen_position_client =
1645 aura::client::GetScreenPositionClient(root_window);
1646 if (!screen_position_client)
1647 return rect;
1648 screen_position_client->ConvertPointToScreen(window_, &origin);
1649 screen_position_client->ConvertPointToScreen(window_, &end);
1650 return gfx::Rect(origin.x(),
1651 origin.y(),
1652 end.x() - origin.x(),
1653 end.y() - origin.y());
1656 gfx::Rect RenderWidgetHostViewAura::ConvertRectFromScreen(
1657 const gfx::Rect& rect) const {
1658 gfx::Point origin = rect.origin();
1659 gfx::Point end = gfx::Point(rect.right(), rect.bottom());
1661 aura::Window* root_window = window_->GetRootWindow();
1662 if (root_window) {
1663 aura::client::ScreenPositionClient* screen_position_client =
1664 aura::client::GetScreenPositionClient(root_window);
1665 screen_position_client->ConvertPointFromScreen(window_, &origin);
1666 screen_position_client->ConvertPointFromScreen(window_, &end);
1667 return gfx::Rect(origin.x(),
1668 origin.y(),
1669 end.x() - origin.x(),
1670 end.y() - origin.y());
1673 return rect;
1676 gfx::Rect RenderWidgetHostViewAura::GetCaretBounds() const {
1677 gfx::Rect rect =
1678 ui::RectBetweenSelectionBounds(selection_anchor_, selection_focus_);
1679 return ConvertRectToScreen(rect);
1682 bool RenderWidgetHostViewAura::GetCompositionCharacterBounds(
1683 uint32 index,
1684 gfx::Rect* rect) const {
1685 DCHECK(rect);
1686 if (index >= composition_character_bounds_.size())
1687 return false;
1688 *rect = ConvertRectToScreen(composition_character_bounds_[index]);
1689 return true;
1692 bool RenderWidgetHostViewAura::HasCompositionText() const {
1693 return has_composition_text_;
1696 bool RenderWidgetHostViewAura::GetTextRange(gfx::Range* range) const {
1697 range->set_start(selection_text_offset_);
1698 range->set_end(selection_text_offset_ + selection_text_.length());
1699 return true;
1702 bool RenderWidgetHostViewAura::GetCompositionTextRange(
1703 gfx::Range* range) const {
1704 // TODO(suzhe): implement this method when fixing http://crbug.com/55130.
1705 NOTIMPLEMENTED();
1706 return false;
1709 bool RenderWidgetHostViewAura::GetSelectionRange(gfx::Range* range) const {
1710 range->set_start(selection_range_.start());
1711 range->set_end(selection_range_.end());
1712 return true;
1715 bool RenderWidgetHostViewAura::SetSelectionRange(const gfx::Range& range) {
1716 // TODO(suzhe): implement this method when fixing http://crbug.com/55130.
1717 NOTIMPLEMENTED();
1718 return false;
1721 bool RenderWidgetHostViewAura::DeleteRange(const gfx::Range& range) {
1722 // TODO(suzhe): implement this method when fixing http://crbug.com/55130.
1723 NOTIMPLEMENTED();
1724 return false;
1727 bool RenderWidgetHostViewAura::GetTextFromRange(
1728 const gfx::Range& range,
1729 base::string16* text) const {
1730 gfx::Range selection_text_range(selection_text_offset_,
1731 selection_text_offset_ + selection_text_.length());
1733 if (!selection_text_range.Contains(range)) {
1734 text->clear();
1735 return false;
1737 if (selection_text_range.EqualsIgnoringDirection(range)) {
1738 // Avoid calling substr whose performance is low.
1739 *text = selection_text_;
1740 } else {
1741 *text = selection_text_.substr(
1742 range.GetMin() - selection_text_offset_,
1743 range.length());
1745 return true;
1748 void RenderWidgetHostViewAura::OnInputMethodChanged() {
1749 if (!host_)
1750 return;
1752 if (GetInputMethod())
1753 host_->SetInputMethodActive(GetInputMethod()->IsActive());
1755 // TODO(suzhe): implement the newly added “locale” property of HTML DOM
1756 // TextEvent.
1759 bool RenderWidgetHostViewAura::ChangeTextDirectionAndLayoutAlignment(
1760 base::i18n::TextDirection direction) {
1761 if (!host_)
1762 return false;
1763 host_->UpdateTextDirection(
1764 direction == base::i18n::RIGHT_TO_LEFT ?
1765 blink::WebTextDirectionRightToLeft :
1766 blink::WebTextDirectionLeftToRight);
1767 host_->NotifyTextDirection();
1768 return true;
1771 void RenderWidgetHostViewAura::ExtendSelectionAndDelete(
1772 size_t before, size_t after) {
1773 RenderFrameHostImpl* rfh = GetFocusedFrame();
1774 if (rfh)
1775 rfh->ExtendSelectionAndDelete(before, after);
1778 void RenderWidgetHostViewAura::EnsureCaretInRect(const gfx::Rect& rect) {
1779 gfx::Rect intersected_rect(
1780 gfx::IntersectRects(rect, window_->GetBoundsInScreen()));
1782 if (intersected_rect.IsEmpty())
1783 return;
1785 host_->ScrollFocusedEditableNodeIntoRect(
1786 ConvertRectFromScreen(intersected_rect));
1789 bool RenderWidgetHostViewAura::IsEditCommandEnabled(int command_id) {
1790 return false;
1793 void RenderWidgetHostViewAura::SetEditCommandForNextKeyEvent(int command_id) {
1796 ////////////////////////////////////////////////////////////////////////////////
1797 // RenderWidgetHostViewAura, gfx::DisplayObserver implementation:
1799 void RenderWidgetHostViewAura::OnDisplayAdded(
1800 const gfx::Display& new_display) {
1803 void RenderWidgetHostViewAura::OnDisplayRemoved(
1804 const gfx::Display& old_display) {
1807 void RenderWidgetHostViewAura::OnDisplayMetricsChanged(
1808 const gfx::Display& display, uint32_t metrics) {
1809 // The screen info should be updated regardless of the metric change.
1810 gfx::Screen* screen = gfx::Screen::GetScreenFor(window_);
1811 if (display.id() == screen->GetDisplayNearestWindow(window_).id()) {
1812 UpdateScreenInfo(window_);
1813 current_cursor_.SetDisplayInfo(display);
1814 UpdateCursorIfOverSelf();
1818 ////////////////////////////////////////////////////////////////////////////////
1819 // RenderWidgetHostViewAura, aura::WindowDelegate implementation:
1821 gfx::Size RenderWidgetHostViewAura::GetMinimumSize() const {
1822 return gfx::Size();
1825 gfx::Size RenderWidgetHostViewAura::GetMaximumSize() const {
1826 return gfx::Size();
1829 void RenderWidgetHostViewAura::OnBoundsChanged(const gfx::Rect& old_bounds,
1830 const gfx::Rect& new_bounds) {
1831 base::AutoReset<bool> in_bounds_changed(&in_bounds_changed_, true);
1832 // We care about this whenever RenderWidgetHostViewAura is not owned by a
1833 // WebContentsViewAura since changes to the Window's bounds need to be
1834 // messaged to the renderer. WebContentsViewAura invokes SetSize() or
1835 // SetBounds() itself. No matter how we got here, any redundant calls are
1836 // harmless.
1837 SetSize(new_bounds.size());
1839 if (GetInputMethod())
1840 GetInputMethod()->OnCaretBoundsChanged(this);
1843 gfx::NativeCursor RenderWidgetHostViewAura::GetCursor(const gfx::Point& point) {
1844 if (mouse_locked_)
1845 return ui::kCursorNone;
1846 return current_cursor_.GetNativeCursor();
1849 int RenderWidgetHostViewAura::GetNonClientComponent(
1850 const gfx::Point& point) const {
1851 return HTCLIENT;
1854 bool RenderWidgetHostViewAura::ShouldDescendIntoChildForEventHandling(
1855 aura::Window* child,
1856 const gfx::Point& location) {
1857 return true;
1860 bool RenderWidgetHostViewAura::CanFocus() {
1861 return popup_type_ == blink::WebPopupTypeNone;
1864 void RenderWidgetHostViewAura::OnCaptureLost() {
1865 host_->LostCapture();
1866 if (touch_editing_client_)
1867 touch_editing_client_->EndTouchEditing(false);
1870 void RenderWidgetHostViewAura::OnPaint(const ui::PaintContext& context) {
1871 NOTREACHED();
1874 void RenderWidgetHostViewAura::OnDeviceScaleFactorChanged(
1875 float device_scale_factor) {
1876 if (!host_ || !window_->GetRootWindow())
1877 return;
1879 UpdateScreenInfo(window_);
1881 const gfx::Display display = gfx::Screen::GetScreenFor(window_)->
1882 GetDisplayNearestWindow(window_);
1883 DCHECK_EQ(device_scale_factor, display.device_scale_factor());
1884 current_cursor_.SetDisplayInfo(display);
1885 SnapToPhysicalPixelBoundary();
1888 void RenderWidgetHostViewAura::OnWindowDestroying(aura::Window* window) {
1889 #if defined(OS_WIN)
1890 HWND parent = NULL;
1891 // If the tab was hidden and it's closed, host_->is_hidden would have been
1892 // reset to false in RenderWidgetHostImpl::RendererExited.
1893 if (!window_->GetRootWindow() || host_->is_hidden()) {
1894 parent = ui::GetHiddenWindow();
1895 } else {
1896 parent = window_->GetHost()->GetAcceleratedWidget();
1898 LPARAM lparam = reinterpret_cast<LPARAM>(this);
1899 EnumChildWindows(parent, WindowDestroyingCallback, lparam);
1901 // The LegacyRenderWidgetHostHWND instance is destroyed when its window is
1902 // destroyed. Normally we control when that happens via the Destroy call
1903 // in the dtor. However there may be cases where the window is destroyed
1904 // by Windows, i.e. the parent window is destroyed before the
1905 // RenderWidgetHostViewAura instance goes away etc. To avoid that we
1906 // destroy the LegacyRenderWidgetHostHWND instance here.
1907 if (legacy_render_widget_host_HWND_) {
1908 legacy_render_widget_host_HWND_->set_host(NULL);
1909 legacy_render_widget_host_HWND_->Destroy();
1910 // The Destroy call above will delete the LegacyRenderWidgetHostHWND
1911 // instance.
1912 legacy_render_widget_host_HWND_ = NULL;
1914 #endif
1916 // Make sure that the input method no longer references to this object before
1917 // this object is removed from the root window (i.e. this object loses access
1918 // to the input method).
1919 ui::InputMethod* input_method = GetInputMethod();
1920 if (input_method)
1921 input_method->DetachTextInputClient(this);
1923 if (overscroll_controller_)
1924 overscroll_controller_->Reset();
1927 void RenderWidgetHostViewAura::OnWindowDestroyed(aura::Window* window) {
1928 // Ask the RWH to drop reference to us.
1929 if (!is_guest_view_hack_)
1930 host_->ViewDestroyed();
1932 delete this;
1935 void RenderWidgetHostViewAura::OnWindowTargetVisibilityChanged(bool visible) {
1938 bool RenderWidgetHostViewAura::HasHitTestMask() const {
1939 return false;
1942 void RenderWidgetHostViewAura::GetHitTestMask(gfx::Path* mask) const {
1945 ////////////////////////////////////////////////////////////////////////////////
1946 // RenderWidgetHostViewAura, ui::EventHandler implementation:
1948 void RenderWidgetHostViewAura::OnKeyEvent(ui::KeyEvent* event) {
1949 TRACE_EVENT0("input", "RenderWidgetHostViewAura::OnKeyEvent");
1950 if (touch_editing_client_ && touch_editing_client_->HandleInputEvent(event))
1951 return;
1953 if (popup_child_host_view_ && popup_child_host_view_->NeedsInputGrab()) {
1954 popup_child_host_view_->OnKeyEvent(event);
1955 if (event->handled())
1956 return;
1959 // We need to handle the Escape key for Pepper Flash.
1960 if (is_fullscreen_ && event->key_code() == ui::VKEY_ESCAPE) {
1961 // Focus the window we were created from.
1962 if (host_tracker_.get() && !host_tracker_->windows().empty()) {
1963 aura::Window* host = *(host_tracker_->windows().begin());
1964 aura::client::FocusClient* client = aura::client::GetFocusClient(host);
1965 if (client) {
1966 // Calling host->Focus() may delete |this|. We create a local observer
1967 // for that. In that case we exit without further access to any members.
1968 aura::WindowTracker tracker;
1969 aura::Window* window = window_;
1970 tracker.Add(window);
1971 host->Focus();
1972 if (!tracker.Contains(window)) {
1973 event->SetHandled();
1974 return;
1978 Shutdown();
1979 } else {
1980 if (event->key_code() == ui::VKEY_RETURN) {
1981 // Do not forward return key release events if no press event was handled.
1982 if (event->type() == ui::ET_KEY_RELEASED && !accept_return_character_)
1983 return;
1984 // Accept return key character events between press and release events.
1985 accept_return_character_ = event->type() == ui::ET_KEY_PRESSED;
1988 // We don't have to communicate with an input method here.
1989 NativeWebKeyboardEvent webkit_event(*event);
1990 ForwardKeyboardEvent(webkit_event);
1992 event->SetHandled();
1995 void RenderWidgetHostViewAura::OnMouseEvent(ui::MouseEvent* event) {
1996 TRACE_EVENT0("input", "RenderWidgetHostViewAura::OnMouseEvent");
1998 if (touch_editing_client_ && touch_editing_client_->HandleInputEvent(event))
1999 return;
2001 if (mouse_locked_) {
2002 aura::client::CursorClient* cursor_client =
2003 aura::client::GetCursorClient(window_->GetRootWindow());
2004 DCHECK(!cursor_client || !cursor_client->IsCursorVisible());
2006 if (event->type() == ui::ET_MOUSEWHEEL) {
2007 blink::WebMouseWheelEvent mouse_wheel_event =
2008 MakeWebMouseWheelEvent(static_cast<ui::MouseWheelEvent&>(*event));
2009 if (mouse_wheel_event.deltaX != 0 || mouse_wheel_event.deltaY != 0)
2010 host_->ForwardWheelEvent(mouse_wheel_event);
2011 return;
2014 gfx::Point center(gfx::Rect(window_->bounds().size()).CenterPoint());
2016 // If we receive non client mouse messages while we are in the locked state
2017 // it probably means that the mouse left the borders of our window and
2018 // needs to be moved back to the center.
2019 if (event->flags() & ui::EF_IS_NON_CLIENT) {
2020 synthetic_move_sent_ = true;
2021 window_->MoveCursorTo(center);
2022 return;
2025 blink::WebMouseEvent mouse_event = MakeWebMouseEvent(*event);
2027 bool is_move_to_center_event = (event->type() == ui::ET_MOUSE_MOVED ||
2028 event->type() == ui::ET_MOUSE_DRAGGED) &&
2029 mouse_event.x == center.x() && mouse_event.y == center.y();
2031 // For fractional scale factors, the conversion from pixels to dip and
2032 // vice versa could result in off by 1 or 2 errors which hurts us because
2033 // we want to avoid sending the artificial move to center event to the
2034 // renderer. Sending the move to center to the renderer cause the cursor
2035 // to bounce around the center of the screen leading to the lock operation
2036 // not working correctly.
2037 // Workaround is to treat a mouse move or drag event off by at most 2 px
2038 // from the center as a move to center event.
2039 if (synthetic_move_sent_ &&
2040 IsFractionalScaleFactor(current_device_scale_factor_)) {
2041 if (event->type() == ui::ET_MOUSE_MOVED ||
2042 event->type() == ui::ET_MOUSE_DRAGGED) {
2043 if ((abs(mouse_event.x - center.x()) <= 2) &&
2044 (abs(mouse_event.y - center.y()) <= 2)) {
2045 is_move_to_center_event = true;
2050 ModifyEventMovementAndCoords(&mouse_event);
2052 bool should_not_forward = is_move_to_center_event && synthetic_move_sent_;
2053 if (should_not_forward) {
2054 synthetic_move_sent_ = false;
2055 } else {
2056 // Check if the mouse has reached the border and needs to be centered.
2057 if (ShouldMoveToCenter()) {
2058 synthetic_move_sent_ = true;
2059 window_->MoveCursorTo(center);
2061 bool is_selection_popup = popup_child_host_view_ &&
2062 popup_child_host_view_->NeedsInputGrab();
2063 // Forward event to renderer.
2064 if (CanRendererHandleEvent(event, mouse_locked_, is_selection_popup) &&
2065 !(event->flags() & ui::EF_FROM_TOUCH)) {
2066 host_->ForwardMouseEvent(mouse_event);
2067 // Ensure that we get keyboard focus on mouse down as a plugin window
2068 // may have grabbed keyboard focus.
2069 if (event->type() == ui::ET_MOUSE_PRESSED)
2070 SetKeyboardFocus();
2073 return;
2076 // As the overscroll is handled during scroll events from the trackpad, the
2077 // RWHVA window is transformed by the overscroll controller. This transform
2078 // triggers a synthetic mouse-move event to be generated (by the aura
2079 // RootWindow). But this event interferes with the overscroll gesture. So,
2080 // ignore such synthetic mouse-move events if an overscroll gesture is in
2081 // progress.
2082 if (overscroll_controller_ &&
2083 overscroll_controller_->overscroll_mode() != OVERSCROLL_NONE &&
2084 event->flags() & ui::EF_IS_SYNTHESIZED &&
2085 (event->type() == ui::ET_MOUSE_ENTERED ||
2086 event->type() == ui::ET_MOUSE_EXITED ||
2087 event->type() == ui::ET_MOUSE_MOVED)) {
2088 event->StopPropagation();
2089 return;
2092 if (event->type() == ui::ET_MOUSEWHEEL) {
2093 #if defined(OS_WIN)
2094 // We get mouse wheel/scroll messages even if we are not in the foreground.
2095 // So here we check if we have any owned popup windows in the foreground and
2096 // dismiss them.
2097 aura::WindowTreeHost* host = window_->GetHost();
2098 if (host) {
2099 HWND parent = host->GetAcceleratedWidget();
2100 HWND toplevel_hwnd = ::GetAncestor(parent, GA_ROOT);
2101 EnumThreadWindows(GetCurrentThreadId(),
2102 DismissOwnedPopups,
2103 reinterpret_cast<LPARAM>(toplevel_hwnd));
2105 #endif
2106 // The Disambiguation popup does not parent itself from this window, so we
2107 // manually dismiss it.
2108 HideDisambiguationPopup();
2110 blink::WebMouseWheelEvent mouse_wheel_event =
2111 MakeWebMouseWheelEvent(static_cast<ui::MouseWheelEvent&>(*event));
2112 if (mouse_wheel_event.deltaX != 0 || mouse_wheel_event.deltaY != 0)
2113 host_->ForwardWheelEvent(mouse_wheel_event);
2114 } else {
2115 bool is_selection_popup = popup_child_host_view_ &&
2116 popup_child_host_view_->NeedsInputGrab();
2117 if (CanRendererHandleEvent(event, mouse_locked_, is_selection_popup) &&
2118 !(event->flags() & ui::EF_FROM_TOUCH)) {
2119 // Confirm existing composition text on mouse press, to make sure
2120 // the input caret won't be moved with an ongoing composition text.
2121 if (event->type() == ui::ET_MOUSE_PRESSED)
2122 FinishImeCompositionSession();
2124 blink::WebMouseEvent mouse_event = MakeWebMouseEvent(*event);
2125 ModifyEventMovementAndCoords(&mouse_event);
2126 host_->ForwardMouseEvent(mouse_event);
2127 // Ensure that we get keyboard focus on mouse down as a plugin window may
2128 // have grabbed keyboard focus.
2129 if (event->type() == ui::ET_MOUSE_PRESSED)
2130 SetKeyboardFocus();
2134 switch (event->type()) {
2135 case ui::ET_MOUSE_PRESSED:
2136 window_->SetCapture();
2137 break;
2138 case ui::ET_MOUSE_RELEASED:
2139 if (!NeedsMouseCapture())
2140 window_->ReleaseCapture();
2141 break;
2142 default:
2143 break;
2146 // Needed to propagate mouse event to |window_->parent()->delegate()|, but
2147 // note that it might be something other than a WebContentsViewAura instance.
2148 // TODO(pkotwicz): Find a better way of doing this.
2149 // In fullscreen mode which is typically used by flash, don't forward
2150 // the mouse events to the parent. The renderer and the plugin process
2151 // handle these events.
2152 if (!is_fullscreen_ && window_->parent() && window_->parent()->delegate() &&
2153 !(event->flags() & ui::EF_FROM_TOUCH)) {
2154 event->ConvertLocationToTarget(window_, window_->parent());
2155 window_->parent()->delegate()->OnMouseEvent(event);
2158 if (!IsXButtonUpEvent(event))
2159 event->SetHandled();
2162 void RenderWidgetHostViewAura::OnScrollEvent(ui::ScrollEvent* event) {
2163 TRACE_EVENT0("input", "RenderWidgetHostViewAura::OnScrollEvent");
2164 if (touch_editing_client_ && touch_editing_client_->HandleInputEvent(event))
2165 return;
2167 if (event->type() == ui::ET_SCROLL) {
2168 #if !defined(OS_WIN)
2169 // TODO(ananta)
2170 // Investigate if this is true for Windows 8 Metro ASH as well.
2171 if (event->finger_count() != 2)
2172 return;
2173 #endif
2174 blink::WebGestureEvent gesture_event =
2175 MakeWebGestureEventFlingCancel();
2176 host_->ForwardGestureEvent(gesture_event);
2177 blink::WebMouseWheelEvent mouse_wheel_event =
2178 MakeWebMouseWheelEvent(*event);
2179 host_->ForwardWheelEvent(mouse_wheel_event);
2180 RecordAction(base::UserMetricsAction("TrackpadScroll"));
2181 } else if (event->type() == ui::ET_SCROLL_FLING_START ||
2182 event->type() == ui::ET_SCROLL_FLING_CANCEL) {
2183 blink::WebGestureEvent gesture_event = MakeWebGestureEvent(*event);
2184 host_->ForwardGestureEvent(gesture_event);
2185 if (event->type() == ui::ET_SCROLL_FLING_START)
2186 RecordAction(base::UserMetricsAction("TrackpadScrollFling"));
2189 event->SetHandled();
2192 void RenderWidgetHostViewAura::OnTouchEvent(ui::TouchEvent* event) {
2193 TRACE_EVENT0("input", "RenderWidgetHostViewAura::OnTouchEvent");
2194 if (touch_editing_client_ && touch_editing_client_->HandleInputEvent(event))
2195 return;
2197 // Update the touch event first.
2198 if (!pointer_state_.OnTouch(*event)) {
2199 event->StopPropagation();
2200 return;
2203 blink::WebTouchEvent touch_event = ui::CreateWebTouchEventFromMotionEvent(
2204 pointer_state_, event->may_cause_scrolling());
2205 pointer_state_.CleanupRemovedTouchPoints(*event);
2207 // It is important to always mark events as being handled asynchronously when
2208 // they are forwarded. This ensures that the current event does not get
2209 // processed by the gesture recognizer before events currently awaiting
2210 // dispatch in the touch queue.
2211 event->DisableSynchronousHandling();
2213 // Set unchanged touch point to StateStationary for touchmove and
2214 // touchcancel to make sure only send one ack per WebTouchEvent.
2215 MarkUnchangedTouchPointsAsStationary(&touch_event, event->touch_id());
2216 host_->ForwardTouchEventWithLatencyInfo(touch_event, *event->latency());
2219 void RenderWidgetHostViewAura::OnGestureEvent(ui::GestureEvent* event) {
2220 TRACE_EVENT0("input", "RenderWidgetHostViewAura::OnGestureEvent");
2221 if ((event->type() == ui::ET_GESTURE_PINCH_BEGIN ||
2222 event->type() == ui::ET_GESTURE_PINCH_UPDATE ||
2223 event->type() == ui::ET_GESTURE_PINCH_END) && !pinch_zoom_enabled_) {
2224 event->SetHandled();
2225 return;
2228 if (touch_editing_client_ && touch_editing_client_->HandleInputEvent(event))
2229 return;
2231 // Confirm existing composition text on TAP gesture, to make sure the input
2232 // caret won't be moved with an ongoing composition text.
2233 if (event->type() == ui::ET_GESTURE_TAP)
2234 FinishImeCompositionSession();
2236 blink::WebGestureEvent gesture = MakeWebGestureEvent(*event);
2237 if (event->type() == ui::ET_GESTURE_TAP_DOWN) {
2238 // Webkit does not stop a fling-scroll on tap-down. So explicitly send an
2239 // event to stop any in-progress flings.
2240 blink::WebGestureEvent fling_cancel = gesture;
2241 fling_cancel.type = blink::WebInputEvent::GestureFlingCancel;
2242 fling_cancel.sourceDevice = blink::WebGestureDeviceTouchscreen;
2243 host_->ForwardGestureEvent(fling_cancel);
2246 if (gesture.type != blink::WebInputEvent::Undefined) {
2247 host_->ForwardGestureEventWithLatencyInfo(gesture, *event->latency());
2249 if (event->type() == ui::ET_GESTURE_SCROLL_BEGIN ||
2250 event->type() == ui::ET_GESTURE_SCROLL_UPDATE ||
2251 event->type() == ui::ET_GESTURE_SCROLL_END) {
2252 RecordAction(base::UserMetricsAction("TouchscreenScroll"));
2253 } else if (event->type() == ui::ET_SCROLL_FLING_START) {
2254 RecordAction(base::UserMetricsAction("TouchscreenScrollFling"));
2258 // If a gesture is not processed by the webpage, then WebKit processes it
2259 // (e.g. generates synthetic mouse events).
2260 event->SetHandled();
2263 ////////////////////////////////////////////////////////////////////////////////
2264 // RenderWidgetHostViewAura, aura::client::ActivationDelegate implementation:
2266 bool RenderWidgetHostViewAura::ShouldActivate() const {
2267 aura::WindowTreeHost* host = window_->GetHost();
2268 if (!host)
2269 return true;
2270 const ui::Event* event = host->dispatcher()->current_event();
2271 if (!event)
2272 return true;
2273 return is_fullscreen_;
2276 ////////////////////////////////////////////////////////////////////////////////
2277 // RenderWidgetHostViewAura, aura::client::CursorClientObserver implementation:
2279 void RenderWidgetHostViewAura::OnCursorVisibilityChanged(bool is_visible) {
2280 NotifyRendererOfCursorVisibilityState(is_visible);
2283 ////////////////////////////////////////////////////////////////////////////////
2284 // RenderWidgetHostViewAura, aura::client::FocusChangeObserver implementation:
2286 void RenderWidgetHostViewAura::OnWindowFocused(aura::Window* gained_focus,
2287 aura::Window* lost_focus) {
2288 DCHECK(window_ == gained_focus || window_ == lost_focus);
2289 if (window_ == gained_focus) {
2290 // We need to honor input bypass if the associated tab is does not want
2291 // input. This gives the current focused window a chance to be the text
2292 // input client and handle events.
2293 if (host_->ignore_input_events())
2294 return;
2296 host_->GotFocus();
2297 host_->SetActive(true);
2299 ui::InputMethod* input_method = GetInputMethod();
2300 if (input_method) {
2301 // Ask the system-wide IME to send all TextInputClient messages to |this|
2302 // object.
2303 input_method->SetFocusedTextInputClient(this);
2304 host_->SetInputMethodActive(input_method->IsActive());
2306 // Often the application can set focus to the view in response to a key
2307 // down. However the following char event shouldn't be sent to the web
2308 // page.
2309 host_->SuppressNextCharEvents();
2310 } else {
2311 host_->SetInputMethodActive(false);
2314 BrowserAccessibilityManager* manager =
2315 host_->GetRootBrowserAccessibilityManager();
2316 if (manager)
2317 manager->OnWindowFocused();
2318 } else if (window_ == lost_focus) {
2319 host_->SetActive(false);
2320 host_->Blur();
2322 DetachFromInputMethod();
2323 host_->SetInputMethodActive(false);
2325 if (touch_editing_client_)
2326 touch_editing_client_->EndTouchEditing(false);
2328 if (overscroll_controller_)
2329 overscroll_controller_->Cancel();
2331 BrowserAccessibilityManager* manager =
2332 host_->GetRootBrowserAccessibilityManager();
2333 if (manager)
2334 manager->OnWindowBlurred();
2336 // If we lose the focus while fullscreen, close the window; Pepper Flash
2337 // won't do it for us (unlike NPAPI Flash). However, we do not close the
2338 // window if we lose the focus to a window on another display.
2339 gfx::Screen* screen = gfx::Screen::GetScreenFor(window_);
2340 bool focusing_other_display =
2341 gained_focus && screen->GetNumDisplays() > 1 &&
2342 (screen->GetDisplayNearestWindow(window_).id() !=
2343 screen->GetDisplayNearestWindow(gained_focus).id());
2344 if (is_fullscreen_ && !in_shutdown_ && !focusing_other_display) {
2345 #if defined(OS_WIN)
2346 // On Windows, if we are switching to a non Aura Window on a different
2347 // screen we should not close the fullscreen window.
2348 if (!gained_focus) {
2349 POINT point = {0};
2350 ::GetCursorPos(&point);
2351 if (screen->GetDisplayNearestWindow(window_).id() !=
2352 screen->GetDisplayNearestPoint(gfx::Point(point)).id())
2353 return;
2355 #endif
2356 Shutdown();
2357 return;
2360 // Close the child popup window if we lose focus (e.g. due to a JS alert or
2361 // system modal dialog). This is particularly important if
2362 // |popup_child_host_view_| has mouse capture.
2363 if (popup_child_host_view_)
2364 popup_child_host_view_->Shutdown();
2368 ////////////////////////////////////////////////////////////////////////////////
2369 // RenderWidgetHostViewAura, aura::WindowTreeHostObserver implementation:
2371 void RenderWidgetHostViewAura::OnHostMoved(const aura::WindowTreeHost* host,
2372 const gfx::Point& new_origin) {
2373 TRACE_EVENT1("ui", "RenderWidgetHostViewAura::OnHostMoved",
2374 "new_origin", new_origin.ToString());
2376 UpdateScreenInfo(window_);
2379 ////////////////////////////////////////////////////////////////////////////////
2380 // RenderWidgetHostViewAura, private:
2382 RenderWidgetHostViewAura::~RenderWidgetHostViewAura() {
2383 if (touch_editing_client_)
2384 touch_editing_client_->OnViewDestroyed();
2386 delegated_frame_host_.reset();
2387 window_observer_.reset();
2388 if (window_->GetHost())
2389 window_->GetHost()->RemoveObserver(this);
2390 UnlockMouse();
2391 if (popup_parent_host_view_) {
2392 DCHECK(popup_parent_host_view_->popup_child_host_view_ == NULL ||
2393 popup_parent_host_view_->popup_child_host_view_ == this);
2394 popup_parent_host_view_->popup_child_host_view_ = NULL;
2396 if (popup_child_host_view_) {
2397 DCHECK(popup_child_host_view_->popup_parent_host_view_ == NULL ||
2398 popup_child_host_view_->popup_parent_host_view_ == this);
2399 popup_child_host_view_->popup_parent_host_view_ = NULL;
2401 event_filter_for_popup_exit_.reset();
2402 aura::client::SetTooltipText(window_, NULL);
2403 gfx::Screen::GetScreenFor(window_)->RemoveObserver(this);
2405 // This call is usually no-op since |this| object is already removed from the
2406 // Aura root window and we don't have a way to get an input method object
2407 // associated with the window, but just in case.
2408 DetachFromInputMethod();
2410 #if defined(OS_WIN)
2411 // The LegacyRenderWidgetHostHWND window should have been destroyed in
2412 // RenderWidgetHostViewAura::OnWindowDestroying and the pointer should
2413 // be set to NULL.
2414 DCHECK(!legacy_render_widget_host_HWND_);
2415 #endif
2418 void RenderWidgetHostViewAura::UpdateCursorIfOverSelf() {
2419 const gfx::Point screen_point =
2420 gfx::Screen::GetScreenFor(GetNativeView())->GetCursorScreenPoint();
2421 aura::Window* root_window = window_->GetRootWindow();
2422 if (!root_window)
2423 return;
2425 gfx::Point root_window_point = screen_point;
2426 aura::client::ScreenPositionClient* screen_position_client =
2427 aura::client::GetScreenPositionClient(root_window);
2428 if (screen_position_client) {
2429 screen_position_client->ConvertPointFromScreen(
2430 root_window, &root_window_point);
2433 if (root_window->GetEventHandlerForPoint(root_window_point) != window_)
2434 return;
2436 gfx::NativeCursor cursor = current_cursor_.GetNativeCursor();
2437 // Do not show loading cursor when the cursor is currently hidden.
2438 if (is_loading_ && cursor != ui::kCursorNone)
2439 cursor = ui::kCursorPointer;
2441 aura::client::CursorClient* cursor_client =
2442 aura::client::GetCursorClient(root_window);
2443 if (cursor_client) {
2444 cursor_client->SetCursor(cursor);
2448 ui::InputMethod* RenderWidgetHostViewAura::GetInputMethod() const {
2449 aura::Window* root_window = window_->GetRootWindow();
2450 if (!root_window)
2451 return NULL;
2452 return root_window->GetHost()->GetInputMethod();
2455 void RenderWidgetHostViewAura::Shutdown() {
2456 if (!in_shutdown_) {
2457 in_shutdown_ = true;
2458 host_->Shutdown();
2462 bool RenderWidgetHostViewAura::NeedsInputGrab() {
2463 return popup_type_ == blink::WebPopupTypePage;
2466 bool RenderWidgetHostViewAura::NeedsMouseCapture() {
2467 #if defined(OS_LINUX) && !defined(OS_CHROMEOS)
2468 return NeedsInputGrab();
2469 #endif
2470 return false;
2473 void RenderWidgetHostViewAura::FinishImeCompositionSession() {
2474 if (!has_composition_text_)
2475 return;
2476 if (host_) {
2477 host_->ImeConfirmComposition(base::string16(), gfx::Range::InvalidRange(),
2478 false);
2480 ImeCancelComposition();
2483 void RenderWidgetHostViewAura::ModifyEventMovementAndCoords(
2484 blink::WebMouseEvent* event) {
2485 // If the mouse has just entered, we must report zero movementX/Y. Hence we
2486 // reset any global_mouse_position set previously.
2487 if (event->type == blink::WebInputEvent::MouseEnter ||
2488 event->type == blink::WebInputEvent::MouseLeave)
2489 global_mouse_position_.SetPoint(event->globalX, event->globalY);
2491 // Movement is computed by taking the difference of the new cursor position
2492 // and the previous. Under mouse lock the cursor will be warped back to the
2493 // center so that we are not limited by clipping boundaries.
2494 // We do not measure movement as the delta from cursor to center because
2495 // we may receive more mouse movement events before our warp has taken
2496 // effect.
2497 event->movementX = event->globalX - global_mouse_position_.x();
2498 event->movementY = event->globalY - global_mouse_position_.y();
2500 global_mouse_position_.SetPoint(event->globalX, event->globalY);
2502 // Under mouse lock, coordinates of mouse are locked to what they were when
2503 // mouse lock was entered.
2504 if (mouse_locked_) {
2505 event->x = unlocked_mouse_position_.x();
2506 event->y = unlocked_mouse_position_.y();
2507 event->windowX = unlocked_mouse_position_.x();
2508 event->windowY = unlocked_mouse_position_.y();
2509 event->globalX = unlocked_global_mouse_position_.x();
2510 event->globalY = unlocked_global_mouse_position_.y();
2511 } else {
2512 unlocked_mouse_position_.SetPoint(event->windowX, event->windowY);
2513 unlocked_global_mouse_position_.SetPoint(event->globalX, event->globalY);
2517 void RenderWidgetHostViewAura::NotifyRendererOfCursorVisibilityState(
2518 bool is_visible) {
2519 if (host_->is_hidden() ||
2520 (cursor_visibility_state_in_renderer_ == VISIBLE && is_visible) ||
2521 (cursor_visibility_state_in_renderer_ == NOT_VISIBLE && !is_visible))
2522 return;
2524 cursor_visibility_state_in_renderer_ = is_visible ? VISIBLE : NOT_VISIBLE;
2525 host_->SendCursorVisibilityState(is_visible);
2528 void RenderWidgetHostViewAura::SetOverscrollControllerEnabled(bool enabled) {
2529 if (!enabled)
2530 overscroll_controller_.reset();
2531 else if (!overscroll_controller_)
2532 overscroll_controller_.reset(new OverscrollController());
2535 void RenderWidgetHostViewAura::SnapToPhysicalPixelBoundary() {
2536 // The top left corner of our view in window coordinates might not land on a
2537 // device pixel boundary if we have a non-integer device scale. In that case,
2538 // to avoid the web contents area looking blurry we translate the web contents
2539 // in the +x, +y direction to land on the nearest pixel boundary. This may
2540 // cause the bottom and right edges to be clipped slightly, but that's ok.
2541 aura::Window* snapped = NULL;
2542 // On desktop, use the root window. On alternative environment (ash),
2543 // use the toplevel window which must be already snapped.
2544 if (gfx::Screen::GetScreenFor(window_) !=
2545 gfx::Screen::GetScreenByType(gfx::SCREEN_TYPE_ALTERNATE)) {
2546 snapped = window_->GetRootWindow();
2547 } else {
2548 snapped = window_->GetToplevelWindow();
2550 if (snapped && snapped != window_)
2551 ui::SnapLayerToPhysicalPixelBoundary(snapped->layer(), window_->layer());
2553 has_snapped_to_boundary_ = true;
2556 void RenderWidgetHostViewAura::OnShowContextMenu() {
2557 #if defined(OS_WIN)
2558 showing_context_menu_ = true;
2559 #endif
2562 void RenderWidgetHostViewAura::InternalSetBounds(const gfx::Rect& rect) {
2563 SnapToPhysicalPixelBoundary();
2564 // Don't recursively call SetBounds if this bounds update is the result of
2565 // a Window::SetBoundsInternal call.
2566 if (!in_bounds_changed_)
2567 window_->SetBounds(rect);
2568 host_->WasResized();
2569 delegated_frame_host_->WasResized();
2570 if (touch_editing_client_) {
2571 touch_editing_client_->OnSelectionOrCursorChanged(selection_anchor_,
2572 selection_focus_);
2574 #if defined(OS_WIN)
2575 // Create the legacy dummy window which corresponds to the bounds of the
2576 // webcontents. This will be passed as the container window for windowless
2577 // plugins.
2578 // Plugins like Flash assume the container window which is returned via the
2579 // NPNVnetscapeWindow property corresponds to the bounds of the webpage.
2580 // This is not true in Aura where we have only HWND which is the main Aura
2581 // window. If we return this window to plugins like Flash then it causes the
2582 // coordinate translations done by these plugins to break.
2583 // Additonally the legacy dummy window is needed for accessibility and for
2584 // scrolling to work in legacy drivers for trackpoints/trackpads, etc.
2585 if (!legacy_window_destroyed_ && GetNativeViewId()) {
2586 if (!legacy_render_widget_host_HWND_) {
2587 legacy_render_widget_host_HWND_ = LegacyRenderWidgetHostHWND::Create(
2588 reinterpret_cast<HWND>(GetNativeViewId()));
2590 if (legacy_render_widget_host_HWND_) {
2591 legacy_render_widget_host_HWND_->set_host(this);
2592 legacy_render_widget_host_HWND_->SetBounds(
2593 window_->GetBoundsInRootWindow());
2594 // There are cases where the parent window is created, made visible and
2595 // the associated RenderWidget is also visible before the
2596 // LegacyRenderWidgetHostHWND instace is created. Ensure that it is shown
2597 // here.
2598 if (!host_->is_hidden())
2599 legacy_render_widget_host_HWND_->Show();
2603 if (mouse_locked_)
2604 UpdateMouseLockRegion();
2605 #endif
2608 void RenderWidgetHostViewAura::SchedulePaintIfNotInClip(
2609 const gfx::Rect& rect,
2610 const gfx::Rect& clip) {
2611 if (!clip.IsEmpty()) {
2612 gfx::Rect to_paint = gfx::SubtractRects(rect, clip);
2613 if (!to_paint.IsEmpty())
2614 window_->SchedulePaintInRect(to_paint);
2615 } else {
2616 window_->SchedulePaintInRect(rect);
2620 bool RenderWidgetHostViewAura::ShouldMoveToCenter() {
2621 gfx::Rect rect = window_->bounds();
2622 rect = ConvertRectToScreen(rect);
2623 int border_x = rect.width() * kMouseLockBorderPercentage / 100;
2624 int border_y = rect.height() * kMouseLockBorderPercentage / 100;
2626 return global_mouse_position_.x() < rect.x() + border_x ||
2627 global_mouse_position_.x() > rect.right() - border_x ||
2628 global_mouse_position_.y() < rect.y() + border_y ||
2629 global_mouse_position_.y() > rect.bottom() - border_y;
2632 void RenderWidgetHostViewAura::AddedToRootWindow() {
2633 window_->GetHost()->AddObserver(this);
2634 UpdateScreenInfo(window_);
2636 aura::client::CursorClient* cursor_client =
2637 aura::client::GetCursorClient(window_->GetRootWindow());
2638 if (cursor_client) {
2639 cursor_client->AddObserver(this);
2640 NotifyRendererOfCursorVisibilityState(cursor_client->IsCursorVisible());
2642 if (HasFocus()) {
2643 ui::InputMethod* input_method = GetInputMethod();
2644 if (input_method)
2645 input_method->SetFocusedTextInputClient(this);
2648 #if defined(OS_WIN)
2649 // The parent may have changed here. Ensure that the legacy window is
2650 // reparented accordingly.
2651 if (legacy_render_widget_host_HWND_)
2652 legacy_render_widget_host_HWND_->UpdateParent(
2653 reinterpret_cast<HWND>(GetNativeViewId()));
2654 #endif
2656 delegated_frame_host_->SetCompositor(window_->GetHost()->compositor());
2657 if (window_->GetHost()->compositor())
2658 begin_frame_observer_proxy_.SetCompositor(window_->GetHost()->compositor());
2661 void RenderWidgetHostViewAura::RemovingFromRootWindow() {
2662 aura::client::CursorClient* cursor_client =
2663 aura::client::GetCursorClient(window_->GetRootWindow());
2664 if (cursor_client)
2665 cursor_client->RemoveObserver(this);
2667 DetachFromInputMethod();
2669 window_->GetHost()->RemoveObserver(this);
2670 delegated_frame_host_->ResetCompositor();
2671 begin_frame_observer_proxy_.ResetCompositor();
2673 #if defined(OS_WIN)
2674 // Update the legacy window's parent temporarily to the desktop window. It
2675 // will eventually get reparented to the right root.
2676 if (legacy_render_widget_host_HWND_)
2677 legacy_render_widget_host_HWND_->UpdateParent(::GetDesktopWindow());
2678 #endif
2681 void RenderWidgetHostViewAura::DetachFromInputMethod() {
2682 ui::InputMethod* input_method = GetInputMethod();
2683 if (input_method)
2684 input_method->DetachTextInputClient(this);
2687 void RenderWidgetHostViewAura::ForwardKeyboardEvent(
2688 const NativeWebKeyboardEvent& event) {
2689 #if defined(OS_LINUX) && !defined(OS_CHROMEOS)
2690 ui::TextEditKeyBindingsDelegateAuraLinux* keybinding_delegate =
2691 ui::GetTextEditKeyBindingsDelegate();
2692 std::vector<ui::TextEditCommandAuraLinux> commands;
2693 if (!event.skip_in_browser &&
2694 keybinding_delegate &&
2695 event.os_event &&
2696 keybinding_delegate->MatchEvent(*event.os_event, &commands)) {
2697 // Transform from ui/ types to content/ types.
2698 EditCommands edit_commands;
2699 for (std::vector<ui::TextEditCommandAuraLinux>::const_iterator it =
2700 commands.begin(); it != commands.end(); ++it) {
2701 edit_commands.push_back(EditCommand(it->GetCommandString(),
2702 it->argument()));
2704 host_->Send(new InputMsg_SetEditCommandsForNextKeyEvent(
2705 host_->GetRoutingID(), edit_commands));
2706 NativeWebKeyboardEvent copy_event(event);
2707 copy_event.match_edit_command = true;
2708 host_->ForwardKeyboardEvent(copy_event);
2709 return;
2711 #endif
2713 host_->ForwardKeyboardEvent(event);
2716 ////////////////////////////////////////////////////////////////////////////////
2717 // DelegatedFrameHost, public:
2719 ui::Layer* RenderWidgetHostViewAura::DelegatedFrameHostGetLayer() const {
2720 return window_->layer();
2723 bool RenderWidgetHostViewAura::DelegatedFrameHostIsVisible() const {
2724 return !host_->is_hidden();
2727 gfx::Size RenderWidgetHostViewAura::DelegatedFrameHostDesiredSizeInDIP() const {
2728 return window_->bounds().size();
2731 bool RenderWidgetHostViewAura::DelegatedFrameCanCreateResizeLock() const {
2732 #if !defined(OS_CHROMEOS)
2733 // On Windows and Linux, holding pointer moves will not help throttling
2734 // resizes.
2735 // TODO(piman): on Windows we need to block (nested message loop?) the
2736 // WM_SIZE event. On Linux we need to throttle at the WM level using
2737 // _NET_WM_SYNC_REQUEST.
2738 return false;
2739 #else
2740 if (host_->auto_resize_enabled())
2741 return false;
2742 return true;
2743 #endif
2746 scoped_ptr<ResizeLock>
2747 RenderWidgetHostViewAura::DelegatedFrameHostCreateResizeLock(
2748 bool defer_compositor_lock) {
2749 gfx::Size desired_size = window_->bounds().size();
2750 return scoped_ptr<ResizeLock>(new CompositorResizeLock(
2751 window_->GetHost(),
2752 desired_size,
2753 defer_compositor_lock,
2754 base::TimeDelta::FromMilliseconds(kResizeLockTimeoutMs)));
2757 void RenderWidgetHostViewAura::DelegatedFrameHostResizeLockWasReleased() {
2758 host_->WasResized();
2761 void RenderWidgetHostViewAura::DelegatedFrameHostSendCompositorSwapAck(
2762 int output_surface_id,
2763 const cc::CompositorFrameAck& ack) {
2764 host_->Send(new ViewMsg_SwapCompositorFrameAck(host_->GetRoutingID(),
2765 output_surface_id, ack));
2768 void RenderWidgetHostViewAura::DelegatedFrameHostSendReclaimCompositorResources(
2769 int output_surface_id,
2770 const cc::CompositorFrameAck& ack) {
2771 host_->Send(new ViewMsg_ReclaimCompositorResources(host_->GetRoutingID(),
2772 output_surface_id, ack));
2775 void RenderWidgetHostViewAura::DelegatedFrameHostOnLostCompositorResources() {
2776 host_->ScheduleComposite();
2779 void RenderWidgetHostViewAura::DelegatedFrameHostUpdateVSyncParameters(
2780 const base::TimeTicks& timebase,
2781 const base::TimeDelta& interval) {
2782 host_->UpdateVSyncParameters(timebase, interval);
2785 void RenderWidgetHostViewAura::OnDidNavigateMainFrameToNewPage() {
2786 ui::GestureRecognizer::Get()->CancelActiveTouches(window_);
2789 uint32_t RenderWidgetHostViewAura::GetSurfaceIdNamespace() {
2790 return delegated_frame_host_->GetSurfaceIdNamespace();
2793 ////////////////////////////////////////////////////////////////////////////////
2794 // RenderWidgetHostViewBase, public:
2796 // static
2797 void RenderWidgetHostViewBase::GetDefaultScreenInfo(WebScreenInfo* results) {
2798 GetScreenInfoForWindow(results, NULL);
2801 } // namespace content