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