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/geometry/rect.h"
24 #include "ui/gfx/path.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 // The KeyboardWindowDelegate makes sure the keyboard-window does not get focus.
52 // This is necessary to make sure that the synthetic key-events reach the target
54 // The delegate deletes itself when the window is destroyed.
55 class KeyboardWindowDelegate
: public aura::WindowDelegate
{
57 KeyboardWindowDelegate() {}
58 ~KeyboardWindowDelegate() override
{}
61 // Overridden from aura::WindowDelegate:
62 gfx::Size
GetMinimumSize() const override
{ return gfx::Size(); }
63 gfx::Size
GetMaximumSize() const override
{ return gfx::Size(); }
64 void OnBoundsChanged(const gfx::Rect
& old_bounds
,
65 const gfx::Rect
& new_bounds
) override
{}
66 ui::TextInputClient
* GetFocusedTextInputClient() override
{
69 gfx::NativeCursor
GetCursor(const gfx::Point
& point
) override
{
70 return gfx::kNullCursor
;
72 int GetNonClientComponent(const gfx::Point
& point
) const override
{
75 bool ShouldDescendIntoChildForEventHandling(
77 const gfx::Point
& location
) override
{
80 bool CanFocus() override
{ return false; }
81 void OnCaptureLost() override
{}
82 void OnPaint(const ui::PaintContext
& context
) override
{}
83 void OnDeviceScaleFactorChanged(float device_scale_factor
) override
{}
84 void OnWindowDestroying(aura::Window
* window
) override
{}
85 void OnWindowDestroyed(aura::Window
* window
) override
{ delete this; }
86 void OnWindowTargetVisibilityChanged(bool visible
) override
{}
87 bool HasHitTestMask() const override
{ return false; }
88 void GetHitTestMask(gfx::Path
* mask
) const override
{}
90 DISALLOW_COPY_AND_ASSIGN(KeyboardWindowDelegate
);
93 void ToggleTouchEventLogging(bool enable
) {
94 #if defined(OS_CHROMEOS)
95 if (!base::SysInfo::IsRunningOnChromeOS())
97 base::CommandLine
command(
98 base::FilePath("/opt/google/touchscreen/toggle_touch_event_logging"));
100 command
.AppendArg("1");
102 command
.AppendArg("0");
103 VLOG(1) << "Running " << command
.GetCommandLineString();
104 base::LaunchOptions options
;
106 base::LaunchProcess(command
, options
);
114 // Observer for both keyboard show and hide animations. It should be owned by
115 // KeyboardController.
116 class CallbackAnimationObserver
: public ui::LayerAnimationObserver
{
118 CallbackAnimationObserver(const scoped_refptr
<ui::LayerAnimator
>& animator
,
119 base::Callback
<void(void)> callback
);
120 ~CallbackAnimationObserver() override
;
123 // Overridden from ui::LayerAnimationObserver:
124 void OnLayerAnimationEnded(ui::LayerAnimationSequence
* seq
) override
;
125 void OnLayerAnimationAborted(ui::LayerAnimationSequence
* seq
) override
;
126 void OnLayerAnimationScheduled(ui::LayerAnimationSequence
* seq
) override
{}
128 scoped_refptr
<ui::LayerAnimator
> animator_
;
129 base::Callback
<void(void)> callback_
;
131 DISALLOW_COPY_AND_ASSIGN(CallbackAnimationObserver
);
134 CallbackAnimationObserver::CallbackAnimationObserver(
135 const scoped_refptr
<ui::LayerAnimator
>& animator
,
136 base::Callback
<void(void)> callback
)
137 : animator_(animator
), callback_(callback
) {
140 CallbackAnimationObserver::~CallbackAnimationObserver() {
141 animator_
->RemoveObserver(this);
144 void CallbackAnimationObserver::OnLayerAnimationEnded(
145 ui::LayerAnimationSequence
* seq
) {
146 if (animator_
->is_animating())
148 animator_
->RemoveObserver(this);
152 void CallbackAnimationObserver::OnLayerAnimationAborted(
153 ui::LayerAnimationSequence
* seq
) {
154 animator_
->RemoveObserver(this);
157 class WindowBoundsChangeObserver
: public aura::WindowObserver
{
159 void OnWindowBoundsChanged(aura::Window
* window
,
160 const gfx::Rect
& old_bounds
,
161 const gfx::Rect
& new_bounds
) override
;
162 void OnWindowDestroyed(aura::Window
* window
) override
;
164 void AddObservedWindow(aura::Window
* window
);
165 void RemoveAllObservedWindows();
168 std::set
<aura::Window
*> observed_windows_
;
171 void WindowBoundsChangeObserver::OnWindowBoundsChanged(aura::Window
* window
,
172 const gfx::Rect
& old_bounds
, const gfx::Rect
& new_bounds
) {
173 KeyboardController
* controller
= KeyboardController::GetInstance();
175 controller
->UpdateWindowInsets(window
);
178 void WindowBoundsChangeObserver::OnWindowDestroyed(aura::Window
* window
) {
179 if (window
->HasObserver(this))
180 window
->RemoveObserver(this);
181 observed_windows_
.erase(window
);
184 void WindowBoundsChangeObserver::AddObservedWindow(aura::Window
* window
) {
185 if (!window
->HasObserver(this)) {
186 window
->AddObserver(this);
187 observed_windows_
.insert(window
);
191 void WindowBoundsChangeObserver::RemoveAllObservedWindows() {
192 for (std::set
<aura::Window
*>::iterator it
= observed_windows_
.begin();
193 it
!= observed_windows_
.end(); ++it
)
194 (*it
)->RemoveObserver(this);
195 observed_windows_
.clear();
199 KeyboardController
* KeyboardController::instance_
= NULL
;
201 KeyboardController::KeyboardController(KeyboardControllerProxy
* proxy
)
204 keyboard_visible_(false),
205 show_on_resize_(false),
206 lock_keyboard_(false),
207 keyboard_mode_(FULL_WIDTH
),
208 type_(ui::TEXT_INPUT_TYPE_NONE
),
209 weak_factory_(this) {
211 input_method_
= proxy_
->GetInputMethod();
212 input_method_
->AddObserver(this);
213 window_bounds_observer_
.reset(new WindowBoundsChangeObserver());
216 KeyboardController::~KeyboardController() {
218 if (container_
->GetRootWindow())
219 container_
->GetRootWindow()->RemoveObserver(this);
220 container_
->RemoveObserver(this);
223 input_method_
->RemoveObserver(this);
228 void KeyboardController::ResetInstance(KeyboardController
* controller
) {
229 if (instance_
&& instance_
!= controller
)
231 instance_
= controller
;
235 KeyboardController
* KeyboardController::GetInstance() {
239 aura::Window
* KeyboardController::GetContainerWindow() {
240 if (!container_
.get()) {
241 container_
.reset(new aura::Window(new KeyboardWindowDelegate()));
242 container_
->SetName("KeyboardContainer");
243 container_
->set_owned_by_parent(false);
244 container_
->Init(ui::LAYER_NOT_DRAWN
);
245 container_
->AddObserver(this);
246 container_
->SetLayoutManager(new KeyboardLayoutManager(this));
248 return container_
.get();
251 void KeyboardController::NotifyKeyboardBoundsChanging(
252 const gfx::Rect
& new_bounds
) {
253 current_keyboard_bounds_
= new_bounds
;
254 if (proxy_
->HasKeyboardWindow() && proxy_
->GetKeyboardWindow()->IsVisible()) {
255 FOR_EACH_OBSERVER(KeyboardControllerObserver
,
257 OnKeyboardBoundsChanging(new_bounds
));
258 if (keyboard::IsKeyboardOverscrollEnabled()) {
259 // Adjust the height of the viewport for visible windows on the primary
261 // TODO(kevers): Add EnvObserver to properly initialize insets if a
262 // window is created while the keyboard is visible.
263 scoped_ptr
<content::RenderWidgetHostIterator
> widgets(
264 content::RenderWidgetHost::GetRenderWidgetHosts());
265 aura::Window
* keyboard_window
= proxy_
->GetKeyboardWindow();
266 aura::Window
* root_window
= keyboard_window
->GetRootWindow();
267 while (content::RenderWidgetHost
* widget
= widgets
->GetNextHost()) {
268 content::RenderWidgetHostView
* view
= widget
->GetView();
269 // Can be NULL, e.g. if the RenderWidget is being destroyed or
270 // the render process crashed.
272 aura::Window
* window
= view
->GetNativeView();
273 // If virtual keyboard failed to load, a widget that displays error
274 // message will be created and adds as a child of the virtual keyboard
275 // window. We want to avoid add BoundsChangedObserver to that window.
276 if (!keyboard_window
->Contains(window
) &&
277 window
->GetRootWindow() == root_window
) {
278 gfx::Rect window_bounds
= window
->GetBoundsInScreen();
279 gfx::Rect intersect
= gfx::IntersectRects(window_bounds
,
281 int overlap
= intersect
.height();
282 if (overlap
> 0 && overlap
< window_bounds
.height())
283 view
->SetInsets(gfx::Insets(0, 0, overlap
, 0));
285 view
->SetInsets(gfx::Insets());
286 AddBoundsChangedObserver(window
);
294 current_keyboard_bounds_
= gfx::Rect();
298 void KeyboardController::HideKeyboard(HideReason reason
) {
299 keyboard_visible_
= false;
300 ToggleTouchEventLogging(true);
302 keyboard::LogKeyboardControlEvent(
303 reason
== HIDE_REASON_AUTOMATIC
?
304 keyboard::KEYBOARD_CONTROL_HIDE_AUTO
:
305 keyboard::KEYBOARD_CONTROL_HIDE_USER
);
307 NotifyKeyboardBoundsChanging(gfx::Rect());
309 set_lock_keyboard(false);
311 ui::LayerAnimator
* container_animator
= container_
->layer()->GetAnimator();
312 animation_observer_
.reset(new CallbackAnimationObserver(
314 base::Bind(&KeyboardController::HideAnimationFinished
,
315 base::Unretained(this))));
316 container_animator
->AddObserver(animation_observer_
.get());
318 ui::ScopedLayerAnimationSettings
settings(container_animator
);
319 settings
.SetTweenType(gfx::Tween::FAST_OUT_LINEAR_IN
);
320 settings
.SetTransitionDuration(
321 base::TimeDelta::FromMilliseconds(kHideAnimationDurationMs
));
322 gfx::Transform transform
;
323 transform
.Translate(0, kAnimationDistance
);
324 container_
->SetTransform(transform
);
325 container_
->layer()->SetOpacity(kAnimationStartOrAfterHideOpacity
);
328 void KeyboardController::AddObserver(KeyboardControllerObserver
* observer
) {
329 observer_list_
.AddObserver(observer
);
332 void KeyboardController::RemoveObserver(KeyboardControllerObserver
* observer
) {
333 observer_list_
.RemoveObserver(observer
);
336 void KeyboardController::SetKeyboardMode(KeyboardMode mode
) {
337 if (keyboard_mode_
== mode
)
340 keyboard_mode_
= mode
;
341 // When keyboard is floating, no overscroll or resize is necessary. Sets
342 // keyboard bounds to zero so overscroll or resize is disabled.
343 if (keyboard_mode_
== FLOATING
) {
344 NotifyKeyboardBoundsChanging(gfx::Rect());
345 } else if (keyboard_mode_
== FULL_WIDTH
) {
346 // TODO(bshe): handle switch to FULL_WIDTH from FLOATING mode. We need a way
347 // to know the height of virtual keyboard in FULL_WIDTH mode before here.
351 void KeyboardController::ShowKeyboard(bool lock
) {
352 set_lock_keyboard(lock
);
353 ShowKeyboardInternal();
356 void KeyboardController::OnWindowHierarchyChanged(
357 const HierarchyChangeParams
& params
) {
358 if (params
.new_parent
&& params
.target
== container_
.get())
359 OnTextInputStateChanged(proxy_
->GetInputMethod()->GetTextInputClient());
362 void KeyboardController::OnWindowAddedToRootWindow(aura::Window
* window
) {
363 if (!window
->GetRootWindow()->HasObserver(this))
364 window
->GetRootWindow()->AddObserver(this);
367 void KeyboardController::OnWindowRemovingFromRootWindow(aura::Window
* window
,
368 aura::Window
* new_root
) {
369 if (window
->GetRootWindow()->HasObserver(this))
370 window
->GetRootWindow()->RemoveObserver(this);
373 void KeyboardController::OnWindowBoundsChanged(aura::Window
* window
,
374 const gfx::Rect
& old_bounds
,
375 const gfx::Rect
& new_bounds
) {
376 if (!window
->IsRootWindow())
378 // Keep the same height when window resize. It gets called when screen
380 if (!keyboard_container_initialized() || !proxy_
->HasKeyboardWindow())
383 int container_height
= container_
->bounds().height();
384 if (keyboard_mode_
== FULL_WIDTH
) {
385 container_
->SetBounds(gfx::Rect(new_bounds
.x(),
386 new_bounds
.bottom() - container_height
,
389 } else if (keyboard_mode_
== FLOATING
) {
390 // When screen rotate, horizontally center floating virtual keyboard
391 // window and vertically align it to the bottom.
392 int container_width
= container_
->bounds().width();
393 container_
->SetBounds(gfx::Rect(
394 new_bounds
.x() + (new_bounds
.width() - container_width
) / 2,
395 new_bounds
.bottom() - container_height
,
401 void KeyboardController::Reload() {
402 if (proxy_
->HasKeyboardWindow()) {
403 // A reload should never try to show virtual keyboard. If keyboard is not
404 // visible before reload, it should keep invisible after reload.
405 show_on_resize_
= false;
406 proxy_
->ReloadKeyboardIfNeeded();
410 void KeyboardController::OnTextInputStateChanged(
411 const ui::TextInputClient
* client
) {
412 if (!container_
.get())
415 type_
= client
? client
->GetTextInputType() : ui::TEXT_INPUT_TYPE_NONE
;
417 if (type_
== ui::TEXT_INPUT_TYPE_NONE
&& !lock_keyboard_
) {
418 if (keyboard_visible_
) {
419 // Set the visibility state here so that any queries for visibility
420 // before the timer fires returns the correct future value.
421 keyboard_visible_
= false;
422 base::MessageLoop::current()->PostDelayedTask(
424 base::Bind(&KeyboardController::HideKeyboard
,
425 weak_factory_
.GetWeakPtr(), HIDE_REASON_AUTOMATIC
),
426 base::TimeDelta::FromMilliseconds(kHideKeyboardDelayMs
));
429 // Abort a pending keyboard hide.
430 if (WillHideKeyboard()) {
431 weak_factory_
.InvalidateWeakPtrs();
432 keyboard_visible_
= true;
434 proxy_
->SetUpdateInputType(type_
);
435 // Do not explicitly show the Virtual keyboard unless it is in the process
436 // of hiding. Instead, the virtual keyboard is shown in response to a user
437 // gesture (mouse or touch) that is received while an element has input
438 // focus. Showing the keyboard requires an explicit call to
439 // OnShowImeIfNeeded.
443 void KeyboardController::OnInputMethodDestroyed(
444 const ui::InputMethod
* input_method
) {
445 DCHECK_EQ(input_method_
, input_method
);
446 input_method_
= NULL
;
449 void KeyboardController::OnShowImeIfNeeded() {
450 ShowKeyboardInternal();
453 bool KeyboardController::ShouldEnableInsets(aura::Window
* window
) {
454 aura::Window
* keyboard_window
= proxy_
->GetKeyboardWindow();
455 return (keyboard_window
->GetRootWindow() == window
->GetRootWindow() &&
456 keyboard::IsKeyboardOverscrollEnabled() &&
457 keyboard_window
->IsVisible() && keyboard_visible_
);
460 void KeyboardController::UpdateWindowInsets(aura::Window
* window
) {
461 aura::Window
* keyboard_window
= proxy_
->GetKeyboardWindow();
462 if (window
== keyboard_window
)
465 scoped_ptr
<content::RenderWidgetHostIterator
> widgets(
466 content::RenderWidgetHost::GetRenderWidgetHosts());
467 while (content::RenderWidgetHost
* widget
= widgets
->GetNextHost()) {
468 content::RenderWidgetHostView
* view
= widget
->GetView();
469 if (view
&& window
->Contains(view
->GetNativeView())) {
470 gfx::Rect window_bounds
= view
->GetNativeView()->GetBoundsInScreen();
471 gfx::Rect intersect
=
472 gfx::IntersectRects(window_bounds
, keyboard_window
->bounds());
473 int overlap
= ShouldEnableInsets(window
) ? intersect
.height() : 0;
474 if (overlap
> 0 && overlap
< window_bounds
.height())
475 view
->SetInsets(gfx::Insets(0, 0, overlap
, 0));
477 view
->SetInsets(gfx::Insets());
483 void KeyboardController::ShowKeyboardInternal() {
484 if (!container_
.get())
487 if (container_
->children().empty()) {
488 keyboard::MarkKeyboardLoadStarted();
489 aura::Window
* keyboard
= proxy_
->GetKeyboardWindow();
491 container_
->AddChild(keyboard
);
492 keyboard
->set_owned_by_parent(false);
495 proxy_
->ReloadKeyboardIfNeeded();
497 if (keyboard_visible_
) {
499 } else if (proxy_
->GetKeyboardWindow()->bounds().height() == 0) {
500 show_on_resize_
= true;
504 keyboard_visible_
= true;
506 // If the controller is in the process of hiding the keyboard, do not log
507 // the stat here since the keyboard will not actually be shown.
508 if (!WillHideKeyboard())
509 keyboard::LogKeyboardControlEvent(keyboard::KEYBOARD_CONTROL_SHOW
);
511 weak_factory_
.InvalidateWeakPtrs();
513 // If |container_| has hide animation, its visibility is set to false when
514 // hide animation finished. So even if the container is visible at this
515 // point, it may in the process of hiding. We still need to show keyboard
516 // container in this case.
517 if (container_
->IsVisible() &&
518 !container_
->layer()->GetAnimator()->is_animating())
521 ToggleTouchEventLogging(false);
522 ui::LayerAnimator
* container_animator
= container_
->layer()->GetAnimator();
524 // If the container is not animating, makes sure the position and opacity
525 // are at begin states for animation.
526 if (!container_animator
->is_animating()) {
527 gfx::Transform transform
;
528 transform
.Translate(0, kAnimationDistance
);
529 container_
->SetTransform(transform
);
530 container_
->layer()->SetOpacity(kAnimationStartOrAfterHideOpacity
);
533 container_animator
->set_preemption_strategy(
534 ui::LayerAnimator::IMMEDIATELY_ANIMATE_TO_NEW_TARGET
);
535 if (keyboard_mode_
== FLOATING
) {
536 animation_observer_
.reset();
538 animation_observer_
.reset(new CallbackAnimationObserver(
540 base::Bind(&KeyboardController::ShowAnimationFinished
,
541 base::Unretained(this))));
542 container_animator
->AddObserver(animation_observer_
.get());
545 proxy_
->ShowKeyboardContainer(container_
.get());
548 // Scope the following animation settings as we don't want to animate
549 // visibility change that triggered by a call to the base class function
550 // ShowKeyboardContainer with these settings. The container should become
551 // visible immediately.
552 ui::ScopedLayerAnimationSettings
settings(container_animator
);
553 settings
.SetTweenType(gfx::Tween::LINEAR_OUT_SLOW_IN
);
554 settings
.SetTransitionDuration(
555 base::TimeDelta::FromMilliseconds(kShowAnimationDurationMs
));
556 container_
->SetTransform(gfx::Transform());
557 container_
->layer()->SetOpacity(1.0);
561 void KeyboardController::ResetWindowInsets() {
562 const gfx::Insets insets
;
563 scoped_ptr
<content::RenderWidgetHostIterator
> widgets(
564 content::RenderWidgetHost::GetRenderWidgetHosts());
565 while (content::RenderWidgetHost
* widget
= widgets
->GetNextHost()) {
566 content::RenderWidgetHostView
* view
= widget
->GetView();
568 view
->SetInsets(insets
);
570 window_bounds_observer_
->RemoveAllObservedWindows();
573 bool KeyboardController::WillHideKeyboard() const {
574 return weak_factory_
.HasWeakPtrs();
577 void KeyboardController::ShowAnimationFinished() {
578 // Notify observers after animation finished to prevent reveal desktop
579 // background during animation.
580 NotifyKeyboardBoundsChanging(container_
->bounds());
581 proxy_
->EnsureCaretInWorkArea();
584 void KeyboardController::HideAnimationFinished() {
585 proxy_
->HideKeyboardContainer(container_
.get());
588 void KeyboardController::AddBoundsChangedObserver(aura::Window
* window
) {
589 aura::Window
* target_window
= window
? window
->GetToplevelWindow() : nullptr;
591 window_bounds_observer_
->AddObservedWindow(target_window
);
594 } // namespace keyboard