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