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