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