Revert "If the currently focused actor is hidden, it should lose focus. and If VISIBL...
[platform/core/uifw/dali-toolkit.git] / dali-toolkit / internal / focus-manager / keyboard-focus-manager-impl.cpp
1 /*
2  * Copyright (c) 2022 Samsung Electronics Co., Ltd.
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  * http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  *
16  */
17
18 // CLASS HEADER
19 #include "keyboard-focus-manager-impl.h"
20
21 // EXTERNAL INCLUDES
22 #include <dali/devel-api/actors/actor-devel.h>
23 #include <dali/devel-api/adaptor-framework/lifecycle-controller.h>
24 #include <dali/devel-api/common/singleton-service.h>
25 #include <dali/integration-api/adaptor-framework/adaptor.h>
26 #include <dali/integration-api/adaptor-framework/scene-holder.h>
27 #include <dali/integration-api/debug.h>
28 #include <dali/public-api/actors/layer.h>
29 #include <dali/public-api/animation/constraints.h>
30 #include <dali/public-api/events/key-event.h>
31 #include <dali/public-api/events/touch-event.h>
32 #include <dali/public-api/events/wheel-event.h>
33 #include <dali/public-api/object/property-map.h>
34 #include <dali/public-api/object/type-registry-helper.h>
35 #include <dali/public-api/object/type-registry.h>
36 #include <cstring> // for strcmp
37
38 // INTERNAL INCLUDES
39 #include <dali-toolkit/devel-api/asset-manager/asset-manager.h>
40 #include <dali-toolkit/devel-api/controls/control-devel.h>
41 #include <dali-toolkit/devel-api/focus-manager/focus-finder.h>
42 #include <dali-toolkit/devel-api/styling/style-manager-devel.h>
43 #include <dali-toolkit/public-api/controls/control-impl.h>
44 #include <dali-toolkit/public-api/controls/control.h>
45 #include <dali-toolkit/public-api/controls/image-view/image-view.h>
46 #include <dali-toolkit/public-api/styling/style-manager.h>
47 #include <dali/devel-api/adaptor-framework/accessibility.h>
48
49 namespace Dali
50 {
51 namespace Toolkit
52 {
53 namespace Internal
54 {
55 namespace // Unnamed namespace
56 {
57 #if defined(DEBUG_ENABLED)
58 Debug::Filter* gLogFilter = Debug::Filter::New(Debug::NoLogging, false, "LOG_KEYBOARD_FOCUS_MANAGER");
59 #endif
60
61 const char* const IS_FOCUS_GROUP_PROPERTY_NAME = "isKeyboardFocusGroup"; // This property will be replaced by a flag in Control.
62
63 const char* const FOCUS_BORDER_IMAGE_FILE_NAME = "keyboard_focus.9.png";
64
65 BaseHandle Create()
66 {
67   BaseHandle handle = KeyboardFocusManager::Get();
68
69   if(!handle)
70   {
71     SingletonService singletonService(SingletonService::Get());
72     if(singletonService)
73     {
74       Toolkit::KeyboardFocusManager manager = Toolkit::KeyboardFocusManager(new Internal::KeyboardFocusManager());
75       singletonService.Register(typeid(manager), manager);
76       handle = manager;
77     }
78   }
79
80   return handle;
81 }
82
83 DALI_TYPE_REGISTRATION_BEGIN_CREATE(Toolkit::KeyboardFocusManager, Dali::BaseHandle, Create, true)
84
85 DALI_SIGNAL_REGISTRATION(Toolkit, KeyboardFocusManager, "keyboardPreFocusChange", SIGNAL_PRE_FOCUS_CHANGE)
86 DALI_SIGNAL_REGISTRATION(Toolkit, KeyboardFocusManager, "keyboardFocusChanged", SIGNAL_FOCUS_CHANGED)
87 DALI_SIGNAL_REGISTRATION(Toolkit, KeyboardFocusManager, "keyboardFocusGroupChanged", SIGNAL_FOCUS_GROUP_CHANGED)
88 DALI_SIGNAL_REGISTRATION(Toolkit, KeyboardFocusManager, "keyboardFocusedActorEnterKey", SIGNAL_FOCUSED_ACTOR_ENTER_KEY)
89
90 DALI_TYPE_REGISTRATION_END()
91
92 const unsigned int MAX_HISTORY_AMOUNT = 30; ///< Max length of focus history stack
93
94 } // unnamed namespace
95
96 Toolkit::KeyboardFocusManager KeyboardFocusManager::Get()
97 {
98   Toolkit::KeyboardFocusManager manager;
99
100   SingletonService singletonService(SingletonService::Get());
101   if(singletonService)
102   {
103     // Check whether the keyboard focus manager is already created
104     Dali::BaseHandle handle = singletonService.GetSingleton(typeid(Toolkit::KeyboardFocusManager));
105     if(handle)
106     {
107       // If so, downcast the handle of singleton to keyboard focus manager
108       manager = Toolkit::KeyboardFocusManager(dynamic_cast<KeyboardFocusManager*>(handle.GetObjectPtr()));
109     }
110   }
111
112   return manager;
113 }
114
115 KeyboardFocusManager::KeyboardFocusManager()
116 : mPreFocusChangeSignal(),
117   mFocusChangedSignal(),
118   mFocusGroupChangedSignal(),
119   mFocusedActorEnterKeySignal(),
120   mCurrentFocusActor(),
121   mFocusIndicatorActor(),
122   mFocusFinderRootActor(),
123   mFocusHistory(),
124   mSlotDelegate(this),
125   mCustomAlgorithmInterface(NULL),
126   mCurrentFocusedWindow(),
127   mIsFocusIndicatorShown(UNKNOWN),
128   mEnableFocusIndicator(ENABLE),
129   mAlwaysShowIndicator(ALWAYS_SHOW),
130   mFocusGroupLoopEnabled(false),
131   mIsWaitingKeyboardFocusChangeCommit(false),
132   mClearFocusOnTouch(true),
133   mEnableDefaultAlgorithm(false)
134 {
135   // TODO: Get FocusIndicatorEnable constant from stylesheet to set mIsFocusIndicatorShown.
136
137   LifecycleController::Get().InitSignal().Connect(mSlotDelegate, &KeyboardFocusManager::OnAdaptorInit);
138 }
139
140 void KeyboardFocusManager::OnAdaptorInit()
141 {
142   if(Adaptor::IsAvailable())
143   {
144     // Retrieve all the existing scene holders
145     Dali::SceneHolderList sceneHolders = Adaptor::Get().GetSceneHolders();
146     for(auto iter = sceneHolders.begin(); iter != sceneHolders.end(); ++iter)
147     {
148       (*iter).KeyEventSignal().Connect(mSlotDelegate, &KeyboardFocusManager::OnKeyEvent);
149       (*iter).TouchedSignal().Connect(mSlotDelegate, &KeyboardFocusManager::OnTouch);
150       (*iter).WheelEventGeneratedSignal().Connect(mSlotDelegate, &KeyboardFocusManager::OnCustomWheelEvent);
151       (*iter).WheelEventSignal().Connect(mSlotDelegate, &KeyboardFocusManager::OnWheelEvent);
152       Dali::Window window = DevelWindow::DownCast(*iter);
153       if(window)
154       {
155         window.FocusChangeSignal().Connect(mSlotDelegate, &KeyboardFocusManager::OnWindowFocusChanged);
156       }
157     }
158
159     // Get notified when any new scene holder is created afterwards
160     Adaptor::Get().WindowCreatedSignal().Connect(mSlotDelegate, &KeyboardFocusManager::OnSceneHolderCreated);
161   }
162 }
163
164 void KeyboardFocusManager::OnSceneHolderCreated(Dali::Integration::SceneHolder& sceneHolder)
165 {
166   sceneHolder.KeyEventSignal().Connect(mSlotDelegate, &KeyboardFocusManager::OnKeyEvent);
167   sceneHolder.TouchedSignal().Connect(mSlotDelegate, &KeyboardFocusManager::OnTouch);
168   sceneHolder.WheelEventGeneratedSignal().Connect(mSlotDelegate, &KeyboardFocusManager::OnCustomWheelEvent);
169   sceneHolder.WheelEventSignal().Connect(mSlotDelegate, &KeyboardFocusManager::OnWheelEvent);
170   Dali::Window window = DevelWindow::DownCast(sceneHolder);
171   if(window)
172   {
173     window.FocusChangeSignal().Connect(mSlotDelegate, &KeyboardFocusManager::OnWindowFocusChanged);
174   }
175 }
176
177 KeyboardFocusManager::~KeyboardFocusManager()
178 {
179 }
180
181 void KeyboardFocusManager::GetConfigurationFromStyleManger()
182 {
183   Toolkit::StyleManager styleManager = Toolkit::StyleManager::Get();
184   if(styleManager)
185   {
186     const Property::Map& config               = Toolkit::DevelStyleManager::GetConfigurations(styleManager);
187     const auto           alwaysShowFocusValue = config.Find("alwaysShowFocus", Property::Type::BOOLEAN);
188
189     mAlwaysShowIndicator   = (alwaysShowFocusValue && alwaysShowFocusValue->Get<bool>()) ? ALWAYS_SHOW : NONE;
190     mIsFocusIndicatorShown = (mAlwaysShowIndicator == ALWAYS_SHOW) ? SHOW : HIDE;
191     mClearFocusOnTouch     = (mIsFocusIndicatorShown == SHOW) ? false : true;
192   }
193 }
194
195 bool KeyboardFocusManager::SetCurrentFocusActor(Actor actor)
196 {
197   DALI_ASSERT_DEBUG(!mIsWaitingKeyboardFocusChangeCommit && "Calling this function in the PreFocusChangeSignal callback?");
198
199   if(mIsFocusIndicatorShown == UNKNOWN)
200   {
201     GetConfigurationFromStyleManger();
202   }
203
204   return DoSetCurrentFocusActor(actor);
205 }
206
207 bool KeyboardFocusManager::DoSetCurrentFocusActor(Actor actor)
208 {
209   bool success = false;
210
211   // Check whether the actor is in the stage and is keyboard focusable.
212   if(actor &&
213      actor.GetProperty<bool>(Actor::Property::KEYBOARD_FOCUSABLE) &&
214      actor.GetProperty<bool>(DevelActor::Property::USER_INTERACTION_ENABLED) &&
215      actor.GetProperty<bool>(Actor::Property::CONNECTED_TO_SCENE))
216   {
217     // If the parent's KEYBOARD_FOCUSABLE_CHILDREN is false, it cannot have focus.
218     Actor parent = actor.GetParent();
219     while(parent)
220     {
221       if(!parent.GetProperty<bool>(DevelActor::Property::KEYBOARD_FOCUSABLE_CHILDREN))
222       {
223         DALI_LOG_INFO(gLogFilter, Debug::General, "[%s:%d] Parent Actor has KEYBOARD_FOCUSABLE_CHILDREN false\n", __FUNCTION__, __LINE__);
224         return false;
225       }
226       parent = parent.GetParent();
227     }
228
229     // If developer set focus on same actor, doing nothing
230     Actor currentFocusedActor = GetCurrentFocusActor();
231     if(actor == currentFocusedActor)
232     {
233       return true;
234     }
235
236     Integration::SceneHolder currentWindow = Integration::SceneHolder::Get(actor);
237     if(currentWindow.GetRootLayer() != mCurrentFocusedWindow.GetHandle())
238     {
239       Layer rootLayer       = currentWindow.GetRootLayer();
240       mCurrentFocusedWindow = rootLayer;
241     }
242
243     if((mIsFocusIndicatorShown == SHOW) && (mEnableFocusIndicator == ENABLE))
244     {
245       actor.Add(GetFocusIndicatorActor());
246     }
247
248     // Save the current focused actor
249     mCurrentFocusActor = actor;
250
251     bool focusedWindowFound = false;
252     for(unsigned int i = 0; i < mCurrentFocusActors.size(); i++)
253     {
254       if(mCurrentFocusActors[i].first == mCurrentFocusedWindow)
255       {
256         mCurrentFocusActors[i].second = actor;
257         focusedWindowFound            = true;
258         break;
259       }
260     }
261     if(!focusedWindowFound)
262     {
263       // A new window gains the focus, so store the focused actor in that window.
264       mCurrentFocusActors.push_back(std::pair<WeakHandle<Layer>, WeakHandle<Actor> >(mCurrentFocusedWindow, actor));
265     }
266
267     // Send notification for the change of focus actor
268     if(!mFocusChangedSignal.Empty())
269     {
270       mFocusChangedSignal.Emit(currentFocusedActor, actor);
271     }
272
273     Toolkit::Control currentlyFocusedControl = Toolkit::Control::DownCast(currentFocusedActor);
274     if(currentlyFocusedControl)
275     {
276       // Do we need it to remember if it was previously DISABLED?
277       currentlyFocusedControl.SetProperty(DevelControl::Property::STATE, DevelControl::NORMAL);
278       currentlyFocusedControl.ClearKeyInputFocus();
279     }
280
281     Toolkit::Control newlyFocusedControl = Toolkit::Control::DownCast(actor);
282     if(newlyFocusedControl)
283     {
284       newlyFocusedControl.SetProperty(DevelControl::Property::STATE, DevelControl::FOCUSED);
285       newlyFocusedControl.SetKeyInputFocus();
286     }
287
288     // Push Current Focused Actor to FocusHistory
289     mFocusHistory.push_back(actor);
290
291     // Delete first element before add new element when Stack is full.
292     if(mFocusHistory.size() > MAX_HISTORY_AMOUNT)
293     {
294       FocusStackIterator beginPos = mFocusHistory.begin();
295       mFocusHistory.erase(beginPos);
296     }
297
298     DALI_LOG_INFO(gLogFilter, Debug::General, "[%s:%d] SUCCEED\n", __FUNCTION__, __LINE__);
299     success = true;
300   }
301   else
302   {
303     DALI_LOG_WARNING("[%s:%d] FAILED\n", __FUNCTION__, __LINE__);
304   }
305
306   return success;
307 }
308
309 Actor KeyboardFocusManager::GetCurrentFocusActor()
310 {
311   Actor actor = mCurrentFocusActor.GetHandle();
312
313   if(actor && !actor.GetProperty<bool>(Actor::Property::CONNECTED_TO_SCENE))
314   {
315     // If the actor has been removed from the stage, then it should not be focused
316     actor.Reset();
317     mCurrentFocusActor.Reset();
318   }
319   return actor;
320 }
321
322 Actor KeyboardFocusManager::GetFocusActorFromCurrentWindow()
323 {
324   Actor        actor;
325   unsigned int index;
326   for(index = 0; index < mCurrentFocusActors.size(); index++)
327   {
328     if(mCurrentFocusActors[index].first == mCurrentFocusedWindow)
329     {
330       actor = mCurrentFocusActors[index].second.GetHandle();
331       break;
332     }
333   }
334
335   if(actor && !actor.GetProperty<bool>(Actor::Property::CONNECTED_TO_SCENE))
336   {
337     // If the actor has been removed from the window, then the window doesn't have any focused actor
338     actor.Reset();
339     mCurrentFocusActors.erase(mCurrentFocusActors.begin() + index);
340   }
341
342   return actor;
343 }
344
345 Actor KeyboardFocusManager::GetCurrentFocusGroup()
346 {
347   return GetFocusGroup(GetCurrentFocusActor());
348 }
349
350 void KeyboardFocusManager::MoveFocusBackward()
351 {
352   // Find Pre Focused Actor when the list size is more than 1
353   if(mFocusHistory.size() > 1)
354   {
355     // Delete current focused actor in history
356     mFocusHistory.pop_back();
357
358     // If pre-focused actors are not on stage or deleted, remove them in stack
359     while(mFocusHistory.size() > 0)
360     {
361       // Get pre focused actor
362       Actor target = mFocusHistory[mFocusHistory.size() - 1].GetHandle();
363
364       // Impl of Actor is not null
365       if(target && target.GetProperty<bool>(Actor::Property::CONNECTED_TO_SCENE))
366       {
367         // Delete pre focused actor in history because it will pushed again by SetCurrentFocusActor()
368         mFocusHistory.pop_back();
369         SetCurrentFocusActor(target);
370         break;
371       }
372       else
373       {
374         // Target is empty handle or off stage. Erase from queue
375         mFocusHistory.pop_back();
376       }
377     }
378
379     // if there is no actor which can get focus, then push current focus actor in stack again
380     if(mFocusHistory.size() == 0)
381     {
382       Actor currentFocusedActor = GetCurrentFocusActor();
383       mFocusHistory.push_back(currentFocusedActor);
384     }
385   }
386 }
387
388 bool KeyboardFocusManager::IsLayoutControl(Actor actor) const
389 {
390   Toolkit::Control control = Toolkit::Control::DownCast(actor);
391   return control && GetImplementation(control).IsKeyboardNavigationSupported();
392 }
393
394 Toolkit::Control KeyboardFocusManager::GetParentLayoutControl(Actor actor) const
395 {
396   // Get the actor's parent layout control that supports two dimensional keyboard navigation
397   Actor rootActor;
398   Actor parent;
399   if(actor)
400   {
401     Integration::SceneHolder window = Integration::SceneHolder::Get(actor);
402     if(window)
403     {
404       rootActor = window.GetRootLayer();
405     }
406
407     parent = actor.GetParent();
408   }
409
410   while(parent && !IsLayoutControl(parent) && parent != rootActor)
411   {
412     parent = parent.GetParent();
413   }
414
415   return Toolkit::Control::DownCast(parent);
416 }
417
418 bool KeyboardFocusManager::MoveFocus(Toolkit::Control::KeyboardFocus::Direction direction, const std::string& deviceName)
419 {
420   Actor currentFocusActor = GetCurrentFocusActor();
421
422   bool succeed = false;
423
424   // Go through the actor's hierarchy until we find a layout control that knows how to move the focus
425   Toolkit::Control layoutControl = IsLayoutControl(currentFocusActor) ? Toolkit::Control::DownCast(currentFocusActor) : GetParentLayoutControl(currentFocusActor);
426   while(layoutControl && !succeed)
427   {
428     succeed       = DoMoveFocusWithinLayoutControl(layoutControl, currentFocusActor, direction);
429     layoutControl = GetParentLayoutControl(layoutControl);
430   }
431
432   if(!succeed)
433   {
434     Actor nextFocusableActor;
435
436     Toolkit::Control currentFocusControl = Toolkit::Control::DownCast(currentFocusActor);
437
438     // If the current focused actor is a control, then find the next focusable actor via the focusable properties.
439     if(currentFocusControl)
440     {
441       int             actorId = -1;
442       Property::Index index   = Property::INVALID_INDEX;
443       Property::Value value;
444
445       // Find property index based upon focus direction
446       switch(direction)
447       {
448         case Toolkit::Control::KeyboardFocus::LEFT:
449         {
450           index = Toolkit::DevelControl::Property::LEFT_FOCUSABLE_ACTOR_ID;
451           break;
452         }
453         case Toolkit::Control::KeyboardFocus::RIGHT:
454         {
455           index = Toolkit::DevelControl::Property::RIGHT_FOCUSABLE_ACTOR_ID;
456           break;
457         }
458         case Toolkit::Control::KeyboardFocus::UP:
459         {
460           index = Toolkit::DevelControl::Property::UP_FOCUSABLE_ACTOR_ID;
461           break;
462         }
463         case Toolkit::Control::KeyboardFocus::DOWN:
464         {
465           index = Toolkit::DevelControl::Property::DOWN_FOCUSABLE_ACTOR_ID;
466           break;
467         }
468         case Toolkit::Control::KeyboardFocus::CLOCKWISE:
469         {
470           index = Toolkit::DevelControl::Property::CLOCKWISE_FOCUSABLE_ACTOR_ID;
471           break;
472         }
473         case Toolkit::Control::KeyboardFocus::COUNTER_CLOCKWISE:
474         {
475           index = Toolkit::DevelControl::Property::COUNTER_CLOCKWISE_FOCUSABLE_ACTOR_ID;
476           break;
477         }
478         default:
479           break;
480       }
481
482       // If the focusable property is set then determine next focusable actor
483       if(index != Property::INVALID_INDEX)
484       {
485         value   = currentFocusActor.GetProperty(index);
486         actorId = value.Get<int>();
487
488         // If actor's id is valid then find actor form actor's id. The actor should be on the stage.
489         if(actorId != -1)
490         {
491           if(currentFocusActor.GetParent())
492           {
493             nextFocusableActor = currentFocusActor.GetParent().FindChildById(actorId);
494           }
495
496           if(!nextFocusableActor)
497           {
498             Integration::SceneHolder window = Integration::SceneHolder::Get(currentFocusActor);
499             if(window)
500             {
501               nextFocusableActor = window.GetRootLayer().FindChildById(actorId);
502             }
503           }
504         }
505       }
506     }
507
508     if(!nextFocusableActor)
509     {
510       // If the implementation of CustomAlgorithmInterface is provided then the PreFocusChangeSignal is no longer emitted.
511       if(mCustomAlgorithmInterface)
512       {
513         mIsWaitingKeyboardFocusChangeCommit = true;
514         nextFocusableActor                  = mCustomAlgorithmInterface->GetNextFocusableActor(currentFocusActor, Actor(), direction, deviceName);
515         mIsWaitingKeyboardFocusChangeCommit = false;
516       }
517       else if(!mPreFocusChangeSignal.Empty())
518       {
519         // Don't know how to move the focus further. The application needs to tell us which actor to move the focus to
520         mIsWaitingKeyboardFocusChangeCommit = true;
521         nextFocusableActor                  = mPreFocusChangeSignal.Emit(currentFocusActor, Actor(), direction);
522         mIsWaitingKeyboardFocusChangeCommit = false;
523       }
524       else if(mEnableDefaultAlgorithm)
525       {
526         Actor rootActor = mFocusFinderRootActor.GetHandle();
527         if(!rootActor)
528         {
529           if(currentFocusActor)
530           {
531             // Find the window of the focused actor.
532             Integration::SceneHolder window = Integration::SceneHolder::Get(currentFocusActor);
533             if(window)
534             {
535               rootActor = window.GetRootLayer();
536             }
537           }
538           else
539           {
540             // Searches from the currently focused window.
541             rootActor = mCurrentFocusedWindow.GetHandle();
542           }
543         }
544         if(rootActor)
545         {
546           // We should find it among the actors nearby.
547           nextFocusableActor = Toolkit::FocusFinder::GetNearestFocusableActor(rootActor, currentFocusActor, direction);
548         }
549       }
550     }
551
552     if(nextFocusableActor && nextFocusableActor.GetProperty<bool>(Actor::Property::KEYBOARD_FOCUSABLE) && nextFocusableActor.GetProperty<bool>(DevelActor::Property::USER_INTERACTION_ENABLED))
553     {
554       // Whether the next focusable actor is a layout control
555       if(IsLayoutControl(nextFocusableActor))
556       {
557         // If so, move the focus inside it.
558         Toolkit::Control layoutControl = Toolkit::Control::DownCast(nextFocusableActor);
559         succeed                        = DoMoveFocusWithinLayoutControl(layoutControl, currentFocusActor, direction);
560       }
561       if(!succeed)
562       {
563         // Just set focus to the next focusable actor
564         succeed = SetCurrentFocusActor(nextFocusableActor);
565       }
566     }
567   }
568
569   return succeed;
570 }
571
572 bool KeyboardFocusManager::DoMoveFocusWithinLayoutControl(Toolkit::Control control, Actor actor, Toolkit::Control::KeyboardFocus::Direction direction)
573 {
574   // Ask the control for the next actor to focus
575   Actor nextFocusableActor = GetImplementation(control).GetNextKeyboardFocusableActor(actor, direction, mFocusGroupLoopEnabled);
576   if(nextFocusableActor)
577   {
578     if(!(nextFocusableActor.GetProperty<bool>(Actor::Property::KEYBOARD_FOCUSABLE) || nextFocusableActor.GetProperty<bool>(DevelActor::Property::USER_INTERACTION_ENABLED)))
579     {
580       // If the actor is not focusable, ask the same layout control for the next actor to focus
581       return DoMoveFocusWithinLayoutControl(control, nextFocusableActor, direction);
582     }
583     else
584     {
585       Actor currentFocusActor   = GetCurrentFocusActor();
586       Actor committedFocusActor = nextFocusableActor;
587
588       // We will try to move the focus to the actor. Emit a signal to notify the proposed actor to focus
589       // Signal handler can check the proposed actor and return a different actor if it wishes.
590       if(!mPreFocusChangeSignal.Empty())
591       {
592         mIsWaitingKeyboardFocusChangeCommit = true;
593         committedFocusActor                 = mPreFocusChangeSignal.Emit(currentFocusActor, nextFocusableActor, direction);
594         mIsWaitingKeyboardFocusChangeCommit = false;
595       }
596
597       if(committedFocusActor && committedFocusActor.GetProperty<bool>(Actor::Property::KEYBOARD_FOCUSABLE) && committedFocusActor.GetProperty<bool>(DevelActor::Property::USER_INTERACTION_ENABLED))
598       {
599         // Whether the commited focusable actor is a layout control
600         if(IsLayoutControl(committedFocusActor) && committedFocusActor != control)
601         {
602           // If so, move the focus inside it.
603           Toolkit::Control layoutControl = Toolkit::Control::DownCast(committedFocusActor);
604           return DoMoveFocusWithinLayoutControl(layoutControl, currentFocusActor, direction);
605         }
606         else
607         {
608           // Otherwise, just set focus to the next focusable actor
609           if(committedFocusActor == nextFocusableActor)
610           {
611             // If the application hasn't changed our proposed actor, we informs the layout control we will
612             // move the focus to what the control returns. The control might wish to perform some actions
613             // before the focus is actually moved.
614             GetImplementation(control).OnKeyboardFocusChangeCommitted(committedFocusActor);
615           }
616
617           return SetCurrentFocusActor(committedFocusActor);
618         }
619       }
620       else
621       {
622         return false;
623       }
624     }
625   }
626   else
627   {
628     // No more actor can be focused in the given direction within the same layout control.
629     return false;
630   }
631 }
632
633 bool KeyboardFocusManager::DoMoveFocusToNextFocusGroup(bool forward)
634 {
635   bool succeed = false;
636
637   // Get the parent layout control of the current focus group
638   Toolkit::Control parentLayoutControl = GetParentLayoutControl(GetCurrentFocusGroup());
639
640   while(parentLayoutControl && !succeed)
641   {
642     // If the current focus group has a parent layout control, we can probably automatically
643     // move the focus to the next focus group in the forward or backward direction.
644     Toolkit::Control::KeyboardFocus::Direction direction = forward ? Toolkit::Control::KeyboardFocus::RIGHT : Toolkit::Control::KeyboardFocus::LEFT;
645     succeed                                              = DoMoveFocusWithinLayoutControl(parentLayoutControl, GetCurrentFocusActor(), direction);
646     parentLayoutControl                                  = GetParentLayoutControl(parentLayoutControl);
647   }
648
649   if(!mFocusGroupChangedSignal.Empty())
650   {
651     // Emit a focus group changed signal. The applicaton can move the focus to a new focus group
652     mFocusGroupChangedSignal.Emit(GetCurrentFocusActor(), forward);
653   }
654
655   return succeed;
656 }
657
658 void KeyboardFocusManager::DoKeyboardEnter(Actor actor)
659 {
660   if(actor)
661   {
662     Toolkit::Control control = Toolkit::Control::DownCast(actor);
663     if(control)
664     {
665       // Notify the control that enter has been pressed on it.
666       GetImplementation(control).KeyboardEnter();
667     }
668
669     // Send a notification for the actor.
670     if(!mFocusedActorEnterKeySignal.Empty())
671     {
672       mFocusedActorEnterKeySignal.Emit(actor);
673     }
674   }
675 }
676
677 void KeyboardFocusManager::ClearFocus()
678 {
679   ClearFocusIndicator();
680   Actor actor = GetCurrentFocusActor();
681   if(actor)
682   {
683     // Send notification for the change of focus actor
684     if(!mFocusChangedSignal.Empty())
685     {
686       mFocusChangedSignal.Emit(actor, Actor());
687     }
688
689     Toolkit::Control currentlyFocusedControl = Toolkit::Control::DownCast(actor);
690     if(currentlyFocusedControl)
691     {
692       currentlyFocusedControl.SetProperty(DevelControl::Property::STATE, DevelControl::NORMAL);
693       currentlyFocusedControl.ClearKeyInputFocus();
694     }
695   }
696   mCurrentFocusActor.Reset();
697 }
698
699 void KeyboardFocusManager::ClearFocusIndicator()
700 {
701   Actor actor = GetCurrentFocusActor();
702   if(actor)
703   {
704     if(mFocusIndicatorActor)
705     {
706       actor.Remove(mFocusIndicatorActor);
707     }
708   }
709   mIsFocusIndicatorShown = (mAlwaysShowIndicator == ALWAYS_SHOW) ? SHOW : HIDE;
710 }
711
712 void KeyboardFocusManager::SetFocusGroupLoop(bool enabled)
713 {
714   mFocusGroupLoopEnabled = enabled;
715 }
716
717 bool KeyboardFocusManager::GetFocusGroupLoop() const
718 {
719   return mFocusGroupLoopEnabled;
720 }
721
722 void KeyboardFocusManager::SetAsFocusGroup(Actor actor, bool isFocusGroup)
723 {
724   if(actor)
725   {
726     // Create/Set focus group property.
727     actor.RegisterProperty(IS_FOCUS_GROUP_PROPERTY_NAME, isFocusGroup, Property::READ_WRITE);
728   }
729 }
730
731 bool KeyboardFocusManager::IsFocusGroup(Actor actor) const
732 {
733   // Check whether the actor is a focus group
734   bool isFocusGroup = false;
735
736   if(actor)
737   {
738     Property::Index propertyIsFocusGroup = actor.GetPropertyIndex(IS_FOCUS_GROUP_PROPERTY_NAME);
739     if(propertyIsFocusGroup != Property::INVALID_INDEX)
740     {
741       isFocusGroup = actor.GetProperty<bool>(propertyIsFocusGroup);
742     }
743   }
744
745   return isFocusGroup;
746 }
747
748 Actor KeyboardFocusManager::GetFocusGroup(Actor actor)
749 {
750   // Go through the actor's hierarchy to check which focus group the actor belongs to
751   while(actor && !IsFocusGroup(actor))
752   {
753     actor = actor.GetParent();
754   }
755
756   return actor;
757 }
758
759 void KeyboardFocusManager::SetFocusIndicatorActor(Actor indicator)
760 {
761   if(mFocusIndicatorActor != indicator)
762   {
763     Actor currentFocusActor = GetCurrentFocusActor();
764     if(currentFocusActor)
765     {
766       // The new focus indicator should be added to the current focused actor immediately
767       if(mFocusIndicatorActor)
768       {
769         currentFocusActor.Remove(mFocusIndicatorActor);
770       }
771
772       if(indicator)
773       {
774         currentFocusActor.Add(indicator);
775       }
776     }
777
778     mFocusIndicatorActor = indicator;
779   }
780 }
781
782 Actor KeyboardFocusManager::GetFocusIndicatorActor()
783 {
784   if(!mFocusIndicatorActor)
785   {
786     // Create the default if it hasn't been set and one that's shared by all the keyboard focusable actors
787     const std::string imageDirPath = AssetManager::GetDaliImagePath();
788     mFocusIndicatorActor           = Toolkit::ImageView::New(imageDirPath + FOCUS_BORDER_IMAGE_FILE_NAME);
789
790     // Apply size constraint to the focus indicator
791     mFocusIndicatorActor.SetResizePolicy(ResizePolicy::FILL_TO_PARENT, Dimension::ALL_DIMENSIONS);
792   }
793
794   mFocusIndicatorActor.SetProperty(Actor::Property::PARENT_ORIGIN, ParentOrigin::CENTER);
795   mFocusIndicatorActor.SetProperty(Actor::Property::ANCHOR_POINT, AnchorPoint::CENTER);
796   mFocusIndicatorActor.SetProperty(Actor::Property::POSITION, Vector2(0.0f, 0.0f));
797
798   return mFocusIndicatorActor;
799 }
800
801 void KeyboardFocusManager::OnKeyEvent(const KeyEvent& event)
802 {
803   const std::string& keyName    = event.GetKeyName();
804   const std::string& deviceName = event.GetDeviceName();
805
806   if(mIsFocusIndicatorShown == UNKNOWN)
807   {
808     GetConfigurationFromStyleManger();
809   }
810
811   bool isFocusStartableKey = false;
812
813   if(event.GetState() == KeyEvent::DOWN)
814   {
815     if(keyName == "Left")
816     {
817       if(mIsFocusIndicatorShown == HIDE)
818       {
819         // Show focus indicator
820         mIsFocusIndicatorShown = SHOW;
821       }
822       else
823       {
824         // Move the focus towards left
825         MoveFocus(Toolkit::Control::KeyboardFocus::LEFT, deviceName);
826       }
827
828       isFocusStartableKey = true;
829     }
830     else if(keyName == "Right")
831     {
832       if(mIsFocusIndicatorShown == HIDE)
833       {
834         // Show focus indicator
835         mIsFocusIndicatorShown = SHOW;
836       }
837       else
838       {
839         // Move the focus towards right
840         MoveFocus(Toolkit::Control::KeyboardFocus::RIGHT, deviceName);
841       }
842
843       isFocusStartableKey = true;
844     }
845     else if(keyName == "Up")
846     {
847       if(mIsFocusIndicatorShown == HIDE)
848       {
849         // Show focus indicator
850         mIsFocusIndicatorShown = SHOW;
851       }
852       else
853       {
854         // Move the focus towards up
855         MoveFocus(Toolkit::Control::KeyboardFocus::UP, deviceName);
856       }
857
858       isFocusStartableKey = true;
859     }
860     else if(keyName == "Down")
861     {
862       if(mIsFocusIndicatorShown == HIDE)
863       {
864         // Show focus indicator
865         mIsFocusIndicatorShown = SHOW;
866       }
867       else
868       {
869         // Move the focus towards down
870         MoveFocus(Toolkit::Control::KeyboardFocus::DOWN, deviceName);
871       }
872
873       isFocusStartableKey = true;
874     }
875     else if(keyName == "Prior")
876     {
877       if(mIsFocusIndicatorShown == HIDE)
878       {
879         // Show focus indicator
880         mIsFocusIndicatorShown = SHOW;
881       }
882       else
883       {
884         // Move the focus towards the previous page
885         MoveFocus(Toolkit::Control::KeyboardFocus::PAGE_UP, deviceName);
886       }
887
888       isFocusStartableKey = true;
889     }
890     else if(keyName == "Next")
891     {
892       if(mIsFocusIndicatorShown == HIDE)
893       {
894         // Show focus indicator
895         mIsFocusIndicatorShown = SHOW;
896       }
897       else
898       {
899         // Move the focus towards the next page
900         MoveFocus(Toolkit::Control::KeyboardFocus::PAGE_DOWN, deviceName);
901       }
902
903       isFocusStartableKey = true;
904     }
905     else if(keyName == "Tab")
906     {
907       if(mIsFocusIndicatorShown == HIDE)
908       {
909         // Show focus indicator
910         mIsFocusIndicatorShown = SHOW;
911       }
912       else
913       {
914         // "Tab" key changes the focus group in the forward direction and
915         // "Shift-Tab" key changes it in the backward direction.
916         if(!DoMoveFocusToNextFocusGroup(!event.IsShiftModifier()))
917         {
918           // If the focus group is not changed, Move the focus towards forward, "Shift-Tap" key moves the focus towards backward.
919           MoveFocus(event.IsShiftModifier() ? Toolkit::Control::KeyboardFocus::BACKWARD : Toolkit::Control::KeyboardFocus::FORWARD, deviceName);
920         }
921       }
922
923       isFocusStartableKey = true;
924     }
925     else if(keyName == "space")
926     {
927       if(mIsFocusIndicatorShown == HIDE)
928       {
929         // Show focus indicator
930         mIsFocusIndicatorShown = SHOW;
931       }
932
933       isFocusStartableKey = true;
934     }
935     else if(keyName == "")
936     {
937       // Check the fake key event for evas-plugin case
938       if(mIsFocusIndicatorShown == HIDE)
939       {
940         // Show focus indicator
941         mIsFocusIndicatorShown = SHOW;
942       }
943
944       isFocusStartableKey = true;
945     }
946     else if(keyName == "Backspace")
947     {
948       // Emit signal to go back to the previous view???
949     }
950     else if(keyName == "Escape")
951     {
952     }
953   }
954   else if(event.GetState() == KeyEvent::UP)
955   {
956     if(keyName == "Return")
957     {
958       if(mIsFocusIndicatorShown == HIDE)
959       {
960         // Show focus indicator
961         mIsFocusIndicatorShown = SHOW;
962       }
963       else
964       {
965         // The focused actor has enter pressed on it
966         Actor actor = GetCurrentFocusActor();
967         if(actor)
968         {
969           DoKeyboardEnter(actor);
970         }
971       }
972
973       isFocusStartableKey = true;
974     }
975   }
976
977   if(isFocusStartableKey && mIsFocusIndicatorShown == SHOW)
978   {
979     Actor actor = GetCurrentFocusActor();
980     if(actor)
981     {
982       if(mEnableFocusIndicator == ENABLE)
983       {
984         // Make sure the focused actor is highlighted
985         actor.Add(GetFocusIndicatorActor());
986       }
987     }
988     else if(!mEnableDefaultAlgorithm)
989     {
990       // No actor is focused but keyboard focus is activated by the key press
991       // Let's try to move the initial focus
992       MoveFocus(Toolkit::Control::KeyboardFocus::RIGHT, deviceName);
993     }
994   }
995 }
996
997 void KeyboardFocusManager::OnTouch(const TouchEvent& touch)
998 {
999   // if mIsFocusIndicatorShown is UNKNOWN, it means Configuration is not loaded.
1000   // Try to load configuration.
1001   if(mIsFocusIndicatorShown == UNKNOWN)
1002   {
1003     GetConfigurationFromStyleManger();
1004   }
1005
1006   // Clear the focus when user touch the screen.
1007   // We only do this on a Down event, otherwise the clear action may override a manually focused actor.
1008   if(((touch.GetPointCount() < 1) || (touch.GetState(0) == PointState::DOWN)))
1009   {
1010     // If you touch the currently focused actor again, you don't need to do SetCurrentFocusActor again.
1011     Actor hitActor = touch.GetHitActor(0);
1012     if(hitActor && hitActor == GetCurrentFocusActor())
1013     {
1014       return;
1015     }
1016     // If KEYBOARD_FOCUSABLE and TOUCH_FOCUSABLE is true, set focus actor
1017     if(hitActor && hitActor.GetProperty<bool>(Actor::Property::KEYBOARD_FOCUSABLE) && hitActor.GetProperty<bool>(DevelActor::Property::TOUCH_FOCUSABLE))
1018     {
1019       // If mClearFocusOnTouch is false, do not clear the focus
1020       if(mClearFocusOnTouch)
1021       {
1022         ClearFocus();
1023       }
1024       SetCurrentFocusActor(hitActor);
1025     }
1026     else
1027     {
1028       // If mClearFocusOnTouch is false, do not clear the focus indicator even if user touch the screen.
1029       if(mClearFocusOnTouch)
1030       {
1031         ClearFocusIndicator();
1032       }
1033     }
1034   }
1035 }
1036
1037 void KeyboardFocusManager::OnWheelEvent(const WheelEvent& event)
1038 {
1039   if(event.GetType() == Dali::WheelEvent::CUSTOM_WHEEL)
1040   {
1041     Toolkit::Control::KeyboardFocus::Direction direction = (event.GetDelta() > 0) ? Toolkit::Control::KeyboardFocus::CLOCKWISE : Toolkit::Control::KeyboardFocus::COUNTER_CLOCKWISE;
1042     // Move the focus
1043     MoveFocus(direction);
1044   }
1045 }
1046
1047 bool KeyboardFocusManager::OnCustomWheelEvent(const WheelEvent& event)
1048 {
1049   bool  consumed = false;
1050   Actor actor    = GetCurrentFocusActor();
1051   if(actor)
1052   {
1053     // Notify the actor about the wheel event
1054     consumed = EmitCustomWheelSignals(actor, event);
1055   }
1056   return consumed;
1057 }
1058
1059 bool KeyboardFocusManager::EmitCustomWheelSignals(Actor actor, const WheelEvent& event)
1060 {
1061   bool consumed = false;
1062
1063   if(actor)
1064   {
1065     Dali::Actor oldParent(actor.GetParent());
1066
1067     // Only do the conversion and emit the signal if the actor's wheel signal has connections.
1068     if(!actor.WheelEventSignal().Empty())
1069     {
1070       // Emit the signal to the parent
1071       consumed = actor.WheelEventSignal().Emit(actor, event);
1072     }
1073     // if actor doesn't consume WheelEvent, give WheelEvent to its parent.
1074     if(!consumed)
1075     {
1076       // The actor may have been removed/reparented during the signal callbacks.
1077       Dali::Actor parent = actor.GetParent();
1078
1079       if(parent &&
1080          (parent == oldParent))
1081       {
1082         consumed = EmitCustomWheelSignals(parent, event);
1083       }
1084     }
1085   }
1086
1087   return consumed;
1088 }
1089
1090 void KeyboardFocusManager::OnWindowFocusChanged(Window window, bool focusIn)
1091 {
1092   if(focusIn && mCurrentFocusedWindow.GetHandle() != window.GetRootLayer())
1093   {
1094     // Change Current Focused Window
1095     Layer rootLayer       = window.GetRootLayer();
1096     mCurrentFocusedWindow = rootLayer;
1097
1098     // Get Current Focused Actor from window
1099     Actor currentFocusedActor = GetFocusActorFromCurrentWindow();
1100     SetCurrentFocusActor(currentFocusedActor);
1101
1102     if(currentFocusedActor && (mEnableFocusIndicator == ENABLE))
1103     {
1104       // Make sure the focused actor is highlighted
1105       currentFocusedActor.Add(GetFocusIndicatorActor());
1106       mIsFocusIndicatorShown = SHOW;
1107     }
1108   }
1109 }
1110
1111 Toolkit::KeyboardFocusManager::PreFocusChangeSignalType& KeyboardFocusManager::PreFocusChangeSignal()
1112 {
1113   return mPreFocusChangeSignal;
1114 }
1115
1116 Toolkit::KeyboardFocusManager::FocusChangedSignalType& KeyboardFocusManager::FocusChangedSignal()
1117 {
1118   return mFocusChangedSignal;
1119 }
1120
1121 Toolkit::KeyboardFocusManager::FocusGroupChangedSignalType& KeyboardFocusManager::FocusGroupChangedSignal()
1122 {
1123   return mFocusGroupChangedSignal;
1124 }
1125
1126 Toolkit::KeyboardFocusManager::FocusedActorEnterKeySignalType& KeyboardFocusManager::FocusedActorEnterKeySignal()
1127 {
1128   return mFocusedActorEnterKeySignal;
1129 }
1130
1131 bool KeyboardFocusManager::DoConnectSignal(BaseObject* object, ConnectionTrackerInterface* tracker, const std::string& signalName, FunctorDelegate* functor)
1132 {
1133   Dali::BaseHandle handle(object);
1134
1135   bool                  connected(true);
1136   KeyboardFocusManager* manager = static_cast<KeyboardFocusManager*>(object); // TypeRegistry guarantees that this is the correct type.
1137
1138   if(0 == strcmp(signalName.c_str(), SIGNAL_PRE_FOCUS_CHANGE))
1139   {
1140     manager->PreFocusChangeSignal().Connect(tracker, functor);
1141   }
1142   else if(0 == strcmp(signalName.c_str(), SIGNAL_FOCUS_CHANGED))
1143   {
1144     manager->FocusChangedSignal().Connect(tracker, functor);
1145   }
1146   else if(0 == strcmp(signalName.c_str(), SIGNAL_FOCUS_GROUP_CHANGED))
1147   {
1148     manager->FocusGroupChangedSignal().Connect(tracker, functor);
1149   }
1150   else if(0 == strcmp(signalName.c_str(), SIGNAL_FOCUSED_ACTOR_ENTER_KEY))
1151   {
1152     manager->FocusedActorEnterKeySignal().Connect(tracker, functor);
1153   }
1154   else
1155   {
1156     // signalName does not match any signal
1157     connected = false;
1158   }
1159
1160   return connected;
1161 }
1162
1163 void KeyboardFocusManager::SetCustomAlgorithm(CustomAlgorithmInterface& interface)
1164 {
1165   mCustomAlgorithmInterface = &interface;
1166 }
1167
1168 void KeyboardFocusManager::EnableFocusIndicator(bool enable)
1169 {
1170   if(!enable && mFocusIndicatorActor)
1171   {
1172     mFocusIndicatorActor.Unparent();
1173   }
1174
1175   mEnableFocusIndicator = enable ? ENABLE : DISABLE;
1176 }
1177
1178 bool KeyboardFocusManager::IsFocusIndicatorEnabled() const
1179 {
1180   return (mEnableFocusIndicator == ENABLE);
1181 }
1182
1183 void KeyboardFocusManager::EnableDefaultAlgorithm(bool enable)
1184 {
1185   mEnableDefaultAlgorithm = enable;
1186 }
1187
1188 bool KeyboardFocusManager::IsDefaultAlgorithmEnabled() const
1189 {
1190   return mEnableDefaultAlgorithm;
1191 }
1192
1193 void KeyboardFocusManager::SetFocusFinderRootActor(Actor actor)
1194 {
1195   mFocusFinderRootActor = actor;
1196 }
1197
1198 void KeyboardFocusManager::ResetFocusFinderRootActor()
1199 {
1200   mFocusFinderRootActor.Reset();
1201 }
1202
1203 } // namespace Internal
1204
1205 } // namespace Toolkit
1206
1207 } // namespace Dali