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