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 virtual ~KeyboardContainerTargeter() {}
63 // wm::MaskedWindowTargeter:
64 virtual bool GetHitTestMask(aura::Window
* window
,
65 gfx::Path
* mask
) const override
{
66 if (proxy_
&& !proxy_
->HasKeyboardWindow())
68 gfx::Rect keyboard_bounds
= proxy_
? proxy_
->GetKeyboardWindow()->bounds() :
69 keyboard::DefaultKeyboardBoundsFromWindowBounds(window
->bounds());
70 mask
->addRect(RectToSkRect(keyboard_bounds
));
74 keyboard::KeyboardControllerProxy
* proxy_
;
76 DISALLOW_COPY_AND_ASSIGN(KeyboardContainerTargeter
);
79 // The KeyboardWindowDelegate makes sure the keyboard-window does not get focus.
80 // This is necessary to make sure that the synthetic key-events reach the target
82 // The delegate deletes itself when the window is destroyed.
83 class KeyboardWindowDelegate
: public aura::WindowDelegate
{
85 explicit KeyboardWindowDelegate(keyboard::KeyboardControllerProxy
* proxy
)
87 virtual ~KeyboardWindowDelegate() {}
90 // Overridden from aura::WindowDelegate:
91 virtual gfx::Size
GetMinimumSize() const override
{ return gfx::Size(); }
92 virtual gfx::Size
GetMaximumSize() const override
{ return gfx::Size(); }
93 virtual void OnBoundsChanged(const gfx::Rect
& old_bounds
,
94 const gfx::Rect
& new_bounds
) override
{
97 virtual gfx::NativeCursor
GetCursor(const gfx::Point
& point
) override
{
98 return gfx::kNullCursor
;
100 virtual int GetNonClientComponent(const gfx::Point
& point
) const override
{
103 virtual bool ShouldDescendIntoChildForEventHandling(
105 const gfx::Point
& location
) override
{
108 virtual bool CanFocus() override
{ return false; }
109 virtual void OnCaptureLost() override
{}
110 virtual void OnPaint(gfx::Canvas
* canvas
) override
{}
111 virtual void OnDeviceScaleFactorChanged(float device_scale_factor
) override
{}
112 virtual void OnWindowDestroying(aura::Window
* window
) override
{}
113 virtual void OnWindowDestroyed(aura::Window
* window
) override
{ delete this; }
114 virtual void OnWindowTargetVisibilityChanged(bool visible
) override
{}
115 virtual bool HasHitTestMask() const override
{
116 return !proxy_
|| proxy_
->HasKeyboardWindow();
118 virtual void GetHitTestMask(gfx::Path
* mask
) const override
{
119 if (proxy_
&& !proxy_
->HasKeyboardWindow())
121 gfx::Rect keyboard_bounds
= proxy_
? proxy_
->GetKeyboardWindow()->bounds() :
122 keyboard::DefaultKeyboardBoundsFromWindowBounds(bounds_
);
123 mask
->addRect(RectToSkRect(keyboard_bounds
));
127 keyboard::KeyboardControllerProxy
* proxy_
;
129 DISALLOW_COPY_AND_ASSIGN(KeyboardWindowDelegate
);
132 void ToggleTouchEventLogging(bool enable
) {
133 #if defined(OS_CHROMEOS)
134 if (!base::SysInfo::IsRunningOnChromeOS())
137 base::FilePath("/opt/google/touchscreen/toggle_touch_event_logging"));
139 command
.AppendArg("1");
141 command
.AppendArg("0");
142 VLOG(1) << "Running " << command
.GetCommandLineString();
143 base::LaunchOptions options
;
145 base::LaunchProcess(command
, options
, NULL
);
149 aura::Window
*GetFrameWindow(aura::Window
*window
) {
150 // Each container window has a non-negative id. Stop traversing at the child
151 // of a container window.
154 while (window
->parent() && window
->parent()->id() < 0) {
155 window
= window
->parent();
164 // Observer for both keyboard show and hide animations. It should be owned by
165 // KeyboardController.
166 class CallbackAnimationObserver
: public ui::LayerAnimationObserver
{
168 CallbackAnimationObserver(ui::LayerAnimator
* animator
,
169 base::Callback
<void(void)> callback
);
170 virtual ~CallbackAnimationObserver();
173 // Overridden from ui::LayerAnimationObserver:
174 virtual void OnLayerAnimationEnded(ui::LayerAnimationSequence
* seq
) override
;
175 virtual void OnLayerAnimationAborted(
176 ui::LayerAnimationSequence
* seq
) override
;
177 virtual void OnLayerAnimationScheduled(
178 ui::LayerAnimationSequence
* seq
) override
{}
180 ui::LayerAnimator
* animator_
;
181 base::Callback
<void(void)> callback_
;
183 DISALLOW_COPY_AND_ASSIGN(CallbackAnimationObserver
);
186 CallbackAnimationObserver::CallbackAnimationObserver(
187 ui::LayerAnimator
* animator
, base::Callback
<void(void)> callback
)
188 : animator_(animator
), callback_(callback
) {
191 CallbackAnimationObserver::~CallbackAnimationObserver() {
192 animator_
->RemoveObserver(this);
195 void CallbackAnimationObserver::OnLayerAnimationEnded(
196 ui::LayerAnimationSequence
* seq
) {
197 if (animator_
->is_animating())
199 animator_
->RemoveObserver(this);
203 void CallbackAnimationObserver::OnLayerAnimationAborted(
204 ui::LayerAnimationSequence
* seq
) {
205 animator_
->RemoveObserver(this);
208 class WindowBoundsChangeObserver
: public aura::WindowObserver
{
210 virtual void OnWindowBoundsChanged(aura::Window
* window
,
211 const gfx::Rect
& old_bounds
,
212 const gfx::Rect
& new_bounds
) override
;
213 virtual void OnWindowDestroyed(aura::Window
* window
) override
;
215 void AddObservedWindow(aura::Window
* window
);
216 void RemoveAllObservedWindows();
219 std::set
<aura::Window
*> observed_windows_
;
222 void WindowBoundsChangeObserver::OnWindowBoundsChanged(aura::Window
* window
,
223 const gfx::Rect
& old_bounds
, const gfx::Rect
& new_bounds
) {
224 KeyboardController
* controller
= KeyboardController::GetInstance();
226 controller
->UpdateWindowInsets(window
);
229 void WindowBoundsChangeObserver::OnWindowDestroyed(aura::Window
* window
) {
230 if (window
->HasObserver(this))
231 window
->RemoveObserver(this);
232 observed_windows_
.erase(window
);
235 void WindowBoundsChangeObserver::AddObservedWindow(aura::Window
* window
) {
236 if (!window
->HasObserver(this)) {
237 window
->AddObserver(this);
238 observed_windows_
.insert(window
);
242 void WindowBoundsChangeObserver::RemoveAllObservedWindows() {
243 for (std::set
<aura::Window
*>::iterator it
= observed_windows_
.begin();
244 it
!= observed_windows_
.end(); ++it
)
245 (*it
)->RemoveObserver(this);
246 observed_windows_
.clear();
250 KeyboardController
* KeyboardController::instance_
= NULL
;
252 KeyboardController::KeyboardController(KeyboardControllerProxy
* proxy
)
255 keyboard_visible_(false),
256 show_on_resize_(false),
257 lock_keyboard_(false),
258 type_(ui::TEXT_INPUT_TYPE_NONE
),
259 weak_factory_(this) {
261 input_method_
= proxy_
->GetInputMethod();
262 input_method_
->AddObserver(this);
263 window_bounds_observer_
.reset(new WindowBoundsChangeObserver());
266 KeyboardController::~KeyboardController() {
268 container_
->RemoveObserver(this);
270 input_method_
->RemoveObserver(this);
275 void KeyboardController::ResetInstance(KeyboardController
* controller
) {
276 if (instance_
&& instance_
!= controller
)
278 instance_
= controller
;
282 KeyboardController
* KeyboardController::GetInstance() {
286 aura::Window
* KeyboardController::GetContainerWindow() {
287 if (!container_
.get()) {
288 container_
.reset(new aura::Window(
289 new KeyboardWindowDelegate(proxy_
.get())));
290 container_
->SetEventTargeter(scoped_ptr
<ui::EventTargeter
>(
291 new KeyboardContainerTargeter(container_
.get(), proxy_
.get())));
292 container_
->SetName("KeyboardContainer");
293 container_
->set_owned_by_parent(false);
294 container_
->Init(aura::WINDOW_LAYER_NOT_DRAWN
);
295 container_
->AddObserver(this);
296 container_
->SetLayoutManager(new KeyboardLayoutManager(this));
298 return container_
.get();
301 void KeyboardController::NotifyKeyboardBoundsChanging(
302 const gfx::Rect
& new_bounds
) {
303 current_keyboard_bounds_
= new_bounds
;
304 if (proxy_
->HasKeyboardWindow() && proxy_
->GetKeyboardWindow()->IsVisible()) {
305 FOR_EACH_OBSERVER(KeyboardControllerObserver
,
307 OnKeyboardBoundsChanging(new_bounds
));
308 if (keyboard::IsKeyboardOverscrollEnabled()) {
309 // Adjust the height of the viewport for visible windows on the primary
311 // TODO(kevers): Add EnvObserver to properly initialize insets if a
312 // window is created while the keyboard is visible.
313 scoped_ptr
<content::RenderWidgetHostIterator
> widgets(
314 content::RenderWidgetHost::GetRenderWidgetHosts());
315 aura::Window
*keyboard_window
= proxy_
->GetKeyboardWindow();
316 aura::Window
*root_window
= keyboard_window
->GetRootWindow();
317 while (content::RenderWidgetHost
* widget
= widgets
->GetNextHost()) {
318 content::RenderWidgetHostView
* view
= widget
->GetView();
319 // Can be NULL, e.g. if the RenderWidget is being destroyed or
320 // the render process crashed.
322 aura::Window
*window
= view
->GetNativeView();
323 // If virtual keyboard failed to load, a widget that displays error
324 // message will be created and adds as a child of the virtual keyboard
325 // window. We want to avoid add BoundsChangedObserver to that window.
326 if (GetFrameWindow(window
) != keyboard_window
&&
327 window
->GetRootWindow() == root_window
) {
328 gfx::Rect window_bounds
= window
->GetBoundsInScreen();
329 gfx::Rect intersect
= gfx::IntersectRects(window_bounds
,
331 int overlap
= intersect
.height();
332 if (overlap
> 0 && overlap
< window_bounds
.height())
333 view
->SetInsets(gfx::Insets(0, 0, overlap
, 0));
335 view
->SetInsets(gfx::Insets());
336 AddBoundsChangedObserver(window
);
344 current_keyboard_bounds_
= gfx::Rect();
348 void KeyboardController::HideKeyboard(HideReason reason
) {
349 keyboard_visible_
= false;
350 ToggleTouchEventLogging(true);
352 keyboard::LogKeyboardControlEvent(
353 reason
== HIDE_REASON_AUTOMATIC
?
354 keyboard::KEYBOARD_CONTROL_HIDE_AUTO
:
355 keyboard::KEYBOARD_CONTROL_HIDE_USER
);
357 NotifyKeyboardBoundsChanging(gfx::Rect());
359 set_lock_keyboard(false);
361 ui::LayerAnimator
* container_animator
= container_
->layer()->GetAnimator();
362 animation_observer_
.reset(new CallbackAnimationObserver(
364 base::Bind(&KeyboardController::HideAnimationFinished
,
365 base::Unretained(this))));
366 container_animator
->AddObserver(animation_observer_
.get());
368 ui::ScopedLayerAnimationSettings
settings(container_animator
);
369 settings
.SetTweenType(gfx::Tween::FAST_OUT_LINEAR_IN
);
370 settings
.SetTransitionDuration(
371 base::TimeDelta::FromMilliseconds(kHideAnimationDurationMs
));
372 gfx::Transform transform
;
373 transform
.Translate(0, kAnimationDistance
);
374 container_
->SetTransform(transform
);
375 container_
->layer()->SetOpacity(kAnimationStartOrAfterHideOpacity
);
378 void KeyboardController::AddObserver(KeyboardControllerObserver
* observer
) {
379 observer_list_
.AddObserver(observer
);
382 void KeyboardController::RemoveObserver(KeyboardControllerObserver
* observer
) {
383 observer_list_
.RemoveObserver(observer
);
386 void KeyboardController::ShowKeyboard(bool lock
) {
387 set_lock_keyboard(lock
);
388 ShowKeyboardInternal();
391 void KeyboardController::OnWindowHierarchyChanged(
392 const HierarchyChangeParams
& params
) {
393 if (params
.new_parent
&& params
.target
== container_
.get())
394 OnTextInputStateChanged(proxy_
->GetInputMethod()->GetTextInputClient());
397 void KeyboardController::Reload() {
398 if (proxy_
->HasKeyboardWindow()) {
399 // A reload should never try to show virtual keyboard. If keyboard is not
400 // visible before reload, it should keep invisible after reload.
401 show_on_resize_
= false;
402 proxy_
->ReloadKeyboardIfNeeded();
406 void KeyboardController::OnTextInputStateChanged(
407 const ui::TextInputClient
* client
) {
408 if (!container_
.get())
411 type_
= client
? client
->GetTextInputType() : ui::TEXT_INPUT_TYPE_NONE
;
413 if (type_
== ui::TEXT_INPUT_TYPE_NONE
&& !lock_keyboard_
) {
414 if (keyboard_visible_
) {
415 // Set the visibility state here so that any queries for visibility
416 // before the timer fires returns the correct future value.
417 keyboard_visible_
= false;
418 base::MessageLoop::current()->PostDelayedTask(
420 base::Bind(&KeyboardController::HideKeyboard
,
421 weak_factory_
.GetWeakPtr(), HIDE_REASON_AUTOMATIC
),
422 base::TimeDelta::FromMilliseconds(kHideKeyboardDelayMs
));
425 // Abort a pending keyboard hide.
426 if (WillHideKeyboard()) {
427 weak_factory_
.InvalidateWeakPtrs();
428 keyboard_visible_
= true;
430 proxy_
->SetUpdateInputType(type_
);
431 // Do not explicitly show the Virtual keyboard unless it is in the process
432 // of hiding. Instead, the virtual keyboard is shown in response to a user
433 // gesture (mouse or touch) that is received while an element has input
434 // focus. Showing the keyboard requires an explicit call to
435 // OnShowImeIfNeeded.
439 void KeyboardController::OnInputMethodDestroyed(
440 const ui::InputMethod
* input_method
) {
441 DCHECK_EQ(input_method_
, input_method
);
442 input_method_
= NULL
;
445 void KeyboardController::OnShowImeIfNeeded() {
446 ShowKeyboardInternal();
449 bool KeyboardController::ShouldEnableInsets(aura::Window
* window
) {
450 aura::Window
*keyboard_window
= proxy_
->GetKeyboardWindow();
451 return (keyboard_window
->GetRootWindow() == window
->GetRootWindow() &&
452 keyboard::IsKeyboardOverscrollEnabled() &&
453 proxy_
->GetKeyboardWindow()->IsVisible() &&
457 void KeyboardController::UpdateWindowInsets(aura::Window
* window
) {
458 aura::Window
*keyboard_window
= proxy_
->GetKeyboardWindow();
459 if (window
== keyboard_window
)
462 scoped_ptr
<content::RenderWidgetHostIterator
> widgets(
463 content::RenderWidgetHost::GetRenderWidgetHosts());
464 while (content::RenderWidgetHost
* widget
= widgets
->GetNextHost()) {
465 content::RenderWidgetHostView
* view
= widget
->GetView();
466 if (view
&& window
->Contains(view
->GetNativeView())) {
467 gfx::Rect window_bounds
= view
->GetNativeView()->GetBoundsInScreen();
468 gfx::Rect intersect
= gfx::IntersectRects(window_bounds
,
469 proxy_
->GetKeyboardWindow()->bounds());
470 int overlap
= ShouldEnableInsets(window
) ? intersect
.height() : 0;
471 if (overlap
> 0 && overlap
< window_bounds
.height())
472 view
->SetInsets(gfx::Insets(0, 0, overlap
, 0));
474 view
->SetInsets(gfx::Insets());
480 void KeyboardController::ShowKeyboardInternal() {
481 if (!container_
.get())
484 if (container_
->children().empty()) {
485 keyboard::MarkKeyboardLoadStarted();
486 aura::Window
* keyboard
= proxy_
->GetKeyboardWindow();
488 container_
->AddChild(keyboard
);
489 keyboard
->set_owned_by_parent(false);
492 proxy_
->ReloadKeyboardIfNeeded();
494 if (keyboard_visible_
) {
496 } else if (proxy_
->GetKeyboardWindow()->bounds().height() == 0) {
497 show_on_resize_
= true;
501 keyboard_visible_
= true;
503 // If the controller is in the process of hiding the keyboard, do not log
504 // the stat here since the keyboard will not actually be shown.
505 if (!WillHideKeyboard())
506 keyboard::LogKeyboardControlEvent(keyboard::KEYBOARD_CONTROL_SHOW
);
508 weak_factory_
.InvalidateWeakPtrs();
510 // If |container_| has hide animation, its visibility is set to false when
511 // hide animation finished. So even if the container is visible at this
512 // point, it may in the process of hiding. We still need to show keyboard
513 // container in this case.
514 if (container_
->IsVisible() &&
515 !container_
->layer()->GetAnimator()->is_animating())
518 ToggleTouchEventLogging(false);
519 ui::LayerAnimator
* container_animator
= container_
->layer()->GetAnimator();
521 // If the container is not animating, makes sure the position and opacity
522 // are at begin states for animation.
523 if (!container_animator
->is_animating()) {
524 gfx::Transform transform
;
525 transform
.Translate(0, kAnimationDistance
);
526 container_
->SetTransform(transform
);
527 container_
->layer()->SetOpacity(kAnimationStartOrAfterHideOpacity
);
530 container_animator
->set_preemption_strategy(
531 ui::LayerAnimator::IMMEDIATELY_ANIMATE_TO_NEW_TARGET
);
532 animation_observer_
.reset(new CallbackAnimationObserver(
534 base::Bind(&KeyboardController::ShowAnimationFinished
,
535 base::Unretained(this))));
536 container_animator
->AddObserver(animation_observer_
.get());
538 proxy_
->ShowKeyboardContainer(container_
.get());
541 // Scope the following animation settings as we don't want to animate
542 // visibility change that triggered by a call to the base class function
543 // ShowKeyboardContainer with these settings. The container should become
544 // visible immediately.
545 ui::ScopedLayerAnimationSettings
settings(container_animator
);
546 settings
.SetTweenType(gfx::Tween::LINEAR_OUT_SLOW_IN
);
547 settings
.SetTransitionDuration(
548 base::TimeDelta::FromMilliseconds(kShowAnimationDurationMs
));
549 container_
->SetTransform(gfx::Transform());
550 container_
->layer()->SetOpacity(1.0);
554 void KeyboardController::ResetWindowInsets() {
555 const gfx::Insets insets
;
556 scoped_ptr
<content::RenderWidgetHostIterator
> widgets(
557 content::RenderWidgetHost::GetRenderWidgetHosts());
558 while (content::RenderWidgetHost
* widget
= widgets
->GetNextHost()) {
559 content::RenderWidgetHostView
* view
= widget
->GetView();
561 view
->SetInsets(insets
);
563 window_bounds_observer_
->RemoveAllObservedWindows();
566 bool KeyboardController::WillHideKeyboard() const {
567 return weak_factory_
.HasWeakPtrs();
570 void KeyboardController::ShowAnimationFinished() {
571 // Notify observers after animation finished to prevent reveal desktop
572 // background during animation.
573 NotifyKeyboardBoundsChanging(proxy_
->GetKeyboardWindow()->bounds());
574 proxy_
->EnsureCaretInWorkArea();
577 void KeyboardController::HideAnimationFinished() {
578 proxy_
->HideKeyboardContainer(container_
.get());
581 void KeyboardController::AddBoundsChangedObserver(aura::Window
* window
) {
582 aura::Window
* target_window
= GetFrameWindow(window
);
584 window_bounds_observer_
->AddObservedWindow(target_window
);
587 } // namespace keyboard