Task Manager: Remove goat teleporter.
[chromium-blink-merge.git] / ui / keyboard / keyboard_controller.cc
blob6c02069e7ff6e761199c30be5780802c71a78726
1 // Copyright (c) 2013 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 "ui/keyboard/keyboard_controller.h"
7 #include <set>
9 #include "base/bind.h"
10 #include "base/command_line.h"
11 #include "content/public/browser/render_widget_host.h"
12 #include "content/public/browser/render_widget_host_iterator.h"
13 #include "content/public/browser/render_widget_host_view.h"
14 #include "ui/aura/window.h"
15 #include "ui/aura/window_delegate.h"
16 #include "ui/aura/window_observer.h"
17 #include "ui/base/cursor/cursor.h"
18 #include "ui/base/hit_test.h"
19 #include "ui/base/ime/input_method.h"
20 #include "ui/base/ime/text_input_client.h"
21 #include "ui/compositor/layer_animation_observer.h"
22 #include "ui/compositor/scoped_layer_animation_settings.h"
23 #include "ui/gfx/path.h"
24 #include "ui/gfx/rect.h"
25 #include "ui/gfx/skia_util.h"
26 #include "ui/keyboard/keyboard_controller_observer.h"
27 #include "ui/keyboard/keyboard_controller_proxy.h"
28 #include "ui/keyboard/keyboard_layout_manager.h"
29 #include "ui/keyboard/keyboard_switches.h"
30 #include "ui/keyboard/keyboard_util.h"
31 #include "ui/wm/core/masked_window_targeter.h"
33 #if defined(OS_CHROMEOS)
34 #include "base/process/launch.h"
35 #include "base/sys_info.h"
36 #endif
38 namespace {
40 const int kHideKeyboardDelayMs = 100;
42 // The virtual keyboard show/hide animation duration.
43 const int kAnimationDurationMs = 200;
45 // The opacity of virtual keyboard container when show animation starts or
46 // hide animation finishes.
47 const float kAnimationStartOrAfterHideOpacity = 0.2f;
49 // Event targeter for the keyboard container.
50 class KeyboardContainerTargeter : public wm::MaskedWindowTargeter {
51 public:
52 KeyboardContainerTargeter(aura::Window* container,
53 keyboard::KeyboardControllerProxy* proxy)
54 : wm::MaskedWindowTargeter(container),
55 proxy_(proxy) {
58 virtual ~KeyboardContainerTargeter() {}
60 private:
61 // wm::MaskedWindowTargeter:
62 virtual bool GetHitTestMask(aura::Window* window,
63 gfx::Path* mask) const OVERRIDE {
64 if (proxy_ && !proxy_->HasKeyboardWindow())
65 return true;
66 gfx::Rect keyboard_bounds = proxy_ ? proxy_->GetKeyboardWindow()->bounds() :
67 keyboard::DefaultKeyboardBoundsFromWindowBounds(window->bounds());
68 mask->addRect(RectToSkRect(keyboard_bounds));
69 return true;
72 keyboard::KeyboardControllerProxy* proxy_;
74 DISALLOW_COPY_AND_ASSIGN(KeyboardContainerTargeter);
77 // The KeyboardWindowDelegate makes sure the keyboard-window does not get focus.
78 // This is necessary to make sure that the synthetic key-events reach the target
79 // window.
80 // The delegate deletes itself when the window is destroyed.
81 class KeyboardWindowDelegate : public aura::WindowDelegate {
82 public:
83 explicit KeyboardWindowDelegate(keyboard::KeyboardControllerProxy* proxy)
84 : proxy_(proxy) {}
85 virtual ~KeyboardWindowDelegate() {}
87 private:
88 // Overridden from aura::WindowDelegate:
89 virtual gfx::Size GetMinimumSize() const OVERRIDE { return gfx::Size(); }
90 virtual gfx::Size GetMaximumSize() const OVERRIDE { return gfx::Size(); }
91 virtual void OnBoundsChanged(const gfx::Rect& old_bounds,
92 const gfx::Rect& new_bounds) OVERRIDE {
93 bounds_ = new_bounds;
95 virtual gfx::NativeCursor GetCursor(const gfx::Point& point) OVERRIDE {
96 return gfx::kNullCursor;
98 virtual int GetNonClientComponent(const gfx::Point& point) const OVERRIDE {
99 return HTNOWHERE;
101 virtual bool ShouldDescendIntoChildForEventHandling(
102 aura::Window* child,
103 const gfx::Point& location) OVERRIDE {
104 return true;
106 virtual bool CanFocus() OVERRIDE { return false; }
107 virtual void OnCaptureLost() OVERRIDE {}
108 virtual void OnPaint(gfx::Canvas* canvas) OVERRIDE {}
109 virtual void OnDeviceScaleFactorChanged(float device_scale_factor) OVERRIDE {}
110 virtual void OnWindowDestroying(aura::Window* window) OVERRIDE {}
111 virtual void OnWindowDestroyed(aura::Window* window) OVERRIDE { delete this; }
112 virtual void OnWindowTargetVisibilityChanged(bool visible) OVERRIDE {}
113 virtual bool HasHitTestMask() const OVERRIDE {
114 return !proxy_ || proxy_->HasKeyboardWindow();
116 virtual void GetHitTestMask(gfx::Path* mask) const OVERRIDE {
117 if (proxy_ && !proxy_->HasKeyboardWindow())
118 return;
119 gfx::Rect keyboard_bounds = proxy_ ? proxy_->GetKeyboardWindow()->bounds() :
120 keyboard::DefaultKeyboardBoundsFromWindowBounds(bounds_);
121 mask->addRect(RectToSkRect(keyboard_bounds));
124 gfx::Rect bounds_;
125 keyboard::KeyboardControllerProxy* proxy_;
127 DISALLOW_COPY_AND_ASSIGN(KeyboardWindowDelegate);
130 void ToggleTouchEventLogging(bool enable) {
131 #if defined(OS_CHROMEOS)
132 if (!base::SysInfo::IsRunningOnChromeOS())
133 return;
134 CommandLine command(
135 base::FilePath("/opt/google/touchscreen/toggle_touch_event_logging"));
136 if (enable)
137 command.AppendArg("1");
138 else
139 command.AppendArg("0");
140 VLOG(1) << "Running " << command.GetCommandLineString();
141 base::LaunchOptions options;
142 options.wait = true;
143 base::LaunchProcess(command, options, NULL);
144 #endif
147 aura::Window *GetFrameWindow(aura::Window *window) {
148 // Each container window has a non-negative id. Stop traversing at the child
149 // of a container window.
150 if (!window)
151 return NULL;
152 while(window->parent() && window->parent()->id() < 0) {
153 window = window->parent();
155 return window;
158 } // namespace
160 namespace keyboard {
162 // Observer for both keyboard show and hide animations. It should be owned by
163 // KeyboardController.
164 class CallbackAnimationObserver : public ui::LayerAnimationObserver {
165 public:
166 CallbackAnimationObserver(ui::LayerAnimator* animator,
167 base::Callback<void(void)> callback);
168 virtual ~CallbackAnimationObserver();
170 private:
171 // Overridden from ui::LayerAnimationObserver:
172 virtual void OnLayerAnimationEnded(ui::LayerAnimationSequence* seq) OVERRIDE;
173 virtual void OnLayerAnimationAborted(
174 ui::LayerAnimationSequence* seq) OVERRIDE;
175 virtual void OnLayerAnimationScheduled(
176 ui::LayerAnimationSequence* seq) OVERRIDE {}
178 ui::LayerAnimator* animator_;
179 base::Callback<void(void)> callback_;
181 DISALLOW_COPY_AND_ASSIGN(CallbackAnimationObserver);
184 CallbackAnimationObserver::CallbackAnimationObserver(
185 ui::LayerAnimator* animator, base::Callback<void(void)> callback)
186 : animator_(animator), callback_(callback) {
189 CallbackAnimationObserver::~CallbackAnimationObserver() {
190 animator_->RemoveObserver(this);
193 void CallbackAnimationObserver::OnLayerAnimationEnded(
194 ui::LayerAnimationSequence* seq) {
195 if (animator_->is_animating())
196 return;
197 animator_->RemoveObserver(this);
198 callback_.Run();
201 void CallbackAnimationObserver::OnLayerAnimationAborted(
202 ui::LayerAnimationSequence* seq) {
203 animator_->RemoveObserver(this);
206 class WindowBoundsChangeObserver : public aura::WindowObserver {
207 public:
208 virtual void OnWindowBoundsChanged(aura::Window* window,
209 const gfx::Rect& old_bounds,
210 const gfx::Rect& new_bounds) OVERRIDE;
211 virtual void OnWindowDestroyed(aura::Window* window) OVERRIDE;
213 void AddObservedWindow(aura::Window* window);
214 void RemoveAllObservedWindows();
216 private:
217 std::set<aura::Window*> observed_windows_;
220 void WindowBoundsChangeObserver::OnWindowBoundsChanged(aura::Window* window,
221 const gfx::Rect& old_bounds, const gfx::Rect& new_bounds) {
222 KeyboardController* controller = KeyboardController::GetInstance();
223 if (controller)
224 controller->UpdateWindowInsets(window);
227 void WindowBoundsChangeObserver::OnWindowDestroyed(aura::Window* window) {
228 if (window->HasObserver(this))
229 window->RemoveObserver(this);
230 observed_windows_.erase(window);
233 void WindowBoundsChangeObserver::AddObservedWindow(aura::Window* window) {
234 if (!window->HasObserver(this)) {
235 window->AddObserver(this);
236 observed_windows_.insert(window);
240 void WindowBoundsChangeObserver::RemoveAllObservedWindows() {
241 for (std::set<aura::Window*>::iterator it = observed_windows_.begin();
242 it != observed_windows_.end(); ++it)
243 (*it)->RemoveObserver(this);
244 observed_windows_.clear();
247 // static
248 KeyboardController* KeyboardController::instance_ = NULL;
250 KeyboardController::KeyboardController(KeyboardControllerProxy* proxy)
251 : proxy_(proxy),
252 input_method_(NULL),
253 keyboard_visible_(false),
254 show_on_resize_(false),
255 lock_keyboard_(false),
256 type_(ui::TEXT_INPUT_TYPE_NONE),
257 weak_factory_(this) {
258 CHECK(proxy);
259 input_method_ = proxy_->GetInputMethod();
260 input_method_->AddObserver(this);
261 window_bounds_observer_.reset(new WindowBoundsChangeObserver());
264 KeyboardController::~KeyboardController() {
265 if (container_)
266 container_->RemoveObserver(this);
267 if (input_method_)
268 input_method_->RemoveObserver(this);
269 ResetWindowInsets();
272 // static
273 void KeyboardController::ResetInstance(KeyboardController* controller) {
274 if (instance_ && instance_ != controller)
275 delete instance_;
276 instance_ = controller;
279 // static
280 KeyboardController* KeyboardController::GetInstance() {
281 return instance_;
284 aura::Window* KeyboardController::GetContainerWindow() {
285 if (!container_.get()) {
286 container_.reset(new aura::Window(
287 new KeyboardWindowDelegate(proxy_.get())));
288 container_->SetEventTargeter(scoped_ptr<ui::EventTargeter>(
289 new KeyboardContainerTargeter(container_.get(), proxy_.get())));
290 container_->SetName("KeyboardContainer");
291 container_->set_owned_by_parent(false);
292 container_->Init(aura::WINDOW_LAYER_NOT_DRAWN);
293 container_->AddObserver(this);
294 container_->SetLayoutManager(new KeyboardLayoutManager(this));
296 return container_.get();
299 void KeyboardController::NotifyKeyboardBoundsChanging(
300 const gfx::Rect& new_bounds) {
301 current_keyboard_bounds_ = new_bounds;
302 if (proxy_->HasKeyboardWindow() && proxy_->GetKeyboardWindow()->IsVisible()) {
303 FOR_EACH_OBSERVER(KeyboardControllerObserver,
304 observer_list_,
305 OnKeyboardBoundsChanging(new_bounds));
306 if (keyboard::IsKeyboardOverscrollEnabled()) {
307 // Adjust the height of the viewport for visible windows on the primary
308 // display.
309 // TODO(kevers): Add EnvObserver to properly initialize insets if a
310 // window is created while the keyboard is visible.
311 scoped_ptr<content::RenderWidgetHostIterator> widgets(
312 content::RenderWidgetHost::GetRenderWidgetHosts());
313 aura::Window *keyboard_window = proxy_->GetKeyboardWindow();
314 aura::Window *root_window = keyboard_window->GetRootWindow();
315 while (content::RenderWidgetHost* widget = widgets->GetNextHost()) {
316 content::RenderWidgetHostView* view = widget->GetView();
317 // Can be NULL, e.g. if the RenderWidget is being destroyed or
318 // the render process crashed.
319 if (view) {
320 aura::Window *window = view->GetNativeView();
321 // If virtual keyboard failed to load, a widget that displays error
322 // message will be created and adds as a child of the virtual keyboard
323 // window. We want to avoid add BoundsChangedObserver to that window.
324 if (GetFrameWindow(window) != keyboard_window &&
325 window->GetRootWindow() == root_window) {
326 gfx::Rect window_bounds = window->GetBoundsInScreen();
327 gfx::Rect intersect = gfx::IntersectRects(window_bounds,
328 new_bounds);
329 int overlap = intersect.height();
330 if (overlap > 0 && overlap < window_bounds.height())
331 view->SetInsets(gfx::Insets(0, 0, overlap, 0));
332 else
333 view->SetInsets(gfx::Insets());
334 AddBoundsChangedObserver(window);
338 } else {
339 ResetWindowInsets();
341 } else {
342 current_keyboard_bounds_ = gfx::Rect();
346 void KeyboardController::HideKeyboard(HideReason reason) {
347 keyboard_visible_ = false;
348 ToggleTouchEventLogging(true);
350 keyboard::LogKeyboardControlEvent(
351 reason == HIDE_REASON_AUTOMATIC ?
352 keyboard::KEYBOARD_CONTROL_HIDE_AUTO :
353 keyboard::KEYBOARD_CONTROL_HIDE_USER);
355 NotifyKeyboardBoundsChanging(gfx::Rect());
357 set_lock_keyboard(false);
359 ui::LayerAnimator* container_animator = container_->layer()->GetAnimator();
360 animation_observer_.reset(new CallbackAnimationObserver(
361 container_animator,
362 base::Bind(&KeyboardController::HideAnimationFinished,
363 base::Unretained(this))));
364 container_animator->AddObserver(animation_observer_.get());
366 ui::ScopedLayerAnimationSettings settings(container_animator);
367 settings.SetTweenType(gfx::Tween::EASE_OUT);
368 settings.SetTransitionDuration(
369 base::TimeDelta::FromMilliseconds(kAnimationDurationMs));
370 gfx::Transform transform;
371 transform.Translate(0, proxy_->GetKeyboardWindow()->bounds().height());
372 container_->SetTransform(transform);
373 container_->layer()->SetOpacity(kAnimationStartOrAfterHideOpacity);
376 void KeyboardController::AddObserver(KeyboardControllerObserver* observer) {
377 observer_list_.AddObserver(observer);
380 void KeyboardController::RemoveObserver(KeyboardControllerObserver* observer) {
381 observer_list_.RemoveObserver(observer);
384 void KeyboardController::ShowKeyboard(bool lock) {
385 set_lock_keyboard(lock);
386 ShowKeyboardInternal();
389 void KeyboardController::OnWindowHierarchyChanged(
390 const HierarchyChangeParams& params) {
391 if (params.new_parent && params.target == container_.get())
392 OnTextInputStateChanged(proxy_->GetInputMethod()->GetTextInputClient());
395 void KeyboardController::Reload() {
396 if (proxy_->HasKeyboardWindow()) {
397 // A reload should never try to show virtual keyboard. If keyboard is not
398 // visible before reload, it should keep invisible after reload.
399 show_on_resize_ = false;
400 proxy_->ReloadKeyboardIfNeeded();
404 void KeyboardController::OnTextInputStateChanged(
405 const ui::TextInputClient* client) {
406 if (!container_.get())
407 return;
409 if (IsKeyboardUsabilityExperimentEnabled()) {
410 ShowKeyboardInternal();
411 return;
414 type_ = client ? client->GetTextInputType() : ui::TEXT_INPUT_TYPE_NONE;
416 if (type_ == ui::TEXT_INPUT_TYPE_NONE && !lock_keyboard_) {
417 if (keyboard_visible_) {
418 // Set the visibility state here so that any queries for visibility
419 // before the timer fires returns the correct future value.
420 keyboard_visible_ = false;
421 base::MessageLoop::current()->PostDelayedTask(
422 FROM_HERE,
423 base::Bind(&KeyboardController::HideKeyboard,
424 weak_factory_.GetWeakPtr(), HIDE_REASON_AUTOMATIC),
425 base::TimeDelta::FromMilliseconds(kHideKeyboardDelayMs));
427 } else {
428 // Abort a pending keyboard hide.
429 if (WillHideKeyboard()) {
430 weak_factory_.InvalidateWeakPtrs();
431 keyboard_visible_ = true;
433 proxy_->SetUpdateInputType(type_);
434 // Do not explicitly show the Virtual keyboard unless it is in the process
435 // of hiding. Instead, the virtual keyboard is shown in response to a user
436 // gesture (mouse or touch) that is received while an element has input
437 // focus. Showing the keyboard requires an explicit call to
438 // OnShowImeIfNeeded.
442 void KeyboardController::OnInputMethodDestroyed(
443 const ui::InputMethod* input_method) {
444 DCHECK_EQ(input_method_, input_method);
445 input_method_ = NULL;
448 void KeyboardController::OnShowImeIfNeeded() {
449 ShowKeyboardInternal();
452 void KeyboardController::UpdateWindowInsets(aura::Window* window) {
453 aura::Window *keyboard_window = proxy_->GetKeyboardWindow();
454 if (window == keyboard_window)
455 return;
457 bool enableInsets = (keyboard_window->GetRootWindow() ==
458 window->GetRootWindow()) && keyboard::IsKeyboardOverscrollEnabled() &&
459 proxy_->GetKeyboardWindow()->IsVisible();
461 scoped_ptr<content::RenderWidgetHostIterator> widgets(
462 content::RenderWidgetHost::GetRenderWidgetHosts());
463 while (content::RenderWidgetHost* widget = widgets->GetNextHost()) {
464 content::RenderWidgetHostView* view = widget->GetView();
465 if (view && window->Contains(view->GetNativeView())) {
466 gfx::Rect window_bounds = view->GetNativeView()->GetBoundsInScreen();
467 gfx::Rect intersect = gfx::IntersectRects(window_bounds,
468 proxy_->GetKeyboardWindow()->bounds());
469 int overlap = enableInsets ? intersect.height() : 0;
470 if (overlap > 0 && overlap < window_bounds.height())
471 view->SetInsets(gfx::Insets(0, 0, overlap, 0));
472 else
473 view->SetInsets(gfx::Insets());
474 return;
479 void KeyboardController::ShowKeyboardInternal() {
480 if (!container_.get())
481 return;
483 if (container_->children().empty()) {
484 keyboard::MarkKeyboardLoadStarted();
485 aura::Window* keyboard = proxy_->GetKeyboardWindow();
486 keyboard->Show();
487 container_->AddChild(keyboard);
488 keyboard->set_owned_by_parent(false);
491 proxy_->ReloadKeyboardIfNeeded();
493 if (keyboard_visible_) {
494 return;
495 } else if (proxy_->GetKeyboardWindow()->bounds().height() == 0) {
496 show_on_resize_ = true;
497 return;
500 keyboard_visible_ = true;
502 // If the controller is in the process of hiding the keyboard, do not log
503 // the stat here since the keyboard will not actually be shown.
504 if (!WillHideKeyboard())
505 keyboard::LogKeyboardControlEvent(keyboard::KEYBOARD_CONTROL_SHOW);
507 weak_factory_.InvalidateWeakPtrs();
509 // If |container_| has hide animation, its visibility is set to false when
510 // hide animation finished. So even if the container is visible at this
511 // point, it may in the process of hiding. We still need to show keyboard
512 // container in this case.
513 if (container_->IsVisible() &&
514 !container_->layer()->GetAnimator()->is_animating())
515 return;
517 ToggleTouchEventLogging(false);
518 ui::LayerAnimator* container_animator = container_->layer()->GetAnimator();
520 // If the container is not animating, makes sure the position and opacity
521 // are at begin states for animation.
522 if (!container_animator->is_animating()) {
523 gfx::Transform transform;
524 transform.Translate(0, proxy_->GetKeyboardWindow()->bounds().height());
525 container_->SetTransform(transform);
526 container_->layer()->SetOpacity(kAnimationStartOrAfterHideOpacity);
529 container_animator->set_preemption_strategy(
530 ui::LayerAnimator::IMMEDIATELY_ANIMATE_TO_NEW_TARGET);
531 animation_observer_.reset(new CallbackAnimationObserver(
532 container_animator,
533 base::Bind(&KeyboardController::ShowAnimationFinished,
534 base::Unretained(this))));
535 container_animator->AddObserver(animation_observer_.get());
537 proxy_->ShowKeyboardContainer(container_.get());
540 // Scope the following animation settings as we don't want to animate
541 // visibility change that triggered by a call to the base class function
542 // ShowKeyboardContainer with these settings. The container should become
543 // visible immediately.
544 ui::ScopedLayerAnimationSettings settings(container_animator);
545 settings.SetTweenType(gfx::Tween::EASE_IN);
546 settings.SetTransitionDuration(
547 base::TimeDelta::FromMilliseconds(kAnimationDurationMs));
548 container_->SetTransform(gfx::Transform());
549 container_->layer()->SetOpacity(1.0);
553 void KeyboardController::ResetWindowInsets() {
554 const gfx::Insets insets;
555 scoped_ptr<content::RenderWidgetHostIterator> widgets(
556 content::RenderWidgetHost::GetRenderWidgetHosts());
557 while (content::RenderWidgetHost* widget = widgets->GetNextHost()) {
558 content::RenderWidgetHostView* view = widget->GetView();
559 if (view)
560 view->SetInsets(insets);
562 window_bounds_observer_->RemoveAllObservedWindows();
565 bool KeyboardController::WillHideKeyboard() const {
566 return weak_factory_.HasWeakPtrs();
569 void KeyboardController::ShowAnimationFinished() {
570 // Notify observers after animation finished to prevent reveal desktop
571 // background during animation.
572 NotifyKeyboardBoundsChanging(proxy_->GetKeyboardWindow()->bounds());
573 proxy_->EnsureCaretInWorkArea();
576 void KeyboardController::HideAnimationFinished() {
577 proxy_->HideKeyboardContainer(container_.get());
580 void KeyboardController::AddBoundsChangedObserver(aura::Window* window) {
581 aura::Window* target_window = GetFrameWindow(window);
582 if (target_window)
583 window_bounds_observer_->AddObservedWindow(target_window);
586 } // namespace keyboard