2 * Copyright (c) 2016 Samsung Electronics Co., Ltd.
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
8 * http://www.apache.org/licenses/LICENSE-2.0
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.
19 #include "keyboard-focus-manager-impl.h"
22 #include <cstring> // for strcmp
23 #include <dali/public-api/actors/layer.h>
24 #include <dali/devel-api/adaptor-framework/accessibility-adaptor.h>
25 #include <dali/devel-api/adaptor-framework/singleton-service.h>
26 #include <dali/public-api/animation/constraints.h>
27 #include <dali/public-api/common/stage.h>
28 #include <dali/public-api/events/key-event.h>
29 #include <dali/public-api/events/touch-data.h>
30 #include <dali/public-api/object/type-registry.h>
31 #include <dali/public-api/object/type-registry-helper.h>
32 #include <dali/public-api/images/resource-image.h>
33 #include <dali/integration-api/debug.h>
36 #include <dali-toolkit/public-api/controls/control.h>
37 #include <dali-toolkit/public-api/controls/control-impl.h>
38 #include <dali-toolkit/public-api/controls/image-view/image-view.h>
39 #include <dali-toolkit/public-api/accessibility-manager/accessibility-manager.h>
40 #include <dali-toolkit/devel-api/focus-manager/keyinput-focus-manager.h>
51 namespace // Unnamed namespace
54 #if defined(DEBUG_ENABLED)
55 Debug::Filter* gLogFilter = Debug::Filter::New(Debug::NoLogging, false, "LOG_KEYBOARD_FOCUS_MANAGER");
58 const char* const IS_FOCUS_GROUP_PROPERTY_NAME = "isKeyboardFocusGroup"; // This property will be replaced by a flag in Control.
60 const char* const FOCUS_BORDER_IMAGE_PATH = DALI_IMAGE_DIR "keyboard_focus.9.png";
64 BaseHandle handle = KeyboardFocusManager::Get();
68 SingletonService singletonService( SingletonService::Get() );
69 if ( singletonService )
71 Toolkit::KeyboardFocusManager manager = Toolkit::KeyboardFocusManager( new Internal::KeyboardFocusManager() );
72 singletonService.Register( typeid( manager ), manager );
80 DALI_TYPE_REGISTRATION_BEGIN_CREATE( Toolkit::KeyboardFocusManager, Dali::BaseHandle, Create, true )
82 DALI_SIGNAL_REGISTRATION( Toolkit, KeyboardFocusManager, "keyboardPreFocusChange", SIGNAL_PRE_FOCUS_CHANGE )
83 DALI_SIGNAL_REGISTRATION( Toolkit, KeyboardFocusManager, "keyboardFocusChanged", SIGNAL_FOCUS_CHANGED )
84 DALI_SIGNAL_REGISTRATION( Toolkit, KeyboardFocusManager, "keyboardFocusGroupChanged", SIGNAL_FOCUS_GROUP_CHANGED )
85 DALI_SIGNAL_REGISTRATION( Toolkit, KeyboardFocusManager, "keyboardFocusedActorEnterKey", SIGNAL_FOCUSED_ACTOR_ENTER_KEY )
87 DALI_TYPE_REGISTRATION_END()
89 const unsigned int MAX_HISTORY_AMOUNT = 30; ///< Max length of focus history stack
91 } // unnamed namespace
93 Toolkit::KeyboardFocusManager KeyboardFocusManager::Get()
95 Toolkit::KeyboardFocusManager manager;
97 SingletonService singletonService( SingletonService::Get() );
98 if ( singletonService )
100 // Check whether the keyboard focus manager is already created
101 Dali::BaseHandle handle = singletonService.GetSingleton( typeid( Toolkit::KeyboardFocusManager ) );
104 // If so, downcast the handle of singleton to keyboard focus manager
105 manager = Toolkit::KeyboardFocusManager( dynamic_cast< KeyboardFocusManager* >( handle.GetObjectPtr() ) );
112 KeyboardFocusManager::KeyboardFocusManager()
113 : mPreFocusChangeSignal(),
114 mFocusChangedSignal(),
115 mFocusGroupChangedSignal(),
116 mFocusedActorEnterKeySignal(),
117 mCurrentFocusActor( 0 ),
118 mFocusIndicatorActor(),
119 mFocusGroupLoopEnabled( false ),
120 mIsFocusIndicatorEnabled( false ),
121 mIsWaitingKeyboardFocusChangeCommit( false ),
123 mSlotDelegate( this )
125 // TODO: Get FocusIndicatorEnable constant from stylesheet to set mIsFocusIndicatorEnabled.
126 Toolkit::KeyInputFocusManager::Get().UnhandledKeyEventSignal().Connect(mSlotDelegate, &KeyboardFocusManager::OnKeyEvent);
127 Stage::GetCurrent().TouchSignal().Connect( mSlotDelegate, &KeyboardFocusManager::OnTouch );
130 KeyboardFocusManager::~KeyboardFocusManager()
134 bool KeyboardFocusManager::SetCurrentFocusActor( Actor actor )
136 DALI_ASSERT_DEBUG( !mIsWaitingKeyboardFocusChangeCommit && "Calling this function in the PreFocusChangeSignal callback?" );
140 return DoSetCurrentFocusActor( actor.GetId() );
146 bool KeyboardFocusManager::DoSetCurrentFocusActor( const unsigned int actorID )
148 Actor rootActor = Stage::GetCurrent().GetRootLayer();
149 Actor actor = rootActor.FindChildById( actorID );
150 bool success = false;
152 // Check whether the actor is in the stage and is keyboard focusable.
153 if( actor && actor.IsKeyboardFocusable() )
155 // Draw the focus indicator upon the focused actor when Focus Indicator is enabled
156 if( mIsFocusIndicatorEnabled )
158 actor.Add( GetFocusIndicatorActor() );
160 // Send notification for the change of focus actor
161 if( !mFocusChangedSignal.Empty() )
163 mFocusChangedSignal.Emit(GetCurrentFocusActor(), actor);
166 DALI_LOG_INFO( gLogFilter, Debug::General, "[%s:%d] Focus Changed\n", __FUNCTION__, __LINE__);
168 // Save the current focused actor
169 mCurrentFocusActor = actorID;
171 // Push Current Focused Actor to FocusHistory
172 mFocusHistory.PushBack( &actor.GetBaseObject() );
174 // Delete first element before add new element when Stack is full.
175 if( mFocusHistory.Count() > MAX_HISTORY_AMOUNT )
177 FocusStackIterator beginPos = mFocusHistory.Begin();
178 mFocusHistory.Erase( beginPos );
181 DALI_LOG_INFO( gLogFilter, Debug::General, "[%s:%d] SUCCEED\n", __FUNCTION__, __LINE__);
186 DALI_LOG_WARNING("[%s:%d] FAILED\n", __FUNCTION__, __LINE__);
192 Actor KeyboardFocusManager::GetCurrentFocusActor()
194 Actor rootActor = Stage::GetCurrent().GetRootLayer();
195 return rootActor.FindChildById(mCurrentFocusActor);
198 Actor KeyboardFocusManager::GetCurrentFocusGroup()
200 return GetFocusGroup(GetCurrentFocusActor());
203 void KeyboardFocusManager::MoveFocusBackward()
205 // Find Pre Focused Actor when the list size is more than 1
206 if( mFocusHistory.Count() > 1 )
208 // Delete current focused actor in history
209 FocusStackIterator endPos = mFocusHistory.End();
210 endPos = mFocusHistory.Erase( --endPos );
212 // If pre-focused actors are not on stage, remove them in stack
213 while( !Dali::Actor::DownCast(BaseHandle(mFocusHistory[ mFocusHistory.Count() - 1 ])).OnStage() )
215 endPos = mFocusHistory.Erase( --endPos );
218 // Get pre focused actor
219 BaseObject* object = mFocusHistory[ mFocusHistory.Count() - 1 ];
220 BaseHandle handle( object );
221 Actor preFocusedActor = Dali::Actor::DownCast( handle );
223 // Delete pre focused actor in history because it will pushed again by SetCurrentFocusActor()
224 mFocusHistory.Erase( --endPos );
226 SetCurrentFocusActor( preFocusedActor );
230 bool KeyboardFocusManager::IsLayoutControl(Actor actor) const
232 Toolkit::Control control = Toolkit::Control::DownCast(actor);
233 return control && GetImplementation( control ).IsKeyboardNavigationSupported();
236 Toolkit::Control KeyboardFocusManager::GetParentLayoutControl(Actor actor) const
238 // Get the actor's parent layout control that supports two dimensional keyboard navigation
239 Actor rootActor = Stage::GetCurrent().GetRootLayer();
243 parent = actor.GetParent();
246 while( parent && !IsLayoutControl(parent) && parent != rootActor )
248 parent = parent.GetParent();
251 return Toolkit::Control::DownCast(parent);
254 bool KeyboardFocusManager::MoveFocus(Toolkit::Control::KeyboardFocus::Direction direction)
256 Actor currentFocusActor = GetCurrentFocusActor();
258 bool succeed = false;
260 // Go through the actor's hierarchy until we find a layout control that knows how to move the focus
261 Toolkit::Control parentLayoutControl = GetParentLayoutControl(currentFocusActor);
262 while(parentLayoutControl && !succeed)
264 succeed = DoMoveFocusWithinLayoutControl(parentLayoutControl, currentFocusActor, direction);
265 parentLayoutControl = GetParentLayoutControl(parentLayoutControl);
268 if(!succeed && !mPreFocusChangeSignal.Empty())
270 // Don't know how to move the focus further. The application needs to tell us which actor to move the focus to
271 mIsWaitingKeyboardFocusChangeCommit = true;
272 Actor nextFocusableActor = mPreFocusChangeSignal.Emit(currentFocusActor, Actor(), direction);
273 mIsWaitingKeyboardFocusChangeCommit = false;
275 if ( nextFocusableActor && nextFocusableActor.IsKeyboardFocusable() )
277 // Whether the next focusable actor is a layout control
278 if(IsLayoutControl(nextFocusableActor))
280 // If so, move the focus inside it.
281 Toolkit::Control layoutControl = Toolkit::Control::DownCast(nextFocusableActor);
282 succeed = DoMoveFocusWithinLayoutControl(layoutControl, currentFocusActor, direction);
286 // Otherwise, just set focus to the next focusable actor
287 succeed = SetCurrentFocusActor(nextFocusableActor);
295 bool KeyboardFocusManager::DoMoveFocusWithinLayoutControl(Toolkit::Control control, Actor actor, Toolkit::Control::KeyboardFocus::Direction direction)
297 // Ask the control for the next actor to focus
298 Actor nextFocusableActor = GetImplementation( control ).GetNextKeyboardFocusableActor(actor, direction, mFocusGroupLoopEnabled);
299 if(nextFocusableActor)
301 if(!nextFocusableActor.IsKeyboardFocusable())
303 // If the actor is not focusable, ask the same layout control for the next actor to focus
304 return DoMoveFocusWithinLayoutControl(control, nextFocusableActor, direction);
308 Actor currentFocusActor = GetCurrentFocusActor();
309 Actor committedFocusActor = nextFocusableActor;
311 // We will try to move the focus to the actor. Emit a signal to notify the proposed actor to focus
312 // Signal handler can check the proposed actor and return a different actor if it wishes.
313 if( !mPreFocusChangeSignal.Empty() )
315 mIsWaitingKeyboardFocusChangeCommit = true;
316 committedFocusActor = mPreFocusChangeSignal.Emit(currentFocusActor, nextFocusableActor, direction);
317 mIsWaitingKeyboardFocusChangeCommit = false;
320 if (committedFocusActor && committedFocusActor.IsKeyboardFocusable())
322 // Whether the commited focusable actor is a layout control
323 if(IsLayoutControl(committedFocusActor))
325 // If so, move the focus inside it.
326 Toolkit::Control layoutControl = Toolkit::Control::DownCast(committedFocusActor);
327 return DoMoveFocusWithinLayoutControl(layoutControl, currentFocusActor, direction);
331 // Otherwise, just set focus to the next focusable actor
332 if(committedFocusActor == nextFocusableActor)
334 // If the application hasn't changed our proposed actor, we informs the layout control we will
335 // move the focus to what the control returns. The control might wish to perform some actions
336 // before the focus is actually moved.
337 GetImplementation( control ).OnKeyboardFocusChangeCommitted( committedFocusActor );
340 return SetCurrentFocusActor(committedFocusActor);
351 // No more actor can be focused in the given direction within the same layout control.
356 bool KeyboardFocusManager::DoMoveFocusToNextFocusGroup(bool forward)
358 bool succeed = false;
360 // Get the parent layout control of the current focus group
361 Toolkit::Control parentLayoutControl = GetParentLayoutControl(GetCurrentFocusGroup());
363 while(parentLayoutControl && !succeed)
365 // If the current focus group has a parent layout control, we can probably automatically
366 // move the focus to the next focus group in the forward or backward direction.
367 Toolkit::Control::KeyboardFocus::Direction direction = forward ? Toolkit::Control::KeyboardFocus::RIGHT : Toolkit::Control::KeyboardFocus::LEFT;
368 succeed = DoMoveFocusWithinLayoutControl(parentLayoutControl, GetCurrentFocusActor(), direction);
369 parentLayoutControl = GetParentLayoutControl(parentLayoutControl);
372 if(!mFocusGroupChangedSignal.Empty())
374 // Emit a focus group changed signal. The applicaton can move the focus to a new focus group
375 mFocusGroupChangedSignal.Emit(GetCurrentFocusActor(), forward);
381 void KeyboardFocusManager::DoKeyboardEnter(Actor actor)
385 Toolkit::Control control = Toolkit::Control::DownCast( actor );
388 // Notify the control that enter has been pressed on it.
389 GetImplementation( control ).KeyboardEnter();
392 // Send a notification for the actor.
393 if( !mFocusedActorEnterKeySignal.Empty() )
395 mFocusedActorEnterKeySignal.Emit( actor );
400 void KeyboardFocusManager::ClearFocus()
402 Actor actor = GetCurrentFocusActor();
405 if(mFocusIndicatorActor)
407 actor.Remove(mFocusIndicatorActor);
410 // Send notification for the change of focus actor
411 if( !mFocusChangedSignal.Empty() )
413 mFocusChangedSignal.Emit(actor, Actor());
417 mCurrentFocusActor = 0;
418 mIsFocusIndicatorEnabled = false;
421 void KeyboardFocusManager::SetFocusGroupLoop(bool enabled)
423 mFocusGroupLoopEnabled = enabled;
426 bool KeyboardFocusManager::GetFocusGroupLoop() const
428 return mFocusGroupLoopEnabled;
431 void KeyboardFocusManager::SetAsFocusGroup(Actor actor, bool isFocusGroup)
435 // Create/Set focus group property.
436 actor.RegisterProperty( IS_FOCUS_GROUP_PROPERTY_NAME, isFocusGroup, Property::READ_WRITE );
440 bool KeyboardFocusManager::IsFocusGroup(Actor actor) const
442 // Check whether the actor is a focus group
443 bool isFocusGroup = false;
447 Property::Index propertyIsFocusGroup = actor.GetPropertyIndex(IS_FOCUS_GROUP_PROPERTY_NAME);
448 if(propertyIsFocusGroup != Property::INVALID_INDEX)
450 isFocusGroup = actor.GetProperty<bool>(propertyIsFocusGroup);
457 Actor KeyboardFocusManager::GetFocusGroup(Actor actor)
459 // Go through the actor's hierarchy to check which focus group the actor belongs to
460 while (actor && !IsFocusGroup(actor))
462 actor = actor.GetParent();
468 void KeyboardFocusManager::SetFocusIndicatorActor(Actor indicator)
470 if(mFocusIndicatorActor != indicator)
472 Actor currentFocusActor = GetCurrentFocusActor();
473 if(currentFocusActor)
475 // The new focus indicator should be added to the current focused actor immediately
476 if(mFocusIndicatorActor)
478 currentFocusActor.Remove(mFocusIndicatorActor);
483 currentFocusActor.Add(indicator);
487 mFocusIndicatorActor = indicator;
491 Actor KeyboardFocusManager::GetFocusIndicatorActor()
493 if( ! mFocusIndicatorActor )
495 // Create the default if it hasn't been set and one that's shared by all the keyboard focusable actors
496 mFocusIndicatorActor = Toolkit::ImageView::New( FOCUS_BORDER_IMAGE_PATH );
497 mFocusIndicatorActor.SetParentOrigin( ParentOrigin::CENTER );
499 // Apply size constraint to the focus indicator
500 mFocusIndicatorActor.SetResizePolicy( ResizePolicy::FILL_TO_PARENT, Dimension::ALL_DIMENSIONS );
503 return mFocusIndicatorActor;
506 void KeyboardFocusManager::OnKeyEvent(const KeyEvent& event)
508 AccessibilityAdaptor accessibilityAdaptor = AccessibilityAdaptor::Get();
509 bool isAccessibilityEnabled = accessibilityAdaptor.IsEnabled();
511 Toolkit::AccessibilityManager accessibilityManager = Toolkit::AccessibilityManager::Get();
513 std::string keyName = event.keyPressedName;
515 bool isFocusStartableKey = false;
517 if(event.state == KeyEvent::Down)
519 if (keyName == "Left")
521 if(!isAccessibilityEnabled)
523 if(!mIsFocusIndicatorEnabled)
525 // Show focus indicator
526 mIsFocusIndicatorEnabled = true;
530 // Move the focus towards left
531 MoveFocus(Toolkit::Control::KeyboardFocus::LEFT);
534 isFocusStartableKey = true;
538 // Move the accessibility focus backward
539 accessibilityManager.MoveFocusBackward();
542 else if (keyName == "Right")
544 if(!isAccessibilityEnabled)
546 if(!mIsFocusIndicatorEnabled)
548 // Show focus indicator
549 mIsFocusIndicatorEnabled = true;
553 // Move the focus towards right
554 MoveFocus(Toolkit::Control::KeyboardFocus::RIGHT);
559 // Move the accessibility focus forward
560 accessibilityManager.MoveFocusForward();
563 isFocusStartableKey = true;
565 else if (keyName == "Up" && !isAccessibilityEnabled)
567 if(!mIsFocusIndicatorEnabled)
569 // Show focus indicator
570 mIsFocusIndicatorEnabled = true;
574 // Move the focus towards up
575 MoveFocus(Toolkit::Control::KeyboardFocus::UP);
578 isFocusStartableKey = true;
580 else if (keyName == "Down" && !isAccessibilityEnabled)
582 if(!mIsFocusIndicatorEnabled)
584 // Show focus indicator
585 mIsFocusIndicatorEnabled = true;
589 // Move the focus towards down
590 MoveFocus(Toolkit::Control::KeyboardFocus::DOWN);
593 isFocusStartableKey = true;
595 else if (keyName == "Prior" && !isAccessibilityEnabled)
597 if(!mIsFocusIndicatorEnabled)
599 // Show focus indicator
600 mIsFocusIndicatorEnabled = true;
604 // Move the focus towards the previous page
605 MoveFocus(Toolkit::Control::KeyboardFocus::PAGE_UP);
608 isFocusStartableKey = true;
610 else if (keyName == "Next" && !isAccessibilityEnabled)
612 if(!mIsFocusIndicatorEnabled)
614 // Show focus indicator
615 mIsFocusIndicatorEnabled = true;
619 // Move the focus towards the next page
620 MoveFocus(Toolkit::Control::KeyboardFocus::PAGE_DOWN);
623 isFocusStartableKey = true;
625 else if (keyName == "Tab" && !isAccessibilityEnabled)
627 if(!mIsFocusIndicatorEnabled)
629 // Show focus indicator
630 mIsFocusIndicatorEnabled = true;
634 // "Tab" key changes the focus group in the forward direction and
635 // "Shift-Tab" key changes it in the backward direction.
636 DoMoveFocusToNextFocusGroup(!event.IsShiftModifier());
639 isFocusStartableKey = true;
641 else if (keyName == "space" && !isAccessibilityEnabled)
643 if(!mIsFocusIndicatorEnabled)
645 // Show focus indicator
646 mIsFocusIndicatorEnabled = true;
649 isFocusStartableKey = true;
651 else if (keyName == "" && !isAccessibilityEnabled)
653 // Check the fake key event for evas-plugin case
654 if(!mIsFocusIndicatorEnabled)
656 // Show focus indicator
657 mIsFocusIndicatorEnabled = true;
660 isFocusStartableKey = true;
662 else if (keyName == "Backspace" && !isAccessibilityEnabled)
664 // Emit signal to go back to the previous view???
666 else if (keyName == "Escape" && !isAccessibilityEnabled)
670 else if(event.state == KeyEvent::Up)
672 if (keyName == "Return")
674 if(!mIsFocusIndicatorEnabled && !isAccessibilityEnabled)
676 // Show focus indicator
677 mIsFocusIndicatorEnabled = true;
681 // The focused actor has enter pressed on it
683 if( !isAccessibilityEnabled )
685 actor = GetCurrentFocusActor();
689 actor = accessibilityManager.GetCurrentFocusActor();
694 DoKeyboardEnter( actor );
698 isFocusStartableKey = true;
702 if(isFocusStartableKey && mIsFocusIndicatorEnabled && !isAccessibilityEnabled)
704 Actor actor = GetCurrentFocusActor();
707 // Make sure the focused actor is highlighted
708 actor.Add( GetFocusIndicatorActor() );
712 // No actor is focused but keyboard focus is activated by the key press
713 // Let's try to move the initial focus
714 MoveFocus(Toolkit::Control::KeyboardFocus::RIGHT);
719 void KeyboardFocusManager::OnTouch(const TouchData& touch)
721 // Clear the focus when user touch the screen.
722 // We only do this on a Down event, otherwise the clear action may override a manually focused actor.
723 if( ( touch.GetPointCount() < 1 ) || ( touch.GetState( 0 ) == PointState::DOWN ) )
729 Toolkit::KeyboardFocusManager::PreFocusChangeSignalType& KeyboardFocusManager::PreFocusChangeSignal()
731 return mPreFocusChangeSignal;
734 Toolkit::KeyboardFocusManager::FocusChangedSignalType& KeyboardFocusManager::FocusChangedSignal()
736 return mFocusChangedSignal;
739 Toolkit::KeyboardFocusManager::FocusGroupChangedSignalType& KeyboardFocusManager::FocusGroupChangedSignal()
741 return mFocusGroupChangedSignal;
744 Toolkit::KeyboardFocusManager::FocusedActorEnterKeySignalType& KeyboardFocusManager::FocusedActorEnterKeySignal()
746 return mFocusedActorEnterKeySignal;
749 bool KeyboardFocusManager::DoConnectSignal( BaseObject* object, ConnectionTrackerInterface* tracker, const std::string& signalName, FunctorDelegate* functor )
751 Dali::BaseHandle handle( object );
753 bool connected( true );
754 KeyboardFocusManager* manager = static_cast< KeyboardFocusManager* >( object ); // TypeRegistry guarantees that this is the correct type.
756 if( 0 == strcmp( signalName.c_str(), SIGNAL_PRE_FOCUS_CHANGE ) )
758 manager->PreFocusChangeSignal().Connect( tracker, functor );
760 else if( 0 == strcmp( signalName.c_str(), SIGNAL_FOCUS_CHANGED ) )
762 manager->FocusChangedSignal().Connect( tracker, functor );
764 else if( 0 == strcmp( signalName.c_str(), SIGNAL_FOCUS_GROUP_CHANGED ) )
766 manager->FocusGroupChangedSignal().Connect( tracker, functor );
768 else if( 0 == strcmp( signalName.c_str(), SIGNAL_FOCUSED_ACTOR_ENTER_KEY ) )
770 manager->FocusedActorEnterKeySignal().Connect( tracker, functor );
774 // signalName does not match any signal
781 } // namespace Internal
783 } // namespace Toolkit