Roll src/third_party/WebKit 733baf8:7f284eb (svn 185998:186005)
[chromium-blink-merge.git] / ui / keyboard / keyboard_controller.cc
blob4ee23b128c284c1dbe013cdd149b056115347b4e
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_util.h"
30 #include "ui/wm/core/masked_window_targeter.h"
32 #if defined(OS_CHROMEOS)
33 #include "base/process/launch.h"
34 #include "base/sys_info.h"
35 #endif
37 namespace {
39 const int kHideKeyboardDelayMs = 100;
41 // The virtual keyboard show/hide animation duration.
42 const int kShowAnimationDurationMs = 350;
43 const int kHideAnimationDurationMs = 100;
45 // The opacity of virtual keyboard container when show animation starts or
46 // hide animation finishes. This cannot be zero because we call Show() on the
47 // keyboard window before setting the opacity back to 1.0. Since windows are not
48 // allowed to be shown with zero opacity, we always animate to 0.01 instead.
49 const float kAnimationStartOrAfterHideOpacity = 0.01f;
51 // Event targeter for the keyboard container.
52 class KeyboardContainerTargeter : public wm::MaskedWindowTargeter {
53 public:
54 KeyboardContainerTargeter(aura::Window* container,
55 keyboard::KeyboardControllerProxy* proxy)
56 : wm::MaskedWindowTargeter(container),
57 proxy_(proxy) {
60 ~KeyboardContainerTargeter() override {}
62 private:
63 // wm::MaskedWindowTargeter:
64 bool GetHitTestMask(aura::Window* window, gfx::Path* mask) const override {
65 if (proxy_ && !proxy_->HasKeyboardWindow())
66 return true;
67 gfx::Rect keyboard_bounds = proxy_ ? proxy_->GetKeyboardWindow()->bounds() :
68 keyboard::DefaultKeyboardBoundsFromWindowBounds(window->bounds());
69 mask->addRect(RectToSkRect(keyboard_bounds));
70 return true;
73 keyboard::KeyboardControllerProxy* proxy_;
75 DISALLOW_COPY_AND_ASSIGN(KeyboardContainerTargeter);
78 // The KeyboardWindowDelegate makes sure the keyboard-window does not get focus.
79 // This is necessary to make sure that the synthetic key-events reach the target
80 // window.
81 // The delegate deletes itself when the window is destroyed.
82 class KeyboardWindowDelegate : public aura::WindowDelegate {
83 public:
84 explicit KeyboardWindowDelegate(keyboard::KeyboardControllerProxy* proxy)
85 : proxy_(proxy) {}
86 ~KeyboardWindowDelegate() override {}
88 private:
89 // Overridden from aura::WindowDelegate:
90 gfx::Size GetMinimumSize() const override { return gfx::Size(); }
91 gfx::Size GetMaximumSize() const override { return gfx::Size(); }
92 void OnBoundsChanged(const gfx::Rect& old_bounds,
93 const gfx::Rect& new_bounds) override {
94 bounds_ = new_bounds;
96 gfx::NativeCursor GetCursor(const gfx::Point& point) override {
97 return gfx::kNullCursor;
99 int GetNonClientComponent(const gfx::Point& point) const override {
100 return HTNOWHERE;
102 bool ShouldDescendIntoChildForEventHandling(
103 aura::Window* child,
104 const gfx::Point& location) override {
105 return true;
107 bool CanFocus() override { return false; }
108 void OnCaptureLost() override {}
109 void OnPaint(gfx::Canvas* canvas) override {}
110 void OnDeviceScaleFactorChanged(float device_scale_factor) override {}
111 void OnWindowDestroying(aura::Window* window) override {}
112 void OnWindowDestroyed(aura::Window* window) override { delete this; }
113 void OnWindowTargetVisibilityChanged(bool visible) override {}
114 bool HasHitTestMask() const override {
115 return !proxy_ || proxy_->HasKeyboardWindow();
117 void GetHitTestMask(gfx::Path* mask) const override {
118 if (proxy_ && !proxy_->HasKeyboardWindow())
119 return;
120 gfx::Rect keyboard_bounds = proxy_ ? proxy_->GetKeyboardWindow()->bounds() :
121 keyboard::DefaultKeyboardBoundsFromWindowBounds(bounds_);
122 mask->addRect(RectToSkRect(keyboard_bounds));
125 gfx::Rect bounds_;
126 keyboard::KeyboardControllerProxy* proxy_;
128 DISALLOW_COPY_AND_ASSIGN(KeyboardWindowDelegate);
131 void ToggleTouchEventLogging(bool enable) {
132 #if defined(OS_CHROMEOS)
133 if (!base::SysInfo::IsRunningOnChromeOS())
134 return;
135 CommandLine command(
136 base::FilePath("/opt/google/touchscreen/toggle_touch_event_logging"));
137 if (enable)
138 command.AppendArg("1");
139 else
140 command.AppendArg("0");
141 VLOG(1) << "Running " << command.GetCommandLineString();
142 base::LaunchOptions options;
143 options.wait = true;
144 base::LaunchProcess(command, options, NULL);
145 #endif
148 } // namespace
150 namespace keyboard {
152 // Observer for both keyboard show and hide animations. It should be owned by
153 // KeyboardController.
154 class CallbackAnimationObserver : public ui::LayerAnimationObserver {
155 public:
156 CallbackAnimationObserver(ui::LayerAnimator* animator,
157 base::Callback<void(void)> callback);
158 ~CallbackAnimationObserver() override;
160 private:
161 // Overridden from ui::LayerAnimationObserver:
162 void OnLayerAnimationEnded(ui::LayerAnimationSequence* seq) override;
163 void OnLayerAnimationAborted(ui::LayerAnimationSequence* seq) override;
164 void OnLayerAnimationScheduled(ui::LayerAnimationSequence* seq) override {}
166 ui::LayerAnimator* animator_;
167 base::Callback<void(void)> callback_;
169 DISALLOW_COPY_AND_ASSIGN(CallbackAnimationObserver);
172 CallbackAnimationObserver::CallbackAnimationObserver(
173 ui::LayerAnimator* animator, base::Callback<void(void)> callback)
174 : animator_(animator), callback_(callback) {
177 CallbackAnimationObserver::~CallbackAnimationObserver() {
178 animator_->RemoveObserver(this);
181 void CallbackAnimationObserver::OnLayerAnimationEnded(
182 ui::LayerAnimationSequence* seq) {
183 if (animator_->is_animating())
184 return;
185 animator_->RemoveObserver(this);
186 callback_.Run();
189 void CallbackAnimationObserver::OnLayerAnimationAborted(
190 ui::LayerAnimationSequence* seq) {
191 animator_->RemoveObserver(this);
194 class WindowBoundsChangeObserver : public aura::WindowObserver {
195 public:
196 void OnWindowBoundsChanged(aura::Window* window,
197 const gfx::Rect& old_bounds,
198 const gfx::Rect& new_bounds) override;
199 void OnWindowDestroyed(aura::Window* window) override;
201 void AddObservedWindow(aura::Window* window);
202 void RemoveAllObservedWindows();
204 private:
205 std::set<aura::Window*> observed_windows_;
208 void WindowBoundsChangeObserver::OnWindowBoundsChanged(aura::Window* window,
209 const gfx::Rect& old_bounds, const gfx::Rect& new_bounds) {
210 KeyboardController* controller = KeyboardController::GetInstance();
211 if (controller)
212 controller->UpdateWindowInsets(window);
215 void WindowBoundsChangeObserver::OnWindowDestroyed(aura::Window* window) {
216 if (window->HasObserver(this))
217 window->RemoveObserver(this);
218 observed_windows_.erase(window);
221 void WindowBoundsChangeObserver::AddObservedWindow(aura::Window* window) {
222 if (!window->HasObserver(this)) {
223 window->AddObserver(this);
224 observed_windows_.insert(window);
228 void WindowBoundsChangeObserver::RemoveAllObservedWindows() {
229 for (std::set<aura::Window*>::iterator it = observed_windows_.begin();
230 it != observed_windows_.end(); ++it)
231 (*it)->RemoveObserver(this);
232 observed_windows_.clear();
235 // static
236 KeyboardController* KeyboardController::instance_ = NULL;
238 KeyboardController::KeyboardController(KeyboardControllerProxy* proxy)
239 : proxy_(proxy),
240 input_method_(NULL),
241 keyboard_visible_(false),
242 show_on_resize_(false),
243 lock_keyboard_(false),
244 type_(ui::TEXT_INPUT_TYPE_NONE),
245 weak_factory_(this) {
246 CHECK(proxy);
247 input_method_ = proxy_->GetInputMethod();
248 input_method_->AddObserver(this);
249 window_bounds_observer_.reset(new WindowBoundsChangeObserver());
252 KeyboardController::~KeyboardController() {
253 if (container_)
254 container_->RemoveObserver(this);
255 if (input_method_)
256 input_method_->RemoveObserver(this);
257 ResetWindowInsets();
260 // static
261 void KeyboardController::ResetInstance(KeyboardController* controller) {
262 if (instance_ && instance_ != controller)
263 delete instance_;
264 instance_ = controller;
267 // static
268 KeyboardController* KeyboardController::GetInstance() {
269 return instance_;
272 aura::Window* KeyboardController::GetContainerWindow() {
273 if (!container_.get()) {
274 container_.reset(new aura::Window(
275 new KeyboardWindowDelegate(proxy_.get())));
276 container_->SetEventTargeter(scoped_ptr<ui::EventTargeter>(
277 new KeyboardContainerTargeter(container_.get(), proxy_.get())));
278 container_->SetName("KeyboardContainer");
279 container_->set_owned_by_parent(false);
280 container_->Init(aura::WINDOW_LAYER_NOT_DRAWN);
281 container_->AddObserver(this);
282 container_->SetLayoutManager(new KeyboardLayoutManager(this));
284 return container_.get();
287 void KeyboardController::NotifyKeyboardBoundsChanging(
288 const gfx::Rect& new_bounds) {
289 current_keyboard_bounds_ = new_bounds;
290 if (proxy_->HasKeyboardWindow() && proxy_->GetKeyboardWindow()->IsVisible()) {
291 FOR_EACH_OBSERVER(KeyboardControllerObserver,
292 observer_list_,
293 OnKeyboardBoundsChanging(new_bounds));
294 if (keyboard::IsKeyboardOverscrollEnabled()) {
295 // Adjust the height of the viewport for visible windows on the primary
296 // display.
297 // TODO(kevers): Add EnvObserver to properly initialize insets if a
298 // window is created while the keyboard is visible.
299 scoped_ptr<content::RenderWidgetHostIterator> widgets(
300 content::RenderWidgetHost::GetRenderWidgetHosts());
301 aura::Window* keyboard_window = proxy_->GetKeyboardWindow();
302 aura::Window* root_window = keyboard_window->GetRootWindow();
303 while (content::RenderWidgetHost* widget = widgets->GetNextHost()) {
304 content::RenderWidgetHostView* view = widget->GetView();
305 // Can be NULL, e.g. if the RenderWidget is being destroyed or
306 // the render process crashed.
307 if (view) {
308 aura::Window* window = view->GetNativeView();
309 // If virtual keyboard failed to load, a widget that displays error
310 // message will be created and adds as a child of the virtual keyboard
311 // window. We want to avoid add BoundsChangedObserver to that window.
312 if (!keyboard_window->Contains(window) &&
313 window->GetRootWindow() == root_window) {
314 gfx::Rect window_bounds = window->GetBoundsInScreen();
315 gfx::Rect intersect = gfx::IntersectRects(window_bounds,
316 new_bounds);
317 int overlap = intersect.height();
318 if (overlap > 0 && overlap < window_bounds.height())
319 view->SetInsets(gfx::Insets(0, 0, overlap, 0));
320 else
321 view->SetInsets(gfx::Insets());
322 AddBoundsChangedObserver(window);
326 } else {
327 ResetWindowInsets();
329 } else {
330 current_keyboard_bounds_ = gfx::Rect();
334 void KeyboardController::HideKeyboard(HideReason reason) {
335 keyboard_visible_ = false;
336 ToggleTouchEventLogging(true);
338 keyboard::LogKeyboardControlEvent(
339 reason == HIDE_REASON_AUTOMATIC ?
340 keyboard::KEYBOARD_CONTROL_HIDE_AUTO :
341 keyboard::KEYBOARD_CONTROL_HIDE_USER);
343 NotifyKeyboardBoundsChanging(gfx::Rect());
345 set_lock_keyboard(false);
347 ui::LayerAnimator* container_animator = container_->layer()->GetAnimator();
348 animation_observer_.reset(new CallbackAnimationObserver(
349 container_animator,
350 base::Bind(&KeyboardController::HideAnimationFinished,
351 base::Unretained(this))));
352 container_animator->AddObserver(animation_observer_.get());
354 ui::ScopedLayerAnimationSettings settings(container_animator);
355 settings.SetTweenType(gfx::Tween::FAST_OUT_LINEAR_IN);
356 settings.SetTransitionDuration(
357 base::TimeDelta::FromMilliseconds(kHideAnimationDurationMs));
358 gfx::Transform transform;
359 transform.Translate(0, kAnimationDistance);
360 container_->SetTransform(transform);
361 container_->layer()->SetOpacity(kAnimationStartOrAfterHideOpacity);
364 void KeyboardController::AddObserver(KeyboardControllerObserver* observer) {
365 observer_list_.AddObserver(observer);
368 void KeyboardController::RemoveObserver(KeyboardControllerObserver* observer) {
369 observer_list_.RemoveObserver(observer);
372 void KeyboardController::ShowKeyboard(bool lock) {
373 set_lock_keyboard(lock);
374 ShowKeyboardInternal();
377 void KeyboardController::OnWindowHierarchyChanged(
378 const HierarchyChangeParams& params) {
379 if (params.new_parent && params.target == container_.get())
380 OnTextInputStateChanged(proxy_->GetInputMethod()->GetTextInputClient());
383 void KeyboardController::Reload() {
384 if (proxy_->HasKeyboardWindow()) {
385 // A reload should never try to show virtual keyboard. If keyboard is not
386 // visible before reload, it should keep invisible after reload.
387 show_on_resize_ = false;
388 proxy_->ReloadKeyboardIfNeeded();
392 void KeyboardController::OnTextInputStateChanged(
393 const ui::TextInputClient* client) {
394 if (!container_.get())
395 return;
397 type_ = client ? client->GetTextInputType() : ui::TEXT_INPUT_TYPE_NONE;
399 if (type_ == ui::TEXT_INPUT_TYPE_NONE && !lock_keyboard_) {
400 if (keyboard_visible_) {
401 // Set the visibility state here so that any queries for visibility
402 // before the timer fires returns the correct future value.
403 keyboard_visible_ = false;
404 base::MessageLoop::current()->PostDelayedTask(
405 FROM_HERE,
406 base::Bind(&KeyboardController::HideKeyboard,
407 weak_factory_.GetWeakPtr(), HIDE_REASON_AUTOMATIC),
408 base::TimeDelta::FromMilliseconds(kHideKeyboardDelayMs));
410 } else {
411 // Abort a pending keyboard hide.
412 if (WillHideKeyboard()) {
413 weak_factory_.InvalidateWeakPtrs();
414 keyboard_visible_ = true;
416 proxy_->SetUpdateInputType(type_);
417 // Do not explicitly show the Virtual keyboard unless it is in the process
418 // of hiding. Instead, the virtual keyboard is shown in response to a user
419 // gesture (mouse or touch) that is received while an element has input
420 // focus. Showing the keyboard requires an explicit call to
421 // OnShowImeIfNeeded.
425 void KeyboardController::OnInputMethodDestroyed(
426 const ui::InputMethod* input_method) {
427 DCHECK_EQ(input_method_, input_method);
428 input_method_ = NULL;
431 void KeyboardController::OnShowImeIfNeeded() {
432 ShowKeyboardInternal();
435 bool KeyboardController::ShouldEnableInsets(aura::Window* window) {
436 aura::Window *keyboard_window = proxy_->GetKeyboardWindow();
437 return (keyboard_window->GetRootWindow() == window->GetRootWindow() &&
438 keyboard::IsKeyboardOverscrollEnabled() &&
439 proxy_->GetKeyboardWindow()->IsVisible() &&
440 keyboard_visible_);
443 void KeyboardController::UpdateWindowInsets(aura::Window* window) {
444 aura::Window *keyboard_window = proxy_->GetKeyboardWindow();
445 if (window == keyboard_window)
446 return;
448 scoped_ptr<content::RenderWidgetHostIterator> widgets(
449 content::RenderWidgetHost::GetRenderWidgetHosts());
450 while (content::RenderWidgetHost* widget = widgets->GetNextHost()) {
451 content::RenderWidgetHostView* view = widget->GetView();
452 if (view && window->Contains(view->GetNativeView())) {
453 gfx::Rect window_bounds = view->GetNativeView()->GetBoundsInScreen();
454 gfx::Rect intersect = gfx::IntersectRects(window_bounds,
455 proxy_->GetKeyboardWindow()->bounds());
456 int overlap = ShouldEnableInsets(window) ? intersect.height() : 0;
457 if (overlap > 0 && overlap < window_bounds.height())
458 view->SetInsets(gfx::Insets(0, 0, overlap, 0));
459 else
460 view->SetInsets(gfx::Insets());
461 return;
466 void KeyboardController::ShowKeyboardInternal() {
467 if (!container_.get())
468 return;
470 if (container_->children().empty()) {
471 keyboard::MarkKeyboardLoadStarted();
472 aura::Window* keyboard = proxy_->GetKeyboardWindow();
473 keyboard->Show();
474 container_->AddChild(keyboard);
475 keyboard->set_owned_by_parent(false);
478 proxy_->ReloadKeyboardIfNeeded();
480 if (keyboard_visible_) {
481 return;
482 } else if (proxy_->GetKeyboardWindow()->bounds().height() == 0) {
483 show_on_resize_ = true;
484 return;
487 keyboard_visible_ = true;
489 // If the controller is in the process of hiding the keyboard, do not log
490 // the stat here since the keyboard will not actually be shown.
491 if (!WillHideKeyboard())
492 keyboard::LogKeyboardControlEvent(keyboard::KEYBOARD_CONTROL_SHOW);
494 weak_factory_.InvalidateWeakPtrs();
496 // If |container_| has hide animation, its visibility is set to false when
497 // hide animation finished. So even if the container is visible at this
498 // point, it may in the process of hiding. We still need to show keyboard
499 // container in this case.
500 if (container_->IsVisible() &&
501 !container_->layer()->GetAnimator()->is_animating())
502 return;
504 ToggleTouchEventLogging(false);
505 ui::LayerAnimator* container_animator = container_->layer()->GetAnimator();
507 // If the container is not animating, makes sure the position and opacity
508 // are at begin states for animation.
509 if (!container_animator->is_animating()) {
510 gfx::Transform transform;
511 transform.Translate(0, kAnimationDistance);
512 container_->SetTransform(transform);
513 container_->layer()->SetOpacity(kAnimationStartOrAfterHideOpacity);
516 container_animator->set_preemption_strategy(
517 ui::LayerAnimator::IMMEDIATELY_ANIMATE_TO_NEW_TARGET);
518 animation_observer_.reset(new CallbackAnimationObserver(
519 container_animator,
520 base::Bind(&KeyboardController::ShowAnimationFinished,
521 base::Unretained(this))));
522 container_animator->AddObserver(animation_observer_.get());
524 proxy_->ShowKeyboardContainer(container_.get());
527 // Scope the following animation settings as we don't want to animate
528 // visibility change that triggered by a call to the base class function
529 // ShowKeyboardContainer with these settings. The container should become
530 // visible immediately.
531 ui::ScopedLayerAnimationSettings settings(container_animator);
532 settings.SetTweenType(gfx::Tween::LINEAR_OUT_SLOW_IN);
533 settings.SetTransitionDuration(
534 base::TimeDelta::FromMilliseconds(kShowAnimationDurationMs));
535 container_->SetTransform(gfx::Transform());
536 container_->layer()->SetOpacity(1.0);
540 void KeyboardController::ResetWindowInsets() {
541 const gfx::Insets insets;
542 scoped_ptr<content::RenderWidgetHostIterator> widgets(
543 content::RenderWidgetHost::GetRenderWidgetHosts());
544 while (content::RenderWidgetHost* widget = widgets->GetNextHost()) {
545 content::RenderWidgetHostView* view = widget->GetView();
546 if (view)
547 view->SetInsets(insets);
549 window_bounds_observer_->RemoveAllObservedWindows();
552 bool KeyboardController::WillHideKeyboard() const {
553 return weak_factory_.HasWeakPtrs();
556 void KeyboardController::ShowAnimationFinished() {
557 // Notify observers after animation finished to prevent reveal desktop
558 // background during animation.
559 NotifyKeyboardBoundsChanging(proxy_->GetKeyboardWindow()->bounds());
560 proxy_->EnsureCaretInWorkArea();
563 void KeyboardController::HideAnimationFinished() {
564 proxy_->HideKeyboardContainer(container_.get());
567 void KeyboardController::AddBoundsChangedObserver(aura::Window* window) {
568 aura::Window* target_window = window ? window->GetToplevelWindow() : nullptr;
569 if (target_window)
570 window_bounds_observer_->AddObservedWindow(target_window);
573 } // namespace keyboard