Update To 11.40.268.0
[platform/framework/web/crosswalk.git] / src / ui / keyboard / keyboard_controller.cc
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.
4
5 #include "ui/keyboard/keyboard_controller.h"
6
7 #include <set>
8
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"
31
32 #if defined(OS_CHROMEOS)
33 #include "base/process/launch.h"
34 #include "base/sys_info.h"
35 #endif
36
37 namespace {
38
39 const int kHideKeyboardDelayMs = 100;
40
41 // The virtual keyboard show/hide animation duration.
42 const int kShowAnimationDurationMs = 350;
43 const int kHideAnimationDurationMs = 100;
44
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;
50
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) {
58   }
59
60   ~KeyboardContainerTargeter() override {}
61
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;
71   }
72
73   keyboard::KeyboardControllerProxy* proxy_;
74
75   DISALLOW_COPY_AND_ASSIGN(KeyboardContainerTargeter);
76 };
77
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 {}
87
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;
95   }
96   gfx::NativeCursor GetCursor(const gfx::Point& point) override {
97     return gfx::kNullCursor;
98   }
99   int GetNonClientComponent(const gfx::Point& point) const override {
100     return HTNOWHERE;
101   }
102   bool ShouldDescendIntoChildForEventHandling(
103       aura::Window* child,
104       const gfx::Point& location) override {
105     return true;
106   }
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();
116   }
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));
123   }
124
125   gfx::Rect bounds_;
126   keyboard::KeyboardControllerProxy* proxy_;
127
128   DISALLOW_COPY_AND_ASSIGN(KeyboardWindowDelegate);
129 };
130
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
146 }
147
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.
151   if (!window)
152     return NULL;
153   while (window->parent() && window->parent()->id() < 0) {
154     window = window->parent();
155   }
156   return window;
157 }
158
159 }  // namespace
160
161 namespace keyboard {
162
163 // Observer for both keyboard show and hide animations. It should be owned by
164 // KeyboardController.
165 class CallbackAnimationObserver : public ui::LayerAnimationObserver {
166  public:
167   CallbackAnimationObserver(ui::LayerAnimator* animator,
168                             base::Callback<void(void)> callback);
169   ~CallbackAnimationObserver() override;
170
171  private:
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 {}
176
177   ui::LayerAnimator* animator_;
178   base::Callback<void(void)> callback_;
179
180   DISALLOW_COPY_AND_ASSIGN(CallbackAnimationObserver);
181 };
182
183 CallbackAnimationObserver::CallbackAnimationObserver(
184     ui::LayerAnimator* animator, base::Callback<void(void)> callback)
185     : animator_(animator), callback_(callback) {
186 }
187
188 CallbackAnimationObserver::~CallbackAnimationObserver() {
189   animator_->RemoveObserver(this);
190 }
191
192 void CallbackAnimationObserver::OnLayerAnimationEnded(
193     ui::LayerAnimationSequence* seq) {
194   if (animator_->is_animating())
195     return;
196   animator_->RemoveObserver(this);
197   callback_.Run();
198 }
199
200 void CallbackAnimationObserver::OnLayerAnimationAborted(
201     ui::LayerAnimationSequence* seq) {
202   animator_->RemoveObserver(this);
203 }
204
205 class WindowBoundsChangeObserver : public aura::WindowObserver {
206  public:
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;
211
212   void AddObservedWindow(aura::Window* window);
213   void RemoveAllObservedWindows();
214
215  private:
216   std::set<aura::Window*> observed_windows_;
217 };
218
219 void WindowBoundsChangeObserver::OnWindowBoundsChanged(aura::Window* window,
220     const gfx::Rect& old_bounds, const gfx::Rect& new_bounds) {
221   KeyboardController* controller =  KeyboardController::GetInstance();
222   if (controller)
223     controller->UpdateWindowInsets(window);
224 }
225
226 void WindowBoundsChangeObserver::OnWindowDestroyed(aura::Window* window) {
227   if (window->HasObserver(this))
228     window->RemoveObserver(this);
229   observed_windows_.erase(window);
230 }
231
232 void WindowBoundsChangeObserver::AddObservedWindow(aura::Window* window) {
233   if (!window->HasObserver(this)) {
234     window->AddObserver(this);
235     observed_windows_.insert(window);
236   }
237 }
238
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();
244 }
245
246 // static
247 KeyboardController* KeyboardController::instance_ = NULL;
248
249 KeyboardController::KeyboardController(KeyboardControllerProxy* proxy)
250     : proxy_(proxy),
251       input_method_(NULL),
252       keyboard_visible_(false),
253       show_on_resize_(false),
254       lock_keyboard_(false),
255       type_(ui::TEXT_INPUT_TYPE_NONE),
256       weak_factory_(this) {
257   CHECK(proxy);
258   input_method_ = proxy_->GetInputMethod();
259   input_method_->AddObserver(this);
260   window_bounds_observer_.reset(new WindowBoundsChangeObserver());
261 }
262
263 KeyboardController::~KeyboardController() {
264   if (container_)
265     container_->RemoveObserver(this);
266   if (input_method_)
267     input_method_->RemoveObserver(this);
268   ResetWindowInsets();
269 }
270
271 // static
272 void KeyboardController::ResetInstance(KeyboardController* controller) {
273   if (instance_ && instance_ != controller)
274     delete instance_;
275   instance_ = controller;
276 }
277
278 // static
279 KeyboardController* KeyboardController::GetInstance() {
280   return instance_;
281 }
282
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));
294   }
295   return container_.get();
296 }
297
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,
303                       observer_list_,
304                       OnKeyboardBoundsChanging(new_bounds));
305     if (keyboard::IsKeyboardOverscrollEnabled()) {
306       // Adjust the height of the viewport for visible windows on the primary
307       // display.
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.
318         if (view) {
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,
327                                                       new_bounds);
328             int overlap = intersect.height();
329             if (overlap > 0 && overlap < window_bounds.height())
330               view->SetInsets(gfx::Insets(0, 0, overlap, 0));
331             else
332               view->SetInsets(gfx::Insets());
333             AddBoundsChangedObserver(window);
334           }
335         }
336       }
337     } else {
338       ResetWindowInsets();
339     }
340   } else {
341     current_keyboard_bounds_ = gfx::Rect();
342   }
343 }
344
345 void KeyboardController::HideKeyboard(HideReason reason) {
346   keyboard_visible_ = false;
347   ToggleTouchEventLogging(true);
348
349   keyboard::LogKeyboardControlEvent(
350       reason == HIDE_REASON_AUTOMATIC ?
351           keyboard::KEYBOARD_CONTROL_HIDE_AUTO :
352           keyboard::KEYBOARD_CONTROL_HIDE_USER);
353
354   NotifyKeyboardBoundsChanging(gfx::Rect());
355
356   set_lock_keyboard(false);
357
358   ui::LayerAnimator* container_animator = container_->layer()->GetAnimator();
359   animation_observer_.reset(new CallbackAnimationObserver(
360       container_animator,
361       base::Bind(&KeyboardController::HideAnimationFinished,
362                  base::Unretained(this))));
363   container_animator->AddObserver(animation_observer_.get());
364
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);
373 }
374
375 void KeyboardController::AddObserver(KeyboardControllerObserver* observer) {
376   observer_list_.AddObserver(observer);
377 }
378
379 void KeyboardController::RemoveObserver(KeyboardControllerObserver* observer) {
380   observer_list_.RemoveObserver(observer);
381 }
382
383 void KeyboardController::ShowKeyboard(bool lock) {
384   set_lock_keyboard(lock);
385   ShowKeyboardInternal();
386 }
387
388 void KeyboardController::OnWindowHierarchyChanged(
389     const HierarchyChangeParams& params) {
390   if (params.new_parent && params.target == container_.get())
391     OnTextInputStateChanged(proxy_->GetInputMethod()->GetTextInputClient());
392 }
393
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();
400   }
401 }
402
403 void KeyboardController::OnTextInputStateChanged(
404     const ui::TextInputClient* client) {
405   if (!container_.get())
406     return;
407
408   type_ = client ? client->GetTextInputType() : ui::TEXT_INPUT_TYPE_NONE;
409
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(
416           FROM_HERE,
417           base::Bind(&KeyboardController::HideKeyboard,
418                      weak_factory_.GetWeakPtr(), HIDE_REASON_AUTOMATIC),
419           base::TimeDelta::FromMilliseconds(kHideKeyboardDelayMs));
420     }
421   } else {
422     // Abort a pending keyboard hide.
423     if (WillHideKeyboard()) {
424       weak_factory_.InvalidateWeakPtrs();
425       keyboard_visible_ = true;
426     }
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.
433   }
434 }
435
436 void KeyboardController::OnInputMethodDestroyed(
437     const ui::InputMethod* input_method) {
438   DCHECK_EQ(input_method_, input_method);
439   input_method_ = NULL;
440 }
441
442 void KeyboardController::OnShowImeIfNeeded() {
443   ShowKeyboardInternal();
444 }
445
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() &&
451           keyboard_visible_);
452 }
453
454 void KeyboardController::UpdateWindowInsets(aura::Window* window) {
455   aura::Window *keyboard_window = proxy_->GetKeyboardWindow();
456   if (window == keyboard_window)
457     return;
458
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));
470       else
471         view->SetInsets(gfx::Insets());
472       return;
473     }
474   }
475 }
476
477 void KeyboardController::ShowKeyboardInternal() {
478   if (!container_.get())
479     return;
480
481   if (container_->children().empty()) {
482     keyboard::MarkKeyboardLoadStarted();
483     aura::Window* keyboard = proxy_->GetKeyboardWindow();
484     keyboard->Show();
485     container_->AddChild(keyboard);
486     keyboard->set_owned_by_parent(false);
487   }
488
489   proxy_->ReloadKeyboardIfNeeded();
490
491   if (keyboard_visible_) {
492     return;
493   } else if (proxy_->GetKeyboardWindow()->bounds().height() == 0) {
494     show_on_resize_ = true;
495     return;
496   }
497
498   keyboard_visible_ = true;
499
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);
504
505   weak_factory_.InvalidateWeakPtrs();
506
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())
513     return;
514
515   ToggleTouchEventLogging(false);
516   ui::LayerAnimator* container_animator = container_->layer()->GetAnimator();
517
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);
525   }
526
527   container_animator->set_preemption_strategy(
528       ui::LayerAnimator::IMMEDIATELY_ANIMATE_TO_NEW_TARGET);
529   animation_observer_.reset(new CallbackAnimationObserver(
530       container_animator,
531       base::Bind(&KeyboardController::ShowAnimationFinished,
532                  base::Unretained(this))));
533   container_animator->AddObserver(animation_observer_.get());
534
535   proxy_->ShowKeyboardContainer(container_.get());
536
537   {
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);
548   }
549 }
550
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();
557     if (view)
558       view->SetInsets(insets);
559   }
560   window_bounds_observer_->RemoveAllObservedWindows();
561 }
562
563 bool KeyboardController::WillHideKeyboard() const {
564   return weak_factory_.HasWeakPtrs();
565 }
566
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();
572 }
573
574 void KeyboardController::HideAnimationFinished() {
575   proxy_->HideKeyboardContainer(container_.get());
576 }
577
578 void KeyboardController::AddBoundsChangedObserver(aura::Window* window) {
579   aura::Window* target_window = GetFrameWindow(window);
580   if (target_window)
581     window_bounds_observer_->AddObservedWindow(target_window);
582 }
583
584 }  // namespace keyboard