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