Update frame around SAML IdP pages to new GAIA style
[chromium-blink-merge.git] / ui / keyboard / keyboard_controller.cc
blob5aa44bbbaf599bf7c431ec55456e8e7277092d80
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/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"
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 // 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
53 // window.
54 // The delegate deletes itself when the window is destroyed.
55 class KeyboardWindowDelegate : public aura::WindowDelegate {
56 public:
57 KeyboardWindowDelegate() {}
58 ~KeyboardWindowDelegate() override {}
60 private:
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 {
67 return nullptr;
69 gfx::NativeCursor GetCursor(const gfx::Point& point) override {
70 return gfx::kNullCursor;
72 int GetNonClientComponent(const gfx::Point& point) const override {
73 return HTNOWHERE;
75 bool ShouldDescendIntoChildForEventHandling(
76 aura::Window* child,
77 const gfx::Point& location) override {
78 return true;
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())
96 return;
97 base::CommandLine command(
98 base::FilePath("/opt/google/touchscreen/toggle_touch_event_logging"));
99 if (enable)
100 command.AppendArg("1");
101 else
102 command.AppendArg("0");
103 VLOG(1) << "Running " << command.GetCommandLineString();
104 base::LaunchOptions options;
105 options.wait = true;
106 base::LaunchProcess(command, options);
107 #endif
110 } // namespace
112 namespace keyboard {
114 // Observer for both keyboard show and hide animations. It should be owned by
115 // KeyboardController.
116 class CallbackAnimationObserver : public ui::LayerAnimationObserver {
117 public:
118 CallbackAnimationObserver(ui::LayerAnimator* animator,
119 base::Callback<void(void)> callback);
120 ~CallbackAnimationObserver() override;
122 private:
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 ui::LayerAnimator* animator_;
129 base::Callback<void(void)> callback_;
131 DISALLOW_COPY_AND_ASSIGN(CallbackAnimationObserver);
134 CallbackAnimationObserver::CallbackAnimationObserver(
135 ui::LayerAnimator* animator, base::Callback<void(void)> callback)
136 : animator_(animator), callback_(callback) {
139 CallbackAnimationObserver::~CallbackAnimationObserver() {
140 animator_->RemoveObserver(this);
143 void CallbackAnimationObserver::OnLayerAnimationEnded(
144 ui::LayerAnimationSequence* seq) {
145 if (animator_->is_animating())
146 return;
147 animator_->RemoveObserver(this);
148 callback_.Run();
151 void CallbackAnimationObserver::OnLayerAnimationAborted(
152 ui::LayerAnimationSequence* seq) {
153 animator_->RemoveObserver(this);
156 class WindowBoundsChangeObserver : public aura::WindowObserver {
157 public:
158 void OnWindowBoundsChanged(aura::Window* window,
159 const gfx::Rect& old_bounds,
160 const gfx::Rect& new_bounds) override;
161 void OnWindowDestroyed(aura::Window* window) override;
163 void AddObservedWindow(aura::Window* window);
164 void RemoveAllObservedWindows();
166 private:
167 std::set<aura::Window*> observed_windows_;
170 void WindowBoundsChangeObserver::OnWindowBoundsChanged(aura::Window* window,
171 const gfx::Rect& old_bounds, const gfx::Rect& new_bounds) {
172 KeyboardController* controller = KeyboardController::GetInstance();
173 if (controller)
174 controller->UpdateWindowInsets(window);
177 void WindowBoundsChangeObserver::OnWindowDestroyed(aura::Window* window) {
178 if (window->HasObserver(this))
179 window->RemoveObserver(this);
180 observed_windows_.erase(window);
183 void WindowBoundsChangeObserver::AddObservedWindow(aura::Window* window) {
184 if (!window->HasObserver(this)) {
185 window->AddObserver(this);
186 observed_windows_.insert(window);
190 void WindowBoundsChangeObserver::RemoveAllObservedWindows() {
191 for (std::set<aura::Window*>::iterator it = observed_windows_.begin();
192 it != observed_windows_.end(); ++it)
193 (*it)->RemoveObserver(this);
194 observed_windows_.clear();
197 // static
198 KeyboardController* KeyboardController::instance_ = NULL;
200 KeyboardController::KeyboardController(KeyboardControllerProxy* proxy)
201 : proxy_(proxy),
202 input_method_(NULL),
203 keyboard_visible_(false),
204 show_on_resize_(false),
205 lock_keyboard_(false),
206 keyboard_mode_(FULL_WIDTH),
207 type_(ui::TEXT_INPUT_TYPE_NONE),
208 weak_factory_(this) {
209 CHECK(proxy);
210 input_method_ = proxy_->GetInputMethod();
211 input_method_->AddObserver(this);
212 window_bounds_observer_.reset(new WindowBoundsChangeObserver());
215 KeyboardController::~KeyboardController() {
216 if (container_) {
217 if (container_->GetRootWindow())
218 container_->GetRootWindow()->RemoveObserver(this);
219 container_->RemoveObserver(this);
221 if (input_method_)
222 input_method_->RemoveObserver(this);
223 ResetWindowInsets();
226 // static
227 void KeyboardController::ResetInstance(KeyboardController* controller) {
228 if (instance_ && instance_ != controller)
229 delete instance_;
230 instance_ = controller;
233 // static
234 KeyboardController* KeyboardController::GetInstance() {
235 return instance_;
238 aura::Window* KeyboardController::GetContainerWindow() {
239 if (!container_.get()) {
240 container_.reset(new aura::Window(new KeyboardWindowDelegate()));
241 container_->SetName("KeyboardContainer");
242 container_->set_owned_by_parent(false);
243 container_->Init(ui::LAYER_NOT_DRAWN);
244 container_->AddObserver(this);
245 container_->SetLayoutManager(new KeyboardLayoutManager(this));
247 return container_.get();
250 void KeyboardController::NotifyKeyboardBoundsChanging(
251 const gfx::Rect& new_bounds) {
252 current_keyboard_bounds_ = new_bounds;
253 if (proxy_->HasKeyboardWindow() && proxy_->GetKeyboardWindow()->IsVisible()) {
254 FOR_EACH_OBSERVER(KeyboardControllerObserver,
255 observer_list_,
256 OnKeyboardBoundsChanging(new_bounds));
257 if (keyboard::IsKeyboardOverscrollEnabled()) {
258 // Adjust the height of the viewport for visible windows on the primary
259 // display.
260 // TODO(kevers): Add EnvObserver to properly initialize insets if a
261 // window is created while the keyboard is visible.
262 scoped_ptr<content::RenderWidgetHostIterator> widgets(
263 content::RenderWidgetHost::GetRenderWidgetHosts());
264 aura::Window* keyboard_window = proxy_->GetKeyboardWindow();
265 aura::Window* root_window = keyboard_window->GetRootWindow();
266 while (content::RenderWidgetHost* widget = widgets->GetNextHost()) {
267 content::RenderWidgetHostView* view = widget->GetView();
268 // Can be NULL, e.g. if the RenderWidget is being destroyed or
269 // the render process crashed.
270 if (view) {
271 aura::Window* window = view->GetNativeView();
272 // If virtual keyboard failed to load, a widget that displays error
273 // message will be created and adds as a child of the virtual keyboard
274 // window. We want to avoid add BoundsChangedObserver to that window.
275 if (!keyboard_window->Contains(window) &&
276 window->GetRootWindow() == root_window) {
277 gfx::Rect window_bounds = window->GetBoundsInScreen();
278 gfx::Rect intersect = gfx::IntersectRects(window_bounds,
279 new_bounds);
280 int overlap = intersect.height();
281 if (overlap > 0 && overlap < window_bounds.height())
282 view->SetInsets(gfx::Insets(0, 0, overlap, 0));
283 else
284 view->SetInsets(gfx::Insets());
285 AddBoundsChangedObserver(window);
289 } else {
290 ResetWindowInsets();
292 } else {
293 current_keyboard_bounds_ = gfx::Rect();
297 void KeyboardController::HideKeyboard(HideReason reason) {
298 keyboard_visible_ = false;
299 ToggleTouchEventLogging(true);
301 keyboard::LogKeyboardControlEvent(
302 reason == HIDE_REASON_AUTOMATIC ?
303 keyboard::KEYBOARD_CONTROL_HIDE_AUTO :
304 keyboard::KEYBOARD_CONTROL_HIDE_USER);
306 NotifyKeyboardBoundsChanging(gfx::Rect());
308 set_lock_keyboard(false);
310 ui::LayerAnimator* container_animator = container_->layer()->GetAnimator();
311 animation_observer_.reset(new CallbackAnimationObserver(
312 container_animator,
313 base::Bind(&KeyboardController::HideAnimationFinished,
314 base::Unretained(this))));
315 container_animator->AddObserver(animation_observer_.get());
317 ui::ScopedLayerAnimationSettings settings(container_animator);
318 settings.SetTweenType(gfx::Tween::FAST_OUT_LINEAR_IN);
319 settings.SetTransitionDuration(
320 base::TimeDelta::FromMilliseconds(kHideAnimationDurationMs));
321 gfx::Transform transform;
322 transform.Translate(0, kAnimationDistance);
323 container_->SetTransform(transform);
324 container_->layer()->SetOpacity(kAnimationStartOrAfterHideOpacity);
327 void KeyboardController::AddObserver(KeyboardControllerObserver* observer) {
328 observer_list_.AddObserver(observer);
331 void KeyboardController::RemoveObserver(KeyboardControllerObserver* observer) {
332 observer_list_.RemoveObserver(observer);
335 void KeyboardController::SetKeyboardMode(KeyboardMode mode) {
336 keyboard_mode_ = mode;
339 void KeyboardController::ShowKeyboard(bool lock) {
340 set_lock_keyboard(lock);
341 ShowKeyboardInternal();
344 void KeyboardController::OnWindowHierarchyChanged(
345 const HierarchyChangeParams& params) {
346 if (params.new_parent && params.target == container_.get())
347 OnTextInputStateChanged(proxy_->GetInputMethod()->GetTextInputClient());
350 void KeyboardController::OnWindowAddedToRootWindow(aura::Window* window) {
351 if (!window->GetRootWindow()->HasObserver(this))
352 window->GetRootWindow()->AddObserver(this);
355 void KeyboardController::OnWindowRemovingFromRootWindow(aura::Window* window,
356 aura::Window* new_root) {
357 if (window->GetRootWindow()->HasObserver(this))
358 window->GetRootWindow()->RemoveObserver(this);
361 void KeyboardController::OnWindowBoundsChanged(aura::Window* window,
362 const gfx::Rect& old_bounds,
363 const gfx::Rect& new_bounds) {
364 if (!window->IsRootWindow())
365 return;
366 // Keep the same height when window resize. It gets called when screen
367 // rotate.
368 if (!keyboard_container_initialized() || !proxy_->HasKeyboardWindow())
369 return;
371 int container_height = container_->bounds().height();
372 if (keyboard_mode_ == FULL_WIDTH) {
373 container_->SetBounds(gfx::Rect(new_bounds.x(),
374 new_bounds.bottom() - container_height,
375 new_bounds.width(),
376 container_height));
377 } else if (keyboard_mode_ == FLOATING) {
378 // When screen rotate, horizontally center floating virtual keyboard
379 // window and vertically align it to the bottom.
380 int container_width = container_->bounds().width();
381 container_->SetBounds(gfx::Rect(
382 new_bounds.x() + (new_bounds.width() - container_width) / 2,
383 new_bounds.bottom() - container_height,
384 container_width,
385 container_height));
389 void KeyboardController::Reload() {
390 if (proxy_->HasKeyboardWindow()) {
391 // A reload should never try to show virtual keyboard. If keyboard is not
392 // visible before reload, it should keep invisible after reload.
393 show_on_resize_ = false;
394 proxy_->ReloadKeyboardIfNeeded();
398 void KeyboardController::OnTextInputStateChanged(
399 const ui::TextInputClient* client) {
400 if (!container_.get())
401 return;
403 type_ = client ? client->GetTextInputType() : ui::TEXT_INPUT_TYPE_NONE;
405 if (type_ == ui::TEXT_INPUT_TYPE_NONE && !lock_keyboard_) {
406 if (keyboard_visible_) {
407 // Set the visibility state here so that any queries for visibility
408 // before the timer fires returns the correct future value.
409 keyboard_visible_ = false;
410 base::MessageLoop::current()->PostDelayedTask(
411 FROM_HERE,
412 base::Bind(&KeyboardController::HideKeyboard,
413 weak_factory_.GetWeakPtr(), HIDE_REASON_AUTOMATIC),
414 base::TimeDelta::FromMilliseconds(kHideKeyboardDelayMs));
416 } else {
417 // Abort a pending keyboard hide.
418 if (WillHideKeyboard()) {
419 weak_factory_.InvalidateWeakPtrs();
420 keyboard_visible_ = true;
422 proxy_->SetUpdateInputType(type_);
423 // Do not explicitly show the Virtual keyboard unless it is in the process
424 // of hiding. Instead, the virtual keyboard is shown in response to a user
425 // gesture (mouse or touch) that is received while an element has input
426 // focus. Showing the keyboard requires an explicit call to
427 // OnShowImeIfNeeded.
431 void KeyboardController::OnInputMethodDestroyed(
432 const ui::InputMethod* input_method) {
433 DCHECK_EQ(input_method_, input_method);
434 input_method_ = NULL;
437 void KeyboardController::OnShowImeIfNeeded() {
438 ShowKeyboardInternal();
441 bool KeyboardController::ShouldEnableInsets(aura::Window* window) {
442 aura::Window* keyboard_window = proxy_->GetKeyboardWindow();
443 return (keyboard_window->GetRootWindow() == window->GetRootWindow() &&
444 keyboard::IsKeyboardOverscrollEnabled() &&
445 keyboard_window->IsVisible() && keyboard_visible_);
448 void KeyboardController::UpdateWindowInsets(aura::Window* window) {
449 aura::Window* keyboard_window = proxy_->GetKeyboardWindow();
450 if (window == keyboard_window)
451 return;
453 scoped_ptr<content::RenderWidgetHostIterator> widgets(
454 content::RenderWidgetHost::GetRenderWidgetHosts());
455 while (content::RenderWidgetHost* widget = widgets->GetNextHost()) {
456 content::RenderWidgetHostView* view = widget->GetView();
457 if (view && window->Contains(view->GetNativeView())) {
458 gfx::Rect window_bounds = view->GetNativeView()->GetBoundsInScreen();
459 gfx::Rect intersect =
460 gfx::IntersectRects(window_bounds, keyboard_window->bounds());
461 int overlap = ShouldEnableInsets(window) ? intersect.height() : 0;
462 if (overlap > 0 && overlap < window_bounds.height())
463 view->SetInsets(gfx::Insets(0, 0, overlap, 0));
464 else
465 view->SetInsets(gfx::Insets());
466 return;
471 void KeyboardController::ShowKeyboardInternal() {
472 if (!container_.get())
473 return;
475 if (container_->children().empty()) {
476 keyboard::MarkKeyboardLoadStarted();
477 aura::Window* keyboard = proxy_->GetKeyboardWindow();
478 keyboard->Show();
479 container_->AddChild(keyboard);
480 keyboard->set_owned_by_parent(false);
483 proxy_->ReloadKeyboardIfNeeded();
485 if (keyboard_visible_) {
486 return;
487 } else if (proxy_->GetKeyboardWindow()->bounds().height() == 0) {
488 show_on_resize_ = true;
489 return;
492 keyboard_visible_ = true;
494 // If the controller is in the process of hiding the keyboard, do not log
495 // the stat here since the keyboard will not actually be shown.
496 if (!WillHideKeyboard())
497 keyboard::LogKeyboardControlEvent(keyboard::KEYBOARD_CONTROL_SHOW);
499 weak_factory_.InvalidateWeakPtrs();
501 // If |container_| has hide animation, its visibility is set to false when
502 // hide animation finished. So even if the container is visible at this
503 // point, it may in the process of hiding. We still need to show keyboard
504 // container in this case.
505 if (container_->IsVisible() &&
506 !container_->layer()->GetAnimator()->is_animating())
507 return;
509 ToggleTouchEventLogging(false);
510 ui::LayerAnimator* container_animator = container_->layer()->GetAnimator();
512 // If the container is not animating, makes sure the position and opacity
513 // are at begin states for animation.
514 if (!container_animator->is_animating()) {
515 gfx::Transform transform;
516 transform.Translate(0, kAnimationDistance);
517 container_->SetTransform(transform);
518 container_->layer()->SetOpacity(kAnimationStartOrAfterHideOpacity);
521 container_animator->set_preemption_strategy(
522 ui::LayerAnimator::IMMEDIATELY_ANIMATE_TO_NEW_TARGET);
523 animation_observer_.reset(new CallbackAnimationObserver(
524 container_animator,
525 base::Bind(&KeyboardController::ShowAnimationFinished,
526 base::Unretained(this))));
527 container_animator->AddObserver(animation_observer_.get());
529 proxy_->ShowKeyboardContainer(container_.get());
532 // Scope the following animation settings as we don't want to animate
533 // visibility change that triggered by a call to the base class function
534 // ShowKeyboardContainer with these settings. The container should become
535 // visible immediately.
536 ui::ScopedLayerAnimationSettings settings(container_animator);
537 settings.SetTweenType(gfx::Tween::LINEAR_OUT_SLOW_IN);
538 settings.SetTransitionDuration(
539 base::TimeDelta::FromMilliseconds(kShowAnimationDurationMs));
540 container_->SetTransform(gfx::Transform());
541 container_->layer()->SetOpacity(1.0);
545 void KeyboardController::ResetWindowInsets() {
546 const gfx::Insets insets;
547 scoped_ptr<content::RenderWidgetHostIterator> widgets(
548 content::RenderWidgetHost::GetRenderWidgetHosts());
549 while (content::RenderWidgetHost* widget = widgets->GetNextHost()) {
550 content::RenderWidgetHostView* view = widget->GetView();
551 if (view)
552 view->SetInsets(insets);
554 window_bounds_observer_->RemoveAllObservedWindows();
557 bool KeyboardController::WillHideKeyboard() const {
558 return weak_factory_.HasWeakPtrs();
561 void KeyboardController::ShowAnimationFinished() {
562 // Notify observers after animation finished to prevent reveal desktop
563 // background during animation.
564 NotifyKeyboardBoundsChanging(container_->bounds());
565 proxy_->EnsureCaretInWorkArea();
568 void KeyboardController::HideAnimationFinished() {
569 proxy_->HideKeyboardContainer(container_.get());
572 void KeyboardController::AddBoundsChangedObserver(aura::Window* window) {
573 aura::Window* target_window = window ? window->GetToplevelWindow() : nullptr;
574 if (target_window)
575 window_bounds_observer_->AddObservedWindow(target_window);
578 } // namespace keyboard