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