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"
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"
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 {
54 KeyboardContainerTargeter(aura::Window* container,
55 keyboard::KeyboardControllerProxy* proxy)
56 : wm::MaskedWindowTargeter(container),
60 ~KeyboardContainerTargeter() override {}
63 // wm::MaskedWindowTargeter:
64 bool GetHitTestMask(aura::Window* window, gfx::Path* mask) const override {
65 if (proxy_ && !proxy_->HasKeyboardWindow())
67 gfx::Rect keyboard_bounds = proxy_ ? proxy_->GetKeyboardWindow()->bounds() :
68 keyboard::DefaultKeyboardBoundsFromWindowBounds(window->bounds());
69 mask->addRect(RectToSkRect(keyboard_bounds));
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
81 // The delegate deletes itself when the window is destroyed.
82 class KeyboardWindowDelegate : public aura::WindowDelegate {
84 explicit KeyboardWindowDelegate(keyboard::KeyboardControllerProxy* proxy)
86 ~KeyboardWindowDelegate() override {}
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 {
96 gfx::NativeCursor GetCursor(const gfx::Point& point) override {
97 return gfx::kNullCursor;
99 int GetNonClientComponent(const gfx::Point& point) const override {
102 bool ShouldDescendIntoChildForEventHandling(
104 const gfx::Point& location) override {
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())
120 gfx::Rect keyboard_bounds = proxy_ ? proxy_->GetKeyboardWindow()->bounds() :
121 keyboard::DefaultKeyboardBoundsFromWindowBounds(bounds_);
122 mask->addRect(RectToSkRect(keyboard_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())
136 base::FilePath("/opt/google/touchscreen/toggle_touch_event_logging"));
138 command.AppendArg("1");
140 command.AppendArg("0");
141 VLOG(1) << "Running " << command.GetCommandLineString();
142 base::LaunchOptions options;
144 base::LaunchProcess(command, options, NULL);
148 aura::Window *GetFrameWindow(aura::Window *window) {
149 // Each container window has a non-negative id. Stop traversing at the child
150 // of a container window.
153 while (window->parent() && window->parent()->id() < 0) {
154 window = window->parent();
163 // Observer for both keyboard show and hide animations. It should be owned by
164 // KeyboardController.
165 class CallbackAnimationObserver : public ui::LayerAnimationObserver {
167 CallbackAnimationObserver(ui::LayerAnimator* animator,
168 base::Callback<void(void)> callback);
169 ~CallbackAnimationObserver() override;
172 // Overridden from ui::LayerAnimationObserver:
173 void OnLayerAnimationEnded(ui::LayerAnimationSequence* seq) override;
174 void OnLayerAnimationAborted(ui::LayerAnimationSequence* seq) override;
175 void OnLayerAnimationScheduled(ui::LayerAnimationSequence* seq) override {}
177 ui::LayerAnimator* animator_;
178 base::Callback<void(void)> callback_;
180 DISALLOW_COPY_AND_ASSIGN(CallbackAnimationObserver);
183 CallbackAnimationObserver::CallbackAnimationObserver(
184 ui::LayerAnimator* animator, base::Callback<void(void)> callback)
185 : animator_(animator), callback_(callback) {
188 CallbackAnimationObserver::~CallbackAnimationObserver() {
189 animator_->RemoveObserver(this);
192 void CallbackAnimationObserver::OnLayerAnimationEnded(
193 ui::LayerAnimationSequence* seq) {
194 if (animator_->is_animating())
196 animator_->RemoveObserver(this);
200 void CallbackAnimationObserver::OnLayerAnimationAborted(
201 ui::LayerAnimationSequence* seq) {
202 animator_->RemoveObserver(this);
205 class WindowBoundsChangeObserver : public aura::WindowObserver {
207 void OnWindowBoundsChanged(aura::Window* window,
208 const gfx::Rect& old_bounds,
209 const gfx::Rect& new_bounds) override;
210 void OnWindowDestroyed(aura::Window* window) override;
212 void AddObservedWindow(aura::Window* window);
213 void RemoveAllObservedWindows();
216 std::set<aura::Window*> observed_windows_;
219 void WindowBoundsChangeObserver::OnWindowBoundsChanged(aura::Window* window,
220 const gfx::Rect& old_bounds, const gfx::Rect& new_bounds) {
221 KeyboardController* controller = KeyboardController::GetInstance();
223 controller->UpdateWindowInsets(window);
226 void WindowBoundsChangeObserver::OnWindowDestroyed(aura::Window* window) {
227 if (window->HasObserver(this))
228 window->RemoveObserver(this);
229 observed_windows_.erase(window);
232 void WindowBoundsChangeObserver::AddObservedWindow(aura::Window* window) {
233 if (!window->HasObserver(this)) {
234 window->AddObserver(this);
235 observed_windows_.insert(window);
239 void WindowBoundsChangeObserver::RemoveAllObservedWindows() {
240 for (std::set<aura::Window*>::iterator it = observed_windows_.begin();
241 it != observed_windows_.end(); ++it)
242 (*it)->RemoveObserver(this);
243 observed_windows_.clear();
247 KeyboardController* KeyboardController::instance_ = NULL;
249 KeyboardController::KeyboardController(KeyboardControllerProxy* proxy)
252 keyboard_visible_(false),
253 show_on_resize_(false),
254 lock_keyboard_(false),
255 type_(ui::TEXT_INPUT_TYPE_NONE),
256 weak_factory_(this) {
258 input_method_ = proxy_->GetInputMethod();
259 input_method_->AddObserver(this);
260 window_bounds_observer_.reset(new WindowBoundsChangeObserver());
263 KeyboardController::~KeyboardController() {
265 container_->RemoveObserver(this);
267 input_method_->RemoveObserver(this);
272 void KeyboardController::ResetInstance(KeyboardController* controller) {
273 if (instance_ && instance_ != controller)
275 instance_ = controller;
279 KeyboardController* KeyboardController::GetInstance() {
283 aura::Window* KeyboardController::GetContainerWindow() {
284 if (!container_.get()) {
285 container_.reset(new aura::Window(
286 new KeyboardWindowDelegate(proxy_.get())));
287 container_->SetEventTargeter(scoped_ptr<ui::EventTargeter>(
288 new KeyboardContainerTargeter(container_.get(), proxy_.get())));
289 container_->SetName("KeyboardContainer");
290 container_->set_owned_by_parent(false);
291 container_->Init(aura::WINDOW_LAYER_NOT_DRAWN);
292 container_->AddObserver(this);
293 container_->SetLayoutManager(new KeyboardLayoutManager(this));
295 return container_.get();
298 void KeyboardController::NotifyKeyboardBoundsChanging(
299 const gfx::Rect& new_bounds) {
300 current_keyboard_bounds_ = new_bounds;
301 if (proxy_->HasKeyboardWindow() && proxy_->GetKeyboardWindow()->IsVisible()) {
302 FOR_EACH_OBSERVER(KeyboardControllerObserver,
304 OnKeyboardBoundsChanging(new_bounds));
305 if (keyboard::IsKeyboardOverscrollEnabled()) {
306 // Adjust the height of the viewport for visible windows on the primary
308 // TODO(kevers): Add EnvObserver to properly initialize insets if a
309 // window is created while the keyboard is visible.
310 scoped_ptr<content::RenderWidgetHostIterator> widgets(
311 content::RenderWidgetHost::GetRenderWidgetHosts());
312 aura::Window *keyboard_window = proxy_->GetKeyboardWindow();
313 aura::Window *root_window = keyboard_window->GetRootWindow();
314 while (content::RenderWidgetHost* widget = widgets->GetNextHost()) {
315 content::RenderWidgetHostView* view = widget->GetView();
316 // Can be NULL, e.g. if the RenderWidget is being destroyed or
317 // the render process crashed.
319 aura::Window *window = view->GetNativeView();
320 // If virtual keyboard failed to load, a widget that displays error
321 // message will be created and adds as a child of the virtual keyboard
322 // window. We want to avoid add BoundsChangedObserver to that window.
323 if (GetFrameWindow(window) != keyboard_window &&
324 window->GetRootWindow() == root_window) {
325 gfx::Rect window_bounds = window->GetBoundsInScreen();
326 gfx::Rect intersect = gfx::IntersectRects(window_bounds,
328 int overlap = intersect.height();
329 if (overlap > 0 && overlap < window_bounds.height())
330 view->SetInsets(gfx::Insets(0, 0, overlap, 0));
332 view->SetInsets(gfx::Insets());
333 AddBoundsChangedObserver(window);
341 current_keyboard_bounds_ = gfx::Rect();
345 void KeyboardController::HideKeyboard(HideReason reason) {
346 keyboard_visible_ = false;
347 ToggleTouchEventLogging(true);
349 keyboard::LogKeyboardControlEvent(
350 reason == HIDE_REASON_AUTOMATIC ?
351 keyboard::KEYBOARD_CONTROL_HIDE_AUTO :
352 keyboard::KEYBOARD_CONTROL_HIDE_USER);
354 NotifyKeyboardBoundsChanging(gfx::Rect());
356 set_lock_keyboard(false);
358 ui::LayerAnimator* container_animator = container_->layer()->GetAnimator();
359 animation_observer_.reset(new CallbackAnimationObserver(
361 base::Bind(&KeyboardController::HideAnimationFinished,
362 base::Unretained(this))));
363 container_animator->AddObserver(animation_observer_.get());
365 ui::ScopedLayerAnimationSettings settings(container_animator);
366 settings.SetTweenType(gfx::Tween::FAST_OUT_LINEAR_IN);
367 settings.SetTransitionDuration(
368 base::TimeDelta::FromMilliseconds(kHideAnimationDurationMs));
369 gfx::Transform transform;
370 transform.Translate(0, kAnimationDistance);
371 container_->SetTransform(transform);
372 container_->layer()->SetOpacity(kAnimationStartOrAfterHideOpacity);
375 void KeyboardController::AddObserver(KeyboardControllerObserver* observer) {
376 observer_list_.AddObserver(observer);
379 void KeyboardController::RemoveObserver(KeyboardControllerObserver* observer) {
380 observer_list_.RemoveObserver(observer);
383 void KeyboardController::ShowKeyboard(bool lock) {
384 set_lock_keyboard(lock);
385 ShowKeyboardInternal();
388 void KeyboardController::OnWindowHierarchyChanged(
389 const HierarchyChangeParams& params) {
390 if (params.new_parent && params.target == container_.get())
391 OnTextInputStateChanged(proxy_->GetInputMethod()->GetTextInputClient());
394 void KeyboardController::Reload() {
395 if (proxy_->HasKeyboardWindow()) {
396 // A reload should never try to show virtual keyboard. If keyboard is not
397 // visible before reload, it should keep invisible after reload.
398 show_on_resize_ = false;
399 proxy_->ReloadKeyboardIfNeeded();
403 void KeyboardController::OnTextInputStateChanged(
404 const ui::TextInputClient* client) {
405 if (!container_.get())
408 type_ = client ? client->GetTextInputType() : ui::TEXT_INPUT_TYPE_NONE;
410 if (type_ == ui::TEXT_INPUT_TYPE_NONE && !lock_keyboard_) {
411 if (keyboard_visible_) {
412 // Set the visibility state here so that any queries for visibility
413 // before the timer fires returns the correct future value.
414 keyboard_visible_ = false;
415 base::MessageLoop::current()->PostDelayedTask(
417 base::Bind(&KeyboardController::HideKeyboard,
418 weak_factory_.GetWeakPtr(), HIDE_REASON_AUTOMATIC),
419 base::TimeDelta::FromMilliseconds(kHideKeyboardDelayMs));
422 // Abort a pending keyboard hide.
423 if (WillHideKeyboard()) {
424 weak_factory_.InvalidateWeakPtrs();
425 keyboard_visible_ = true;
427 proxy_->SetUpdateInputType(type_);
428 // Do not explicitly show the Virtual keyboard unless it is in the process
429 // of hiding. Instead, the virtual keyboard is shown in response to a user
430 // gesture (mouse or touch) that is received while an element has input
431 // focus. Showing the keyboard requires an explicit call to
432 // OnShowImeIfNeeded.
436 void KeyboardController::OnInputMethodDestroyed(
437 const ui::InputMethod* input_method) {
438 DCHECK_EQ(input_method_, input_method);
439 input_method_ = NULL;
442 void KeyboardController::OnShowImeIfNeeded() {
443 ShowKeyboardInternal();
446 bool KeyboardController::ShouldEnableInsets(aura::Window* window) {
447 aura::Window *keyboard_window = proxy_->GetKeyboardWindow();
448 return (keyboard_window->GetRootWindow() == window->GetRootWindow() &&
449 keyboard::IsKeyboardOverscrollEnabled() &&
450 proxy_->GetKeyboardWindow()->IsVisible() &&
454 void KeyboardController::UpdateWindowInsets(aura::Window* window) {
455 aura::Window *keyboard_window = proxy_->GetKeyboardWindow();
456 if (window == keyboard_window)
459 scoped_ptr<content::RenderWidgetHostIterator> widgets(
460 content::RenderWidgetHost::GetRenderWidgetHosts());
461 while (content::RenderWidgetHost* widget = widgets->GetNextHost()) {
462 content::RenderWidgetHostView* view = widget->GetView();
463 if (view && window->Contains(view->GetNativeView())) {
464 gfx::Rect window_bounds = view->GetNativeView()->GetBoundsInScreen();
465 gfx::Rect intersect = gfx::IntersectRects(window_bounds,
466 proxy_->GetKeyboardWindow()->bounds());
467 int overlap = ShouldEnableInsets(window) ? intersect.height() : 0;
468 if (overlap > 0 && overlap < window_bounds.height())
469 view->SetInsets(gfx::Insets(0, 0, overlap, 0));
471 view->SetInsets(gfx::Insets());
477 void KeyboardController::ShowKeyboardInternal() {
478 if (!container_.get())
481 if (container_->children().empty()) {
482 keyboard::MarkKeyboardLoadStarted();
483 aura::Window* keyboard = proxy_->GetKeyboardWindow();
485 container_->AddChild(keyboard);
486 keyboard->set_owned_by_parent(false);
489 proxy_->ReloadKeyboardIfNeeded();
491 if (keyboard_visible_) {
493 } else if (proxy_->GetKeyboardWindow()->bounds().height() == 0) {
494 show_on_resize_ = true;
498 keyboard_visible_ = true;
500 // If the controller is in the process of hiding the keyboard, do not log
501 // the stat here since the keyboard will not actually be shown.
502 if (!WillHideKeyboard())
503 keyboard::LogKeyboardControlEvent(keyboard::KEYBOARD_CONTROL_SHOW);
505 weak_factory_.InvalidateWeakPtrs();
507 // If |container_| has hide animation, its visibility is set to false when
508 // hide animation finished. So even if the container is visible at this
509 // point, it may in the process of hiding. We still need to show keyboard
510 // container in this case.
511 if (container_->IsVisible() &&
512 !container_->layer()->GetAnimator()->is_animating())
515 ToggleTouchEventLogging(false);
516 ui::LayerAnimator* container_animator = container_->layer()->GetAnimator();
518 // If the container is not animating, makes sure the position and opacity
519 // are at begin states for animation.
520 if (!container_animator->is_animating()) {
521 gfx::Transform transform;
522 transform.Translate(0, kAnimationDistance);
523 container_->SetTransform(transform);
524 container_->layer()->SetOpacity(kAnimationStartOrAfterHideOpacity);
527 container_animator->set_preemption_strategy(
528 ui::LayerAnimator::IMMEDIATELY_ANIMATE_TO_NEW_TARGET);
529 animation_observer_.reset(new CallbackAnimationObserver(
531 base::Bind(&KeyboardController::ShowAnimationFinished,
532 base::Unretained(this))));
533 container_animator->AddObserver(animation_observer_.get());
535 proxy_->ShowKeyboardContainer(container_.get());
538 // Scope the following animation settings as we don't want to animate
539 // visibility change that triggered by a call to the base class function
540 // ShowKeyboardContainer with these settings. The container should become
541 // visible immediately.
542 ui::ScopedLayerAnimationSettings settings(container_animator);
543 settings.SetTweenType(gfx::Tween::LINEAR_OUT_SLOW_IN);
544 settings.SetTransitionDuration(
545 base::TimeDelta::FromMilliseconds(kShowAnimationDurationMs));
546 container_->SetTransform(gfx::Transform());
547 container_->layer()->SetOpacity(1.0);
551 void KeyboardController::ResetWindowInsets() {
552 const gfx::Insets insets;
553 scoped_ptr<content::RenderWidgetHostIterator> widgets(
554 content::RenderWidgetHost::GetRenderWidgetHosts());
555 while (content::RenderWidgetHost* widget = widgets->GetNextHost()) {
556 content::RenderWidgetHostView* view = widget->GetView();
558 view->SetInsets(insets);
560 window_bounds_observer_->RemoveAllObservedWindows();
563 bool KeyboardController::WillHideKeyboard() const {
564 return weak_factory_.HasWeakPtrs();
567 void KeyboardController::ShowAnimationFinished() {
568 // Notify observers after animation finished to prevent reveal desktop
569 // background during animation.
570 NotifyKeyboardBoundsChanging(proxy_->GetKeyboardWindow()->bounds());
571 proxy_->EnsureCaretInWorkArea();
574 void KeyboardController::HideAnimationFinished() {
575 proxy_->HideKeyboardContainer(container_.get());
578 void KeyboardController::AddBoundsChangedObserver(aura::Window* window) {
579 aura::Window* target_window = GetFrameWindow(window);
581 window_bounds_observer_->AddObservedWindow(target_window);
584 } // namespace keyboard