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 : mCurrentFocusActor(0),
114 mFocusIndicatorActor(),
115 mFocusGroupLoopEnabled(false),
116 mIsKeyboardFocusEnabled(false),
117 mIsFocusIndicatorEnabled(false),
118 mIsWaitingKeyboardFocusChangeCommit(false),
121 OnPhysicalKeyboardStatusChanged(PhysicalKeyboard::Get());
123 Toolkit::KeyInputFocusManager::Get().UnhandledKeyEventSignal().Connect(mSlotDelegate, &KeyboardFocusManager::OnKeyEvent);
124 Stage::GetCurrent().TouchSignal().Connect( mSlotDelegate, &KeyboardFocusManager::OnTouch );
125 PhysicalKeyboard::Get().StatusChangedSignal().Connect(mSlotDelegate, &KeyboardFocusManager::OnPhysicalKeyboardStatusChanged);
128 KeyboardFocusManager::~KeyboardFocusManager()
132 bool KeyboardFocusManager::SetCurrentFocusActor( Actor actor )
134 DALI_ASSERT_DEBUG( !mIsWaitingKeyboardFocusChangeCommit && "Calling this function in the PreFocusChangeSignal callback?" );
138 return DoSetCurrentFocusActor( actor.GetId() );
144 bool KeyboardFocusManager::DoSetCurrentFocusActor( const unsigned int actorID )
146 Actor rootActor = Stage::GetCurrent().GetRootLayer();
147 Actor actor = rootActor.FindChildById( actorID );
148 bool success = false;
150 // Check whether the actor is in the stage and is keyboard focusable.
151 if( actor && actor.IsKeyboardFocusable() )
153 mIsFocusIndicatorEnabled = true;
154 // Draw the focus indicator upon the focused actor when PhysicalKeyboard is attached
155 if( mIsKeyboardFocusEnabled )
157 actor.Add( GetFocusIndicatorActor() );
159 // Send notification for the change of focus actor
160 if( !mFocusChangedSignal.Empty() )
162 mFocusChangedSignal.Emit(GetCurrentFocusActor(), actor);
165 DALI_LOG_INFO( gLogFilter, Debug::General, "[%s:%d] Focus Changed\n", __FUNCTION__, __LINE__);
167 // Save the current focused actor
168 mCurrentFocusActor = actorID;
170 // Push Current Focused Actor to FocusHistory
171 mFocusHistory.PushBack( &actor.GetBaseObject() );
173 // Delete first element before add new element when Stack is full.
174 if( mFocusHistory.Count() > MAX_HISTORY_AMOUNT )
176 FocusStackIterator beginPos = mFocusHistory.Begin();
177 mFocusHistory.Erase( beginPos );
180 DALI_LOG_INFO( gLogFilter, Debug::General, "[%s:%d] SUCCEED\n", __FUNCTION__, __LINE__);
185 DALI_LOG_WARNING("[%s:%d] FAILED\n", __FUNCTION__, __LINE__);
191 Actor KeyboardFocusManager::GetCurrentFocusActor()
193 Actor rootActor = Stage::GetCurrent().GetRootLayer();
194 return rootActor.FindChildById(mCurrentFocusActor);
197 Actor KeyboardFocusManager::GetCurrentFocusGroup()
199 return GetFocusGroup(GetCurrentFocusActor());
202 void KeyboardFocusManager::MoveFocusBackward()
204 // Find Pre Focused Actor when the list size is more than 1
205 if( mFocusHistory.Count() > 1 )
207 // Delete current focused actor in history
208 FocusStackIterator endPos = mFocusHistory.End();
209 endPos = mFocusHistory.Erase( --endPos );
211 // If pre-focused actors are not on stage, remove them in stack
212 while( !Dali::Actor::DownCast(BaseHandle(mFocusHistory[ mFocusHistory.Count() - 1 ])).OnStage() )
214 endPos = mFocusHistory.Erase( --endPos );
217 // Get pre focused actor
218 BaseObject* object = mFocusHistory[ mFocusHistory.Count() - 1 ];
219 BaseHandle handle( object );
220 Actor preFocusedActor = Dali::Actor::DownCast( handle );
222 // Delete pre focused actor in history because it will pushed again by SetCurrentFocusActor()
223 mFocusHistory.Erase( --endPos );
225 SetCurrentFocusActor( preFocusedActor );
229 bool KeyboardFocusManager::IsLayoutControl(Actor actor) const
231 Toolkit::Control control = Toolkit::Control::DownCast(actor);
232 return control && GetImplementation( control ).IsKeyboardNavigationSupported();
235 Toolkit::Control KeyboardFocusManager::GetParentLayoutControl(Actor actor) const
237 // Get the actor's parent layout control that supports two dimensional keyboard navigation
238 Actor rootActor = Stage::GetCurrent().GetRootLayer();
242 parent = actor.GetParent();
245 while( parent && !IsLayoutControl(parent) && parent != rootActor )
247 parent = parent.GetParent();
250 return Toolkit::Control::DownCast(parent);
253 bool KeyboardFocusManager::MoveFocus(Toolkit::Control::KeyboardFocus::Direction direction)
255 Actor currentFocusActor = GetCurrentFocusActor();
257 bool succeed = false;
259 // Go through the actor's hierarchy until we find a layout control that knows how to move the focus
260 Toolkit::Control parentLayoutControl = GetParentLayoutControl(currentFocusActor);
261 while(parentLayoutControl && !succeed)
263 succeed = DoMoveFocusWithinLayoutControl(parentLayoutControl, currentFocusActor, direction);
264 parentLayoutControl = GetParentLayoutControl(parentLayoutControl);
267 if(!succeed && !mPreFocusChangeSignal.Empty())
269 // Don't know how to move the focus further. The application needs to tell us which actor to move the focus to
270 mIsWaitingKeyboardFocusChangeCommit = true;
271 Actor nextFocusableActor = mPreFocusChangeSignal.Emit(currentFocusActor, Actor(), direction);
272 mIsWaitingKeyboardFocusChangeCommit = false;
274 if ( nextFocusableActor && nextFocusableActor.IsKeyboardFocusable() )
276 // Whether the next focusable actor is a layout control
277 if(IsLayoutControl(nextFocusableActor))
279 // If so, move the focus inside it.
280 Toolkit::Control layoutControl = Toolkit::Control::DownCast(nextFocusableActor);
281 succeed = DoMoveFocusWithinLayoutControl(layoutControl, currentFocusActor, direction);
285 // Otherwise, just set focus to the next focusable actor
286 succeed = SetCurrentFocusActor(nextFocusableActor);
294 bool KeyboardFocusManager::DoMoveFocusWithinLayoutControl(Toolkit::Control control, Actor actor, Toolkit::Control::KeyboardFocus::Direction direction)
296 // Ask the control for the next actor to focus
297 Actor nextFocusableActor = GetImplementation( control ).GetNextKeyboardFocusableActor(actor, direction, mFocusGroupLoopEnabled);
298 if(nextFocusableActor)
300 if(!nextFocusableActor.IsKeyboardFocusable())
302 // If the actor is not focusable, ask the same layout control for the next actor to focus
303 return DoMoveFocusWithinLayoutControl(control, nextFocusableActor, direction);
307 Actor currentFocusActor = GetCurrentFocusActor();
308 Actor committedFocusActor = nextFocusableActor;
310 // We will try to move the focus to the actor. Emit a signal to notify the proposed actor to focus
311 // Signal handler can check the proposed actor and return a different actor if it wishes.
312 if( !mPreFocusChangeSignal.Empty() )
314 mIsWaitingKeyboardFocusChangeCommit = true;
315 committedFocusActor = mPreFocusChangeSignal.Emit(currentFocusActor, nextFocusableActor, direction);
316 mIsWaitingKeyboardFocusChangeCommit = false;
319 if (committedFocusActor && committedFocusActor.IsKeyboardFocusable())
321 // Whether the commited focusable actor is a layout control
322 if(IsLayoutControl(committedFocusActor))
324 // If so, move the focus inside it.
325 Toolkit::Control layoutControl = Toolkit::Control::DownCast(committedFocusActor);
326 return DoMoveFocusWithinLayoutControl(layoutControl, currentFocusActor, direction);
330 // Otherwise, just set focus to the next focusable actor
331 if(committedFocusActor == nextFocusableActor)
333 // If the application hasn't changed our proposed actor, we informs the layout control we will
334 // move the focus to what the control returns. The control might wish to perform some actions
335 // before the focus is actually moved.
336 GetImplementation( control ).OnKeyboardFocusChangeCommitted( committedFocusActor );
339 return SetCurrentFocusActor(committedFocusActor);
350 // No more actor can be focused in the given direction within the same layout control.
355 bool KeyboardFocusManager::DoMoveFocusToNextFocusGroup(bool forward)
357 bool succeed = false;
359 // Get the parent layout control of the current focus group
360 Toolkit::Control parentLayoutControl = GetParentLayoutControl(GetCurrentFocusGroup());
362 while(parentLayoutControl && !succeed)
364 // If the current focus group has a parent layout control, we can probably automatically
365 // move the focus to the next focus group in the forward or backward direction.
366 Toolkit::Control::KeyboardFocus::Direction direction = forward ? Toolkit::Control::KeyboardFocus::RIGHT : Toolkit::Control::KeyboardFocus::LEFT;
367 succeed = DoMoveFocusWithinLayoutControl(parentLayoutControl, GetCurrentFocusActor(), direction);
368 parentLayoutControl = GetParentLayoutControl(parentLayoutControl);
371 if(!mFocusGroupChangedSignal.Empty())
373 // Emit a focus group changed signal. The applicaton can move the focus to a new focus group
374 mFocusGroupChangedSignal.Emit(GetCurrentFocusActor(), forward);
380 void KeyboardFocusManager::DoKeyboardEnter(Actor actor)
384 Toolkit::Control control = Toolkit::Control::DownCast( actor );
387 // Notify the control that enter has been pressed on it.
388 GetImplementation( control ).KeyboardEnter();
391 // Send a notification for the actor.
392 if( !mFocusedActorEnterKeySignal.Empty() )
394 mFocusedActorEnterKeySignal.Emit( actor );
399 void KeyboardFocusManager::ClearFocus()
401 Actor actor = GetCurrentFocusActor();
404 if(mFocusIndicatorActor)
406 actor.Remove(mFocusIndicatorActor);
409 // Send notification for the change of focus actor
410 if( !mFocusChangedSignal.Empty() )
412 mFocusChangedSignal.Emit(actor, Actor());
416 mCurrentFocusActor = 0;
417 mIsFocusIndicatorEnabled = false;
420 void KeyboardFocusManager::SetFocusGroupLoop(bool enabled)
422 mFocusGroupLoopEnabled = enabled;
425 bool KeyboardFocusManager::GetFocusGroupLoop() const
427 return mFocusGroupLoopEnabled;
430 void KeyboardFocusManager::SetAsFocusGroup(Actor actor, bool isFocusGroup)
434 // Create/Set focus group property.
435 actor.RegisterProperty( IS_FOCUS_GROUP_PROPERTY_NAME, isFocusGroup, Property::READ_WRITE );
439 bool KeyboardFocusManager::IsFocusGroup(Actor actor) const
441 // Check whether the actor is a focus group
442 bool isFocusGroup = false;
446 Property::Index propertyIsFocusGroup = actor.GetPropertyIndex(IS_FOCUS_GROUP_PROPERTY_NAME);
447 if(propertyIsFocusGroup != Property::INVALID_INDEX)
449 isFocusGroup = actor.GetProperty<bool>(propertyIsFocusGroup);
456 Actor KeyboardFocusManager::GetFocusGroup(Actor actor)
458 // Go through the actor's hierarchy to check which focus group the actor belongs to
459 while (actor && !IsFocusGroup(actor))
461 actor = actor.GetParent();
467 void KeyboardFocusManager::SetFocusIndicatorActor(Actor indicator)
469 if(mFocusIndicatorActor != indicator)
471 Actor currentFocusActor = GetCurrentFocusActor();
472 if(currentFocusActor)
474 // The new focus indicator should be added to the current focused actor immediately
475 if(mFocusIndicatorActor)
477 currentFocusActor.Remove(mFocusIndicatorActor);
482 currentFocusActor.Add(indicator);
486 mFocusIndicatorActor = indicator;
490 Actor KeyboardFocusManager::GetFocusIndicatorActor()
492 if( ! mFocusIndicatorActor )
494 // Create the default if it hasn't been set and one that's shared by all the keyboard focusable actors
495 mFocusIndicatorActor = Toolkit::ImageView::New( FOCUS_BORDER_IMAGE_PATH );
496 mFocusIndicatorActor.SetParentOrigin( ParentOrigin::CENTER );
498 // Apply size constraint to the focus indicator
499 mFocusIndicatorActor.SetResizePolicy( ResizePolicy::FILL_TO_PARENT, Dimension::ALL_DIMENSIONS );
502 return mFocusIndicatorActor;
505 void KeyboardFocusManager::OnPhysicalKeyboardStatusChanged(PhysicalKeyboard keyboard)
507 mIsKeyboardFocusEnabled = keyboard.IsAttached();
509 if(mIsKeyboardFocusEnabled)
511 // Show indicator when keyboard focus turned on if there is focused actor.
512 Actor actor = GetCurrentFocusActor();
515 actor.Add( GetFocusIndicatorActor() );
517 mIsFocusIndicatorEnabled = true;
521 // Hide indicator when keyboard focus turned off
522 Actor actor = GetCurrentFocusActor();
523 if( actor && mFocusIndicatorActor )
525 actor.Remove( mFocusIndicatorActor );
527 mIsFocusIndicatorEnabled = false;
531 void KeyboardFocusManager::OnKeyEvent(const KeyEvent& event)
533 if(!mIsKeyboardFocusEnabled)
538 AccessibilityAdaptor accessibilityAdaptor = AccessibilityAdaptor::Get();
539 bool isAccessibilityEnabled = accessibilityAdaptor.IsEnabled();
541 Toolkit::AccessibilityManager accessibilityManager = Toolkit::AccessibilityManager::Get();
543 std::string keyName = event.keyPressedName;
545 bool isFocusStartableKey = false;
547 if(event.state == KeyEvent::Down)
549 if (keyName == "Left")
551 if(!isAccessibilityEnabled)
553 if(!mIsFocusIndicatorEnabled)
555 // Show focus indicator
556 mIsFocusIndicatorEnabled = true;
560 // Move the focus towards left
561 MoveFocus(Toolkit::Control::KeyboardFocus::LEFT);
564 isFocusStartableKey = true;
568 // Move the accessibility focus backward
569 accessibilityManager.MoveFocusBackward();
572 else if (keyName == "Right")
574 if(!isAccessibilityEnabled)
576 if(!mIsFocusIndicatorEnabled)
578 // Show focus indicator
579 mIsFocusIndicatorEnabled = true;
583 // Move the focus towards right
584 MoveFocus(Toolkit::Control::KeyboardFocus::RIGHT);
589 // Move the accessibility focus forward
590 accessibilityManager.MoveFocusForward();
593 isFocusStartableKey = true;
595 else if (keyName == "Up" && !isAccessibilityEnabled)
597 if(!mIsFocusIndicatorEnabled)
599 // Show focus indicator
600 mIsFocusIndicatorEnabled = true;
604 // Move the focus towards up
605 MoveFocus(Toolkit::Control::KeyboardFocus::UP);
608 isFocusStartableKey = true;
610 else if (keyName == "Down" && !isAccessibilityEnabled)
612 if(!mIsFocusIndicatorEnabled)
614 // Show focus indicator
615 mIsFocusIndicatorEnabled = true;
619 // Move the focus towards down
620 MoveFocus(Toolkit::Control::KeyboardFocus::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