2 * Copyright (c) 2015 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 <dali-toolkit/internal/text/text-controller.h>
23 #include <dali/public-api/adaptor-framework/key.h>
24 #include <dali/integration-api/debug.h>
25 #include <dali/devel-api/adaptor-framework/clipboard-event-notifier.h>
28 #include <dali-toolkit/internal/text/bidirectional-support.h>
29 #include <dali-toolkit/internal/text/character-set-conversion.h>
30 #include <dali-toolkit/internal/text/layouts/layout-parameters.h>
31 #include <dali-toolkit/internal/text/markup-processor.h>
32 #include <dali-toolkit/internal/text/text-controller-impl.h>
37 #if defined(DEBUG_ENABLED)
38 Debug::Filter* gLogFilter = Debug::Filter::New(Debug::NoLogging, true, "LOG_TEXT_CONTROLS");
41 const float MAX_FLOAT = std::numeric_limits<float>::max();
42 const unsigned int POINTS_PER_INCH = 72;
44 const std::string EMPTY_STRING("");
45 const unsigned int ZERO = 0u;
47 float ConvertToEven( float value )
49 int intValue(static_cast<int>( value ));
50 return static_cast<float>(intValue % 2 == 0) ? intValue : (intValue + 1);
64 ControllerPtr Controller::New( ControlInterface& controlInterface )
66 return ControllerPtr( new Controller( controlInterface ) );
69 void Controller::EnableTextInput( DecoratorPtr decorator )
71 if( !mImpl->mEventData )
73 mImpl->mEventData = new EventData( decorator );
77 void Controller::SetMarkupProcessorEnabled( bool enable )
79 mImpl->mMarkupProcessorEnabled = enable;
82 bool Controller::IsMarkupProcessorEnabled() const
84 return mImpl->mMarkupProcessorEnabled;
87 void Controller::SetText( const std::string& text )
89 DALI_LOG_INFO( gLogFilter, Debug::Verbose, "Controller::SetText\n" );
91 // Reset keyboard as text changed
92 mImpl->ResetImfManager();
94 // Remove the previously set text
97 CharacterIndex lastCursorIndex = 0u;
99 if( mImpl->mEventData )
101 // If popup shown then hide it by switching to Editing state
102 if( ( EventData::SELECTING == mImpl->mEventData->mState ) ||
103 ( EventData::EDITING_WITH_POPUP == mImpl->mEventData->mState ) ||
104 ( EventData::EDITING_WITH_GRAB_HANDLE == mImpl->mEventData->mState ) ||
105 ( EventData::EDITING_WITH_PASTE_POPUP == mImpl->mEventData->mState ) )
107 mImpl->ChangeState( EventData::EDITING );
113 MarkupProcessData markupProcessData;
115 Length textSize = 0u;
116 const uint8_t* utf8 = NULL;
117 if( mImpl->mMarkupProcessorEnabled )
119 ProcessMarkupString( text, markupProcessData );
120 textSize = markupProcessData.markupProcessedText.size();
122 // This is a bit horrible but std::string returns a (signed) char*
123 utf8 = reinterpret_cast<const uint8_t*>( markupProcessData.markupProcessedText.c_str() );
127 textSize = text.size();
129 // This is a bit horrible but std::string returns a (signed) char*
130 utf8 = reinterpret_cast<const uint8_t*>( text.c_str() );
133 // Convert text into UTF-32
134 Vector<Character>& utf32Characters = mImpl->mLogicalModel->mText;
135 utf32Characters.Resize( textSize );
137 // Transform a text array encoded in utf8 into an array encoded in utf32.
138 // It returns the actual number of characters.
139 Length characterCount = Utf8ToUtf32( utf8, textSize, utf32Characters.Begin() );
140 utf32Characters.Resize( characterCount );
142 DALI_ASSERT_DEBUG( textSize >= characterCount && "Invalid UTF32 conversion length" );
143 DALI_LOG_INFO( gLogFilter, Debug::Verbose, "Controller::SetText %p UTF8 size %d, UTF32 size %d\n", this, textSize, mImpl->mLogicalModel->mText.Count() );
145 // To reset the cursor position
146 lastCursorIndex = characterCount;
148 // Update the rest of the model during size negotiation
149 mImpl->QueueModifyEvent( ModifyEvent::TEXT_REPLACED );
151 // The natural size needs to be re-calculated.
152 mImpl->mRecalculateNaturalSize = true;
154 // Apply modifications to the model
155 mImpl->mOperationsPending = ALL_OPERATIONS;
159 ShowPlaceholderText();
162 // Resets the cursor position.
163 ResetCursorPosition( lastCursorIndex );
165 // Scrolls the text to make the cursor visible.
166 ResetScrollPosition();
168 mImpl->RequestRelayout();
170 if( mImpl->mEventData )
172 // Cancel previously queued events
173 mImpl->mEventData->mEventQueue.clear();
176 // Notify IMF as text changed
179 // Do this last since it provides callbacks into application code
180 mImpl->mControlInterface.TextChanged();
183 void Controller::GetText( std::string& text ) const
185 if( ! mImpl->IsShowingPlaceholderText() )
187 Vector<Character>& utf32Characters = mImpl->mLogicalModel->mText;
189 if( 0u != utf32Characters.Count() )
191 Utf32ToUtf8( &utf32Characters[0], utf32Characters.Count(), text );
196 DALI_LOG_INFO( gLogFilter, Debug::Verbose, "Controller::GetText %p empty (but showing placeholder)\n", this );
200 unsigned int Controller::GetLogicalCursorPosition() const
202 if( mImpl->mEventData )
204 return mImpl->mEventData->mPrimaryCursorPosition;
210 void Controller::SetPlaceholderText( PlaceholderType type, const std::string& text )
212 if( mImpl->mEventData )
214 if( PLACEHOLDER_TYPE_INACTIVE == type )
216 mImpl->mEventData->mPlaceholderTextInactive = text;
220 mImpl->mEventData->mPlaceholderTextActive = text;
223 // Update placeholder if there is no text
224 if( mImpl->IsShowingPlaceholderText() ||
225 0u == mImpl->mLogicalModel->mText.Count() )
227 ShowPlaceholderText();
232 void Controller::GetPlaceholderText( PlaceholderType type, std::string& text ) const
234 if( mImpl->mEventData )
236 if( PLACEHOLDER_TYPE_INACTIVE == type )
238 text = mImpl->mEventData->mPlaceholderTextInactive;
242 text = mImpl->mEventData->mPlaceholderTextActive;
247 void Controller::SetMaximumNumberOfCharacters( int maxCharacters )
249 if ( maxCharacters >= 0 )
251 mImpl->mMaximumNumberOfCharacters = maxCharacters;
255 int Controller::GetMaximumNumberOfCharacters()
257 return mImpl->mMaximumNumberOfCharacters;
260 void Controller::SetDefaultFontFamily( const std::string& defaultFontFamily )
262 if( !mImpl->mFontDefaults )
264 mImpl->mFontDefaults = new FontDefaults();
267 mImpl->mFontDefaults->mFontDescription.family = defaultFontFamily;
268 DALI_LOG_INFO( gLogFilter, Debug::General, "Controller::SetDefaultFontFamily %s\n", defaultFontFamily.c_str());
269 mImpl->mUserDefinedFontFamily = true;
271 // Clear the font-specific data
274 mImpl->mOperationsPending = ALL_OPERATIONS;
275 mImpl->mRecalculateNaturalSize = true;
277 mImpl->RequestRelayout();
280 const std::string& Controller::GetDefaultFontFamily() const
282 if( mImpl->mFontDefaults )
284 return mImpl->mFontDefaults->mFontDescription.family;
290 void Controller::SetDefaultFontStyle( const std::string& style )
292 if( !mImpl->mFontDefaults )
294 mImpl->mFontDefaults = new FontDefaults();
297 mImpl->mFontDefaults->mFontStyle = style;
300 const std::string& Controller::GetDefaultFontStyle() const
302 if( mImpl->mFontDefaults )
304 return mImpl->mFontDefaults->mFontStyle;
310 void Controller::SetDefaultFontWidth( FontWidth width )
312 if( !mImpl->mFontDefaults )
314 mImpl->mFontDefaults = new FontDefaults();
317 mImpl->mFontDefaults->mFontDescription.width = width;
319 // Clear the font-specific data
322 mImpl->mOperationsPending = ALL_OPERATIONS;
323 mImpl->mRecalculateNaturalSize = true;
325 mImpl->RequestRelayout();
328 FontWidth Controller::GetDefaultFontWidth() const
330 if( mImpl->mFontDefaults )
332 return mImpl->mFontDefaults->mFontDescription.width;
335 return TextAbstraction::FontWidth::NORMAL;
338 void Controller::SetDefaultFontWeight( FontWeight weight )
340 if( !mImpl->mFontDefaults )
342 mImpl->mFontDefaults = new FontDefaults();
345 mImpl->mFontDefaults->mFontDescription.weight = weight;
347 // Clear the font-specific data
350 mImpl->mOperationsPending = ALL_OPERATIONS;
351 mImpl->mRecalculateNaturalSize = true;
353 mImpl->RequestRelayout();
356 FontWeight Controller::GetDefaultFontWeight() const
358 if( mImpl->mFontDefaults )
360 return mImpl->mFontDefaults->mFontDescription.weight;
363 return TextAbstraction::FontWeight::NORMAL;
366 void Controller::SetDefaultFontSlant( FontSlant slant )
368 if( !mImpl->mFontDefaults )
370 mImpl->mFontDefaults = new FontDefaults();
373 mImpl->mFontDefaults->mFontDescription.slant = slant;
375 // Clear the font-specific data
378 mImpl->mOperationsPending = ALL_OPERATIONS;
379 mImpl->mRecalculateNaturalSize = true;
381 mImpl->RequestRelayout();
384 FontSlant Controller::GetDefaultFontSlant() const
386 if( mImpl->mFontDefaults )
388 return mImpl->mFontDefaults->mFontDescription.slant;
391 return TextAbstraction::FontSlant::NORMAL;
394 void Controller::SetDefaultPointSize( float pointSize )
396 if( !mImpl->mFontDefaults )
398 mImpl->mFontDefaults = new FontDefaults();
401 mImpl->mFontDefaults->mDefaultPointSize = pointSize;
403 unsigned int horizontalDpi( 0u );
404 unsigned int verticalDpi( 0u );
405 mImpl->mFontClient.GetDpi( horizontalDpi, verticalDpi );
407 // Adjust the metrics if the fixed-size font should be down-scaled
408 int maxEmojiSize( pointSize/POINTS_PER_INCH * verticalDpi );
409 DALI_LOG_INFO( gLogFilter, Debug::General, "Controller::SetDefaultPointSize %p setting MaxEmojiSize %d\n", this, maxEmojiSize );
410 mImpl->mMetrics->SetMaxEmojiSize( maxEmojiSize );
412 // Clear the font-specific data
415 mImpl->mOperationsPending = ALL_OPERATIONS;
416 mImpl->mRecalculateNaturalSize = true;
418 mImpl->RequestRelayout();
421 float Controller::GetDefaultPointSize() const
423 if( mImpl->mFontDefaults )
425 return mImpl->mFontDefaults->mDefaultPointSize;
431 void Controller::UpdateAfterFontChange( std::string& newDefaultFont )
433 DALI_LOG_INFO( gLogFilter, Debug::Concise, "Controller::UpdateAfterFontChange");
435 if ( !mImpl->mUserDefinedFontFamily ) // If user defined font then should not update when system font changes
437 DALI_LOG_INFO( gLogFilter, Debug::Concise, "Controller::UpdateAfterFontChange newDefaultFont(%s)\n", newDefaultFont.c_str() );
439 mImpl->mFontDefaults->mFontDescription.family = newDefaultFont;
440 mImpl->UpdateModel( ALL_OPERATIONS );
441 mImpl->QueueModifyEvent( ModifyEvent::TEXT_REPLACED );
442 mImpl->mRecalculateNaturalSize = true;
443 mImpl->RequestRelayout();
447 void Controller::SetTextColor( const Vector4& textColor )
449 mImpl->mTextColor = textColor;
451 if( !mImpl->IsShowingPlaceholderText() )
453 mImpl->mVisualModel->SetTextColor( textColor );
455 mImpl->RequestRelayout();
459 const Vector4& Controller::GetTextColor() const
461 return mImpl->mTextColor;
464 bool Controller::RemoveText( int cursorOffset, int numberOfChars )
466 bool removed( false );
468 DALI_LOG_INFO( gLogFilter, Debug::General, "Controller::RemoveText %p mText.Count() %d cursor %d cursorOffset %d numberOfChars %d\n",
469 this, mImpl->mLogicalModel->mText.Count(), mImpl->mEventData->mPrimaryCursorPosition, cursorOffset, numberOfChars );
471 if( !mImpl->IsShowingPlaceholderText() )
473 // Delete at current cursor position
474 Vector<Character>& currentText = mImpl->mLogicalModel->mText;
475 CharacterIndex& oldCursorIndex = mImpl->mEventData->mPrimaryCursorPosition;
477 CharacterIndex cursorIndex = oldCursorIndex;
479 // Validate the cursor position & number of characters
480 if( static_cast< CharacterIndex >( std::abs( cursorOffset ) ) <= cursorIndex )
482 cursorIndex = oldCursorIndex + cursorOffset;
485 if( ( cursorIndex + numberOfChars ) > currentText.Count() )
487 numberOfChars = currentText.Count() - cursorIndex;
490 if( ( cursorIndex + numberOfChars ) <= currentText.Count() )
492 Vector<Character>::Iterator first = currentText.Begin() + cursorIndex;
493 Vector<Character>::Iterator last = first + numberOfChars;
495 currentText.Erase( first, last );
497 // Cursor position retreat
498 oldCursorIndex = cursorIndex;
500 DALI_LOG_INFO( gLogFilter, Debug::General, "Controller::RemoveText %p removed %d\n", this, numberOfChars );
508 void Controller::SetPlaceholderTextColor( const Vector4& textColor )
510 if( mImpl->mEventData )
512 mImpl->mEventData->mPlaceholderTextColor = textColor;
515 if( mImpl->IsShowingPlaceholderText() )
517 mImpl->mVisualModel->SetTextColor( textColor );
518 mImpl->RequestRelayout();
522 const Vector4& Controller::GetPlaceholderTextColor() const
524 if( mImpl->mEventData )
526 return mImpl->mEventData->mPlaceholderTextColor;
532 void Controller::SetShadowOffset( const Vector2& shadowOffset )
534 mImpl->mVisualModel->SetShadowOffset( shadowOffset );
536 mImpl->RequestRelayout();
539 const Vector2& Controller::GetShadowOffset() const
541 return mImpl->mVisualModel->GetShadowOffset();
544 void Controller::SetShadowColor( const Vector4& shadowColor )
546 mImpl->mVisualModel->SetShadowColor( shadowColor );
548 mImpl->RequestRelayout();
551 const Vector4& Controller::GetShadowColor() const
553 return mImpl->mVisualModel->GetShadowColor();
556 void Controller::SetUnderlineColor( const Vector4& color )
558 mImpl->mVisualModel->SetUnderlineColor( color );
560 mImpl->RequestRelayout();
563 const Vector4& Controller::GetUnderlineColor() const
565 return mImpl->mVisualModel->GetUnderlineColor();
568 void Controller::SetUnderlineEnabled( bool enabled )
570 mImpl->mVisualModel->SetUnderlineEnabled( enabled );
572 mImpl->RequestRelayout();
575 bool Controller::IsUnderlineEnabled() const
577 return mImpl->mVisualModel->IsUnderlineEnabled();
580 void Controller::SetUnderlineHeight( float height )
582 mImpl->mVisualModel->SetUnderlineHeight( height );
584 mImpl->RequestRelayout();
587 float Controller::GetUnderlineHeight() const
589 return mImpl->mVisualModel->GetUnderlineHeight();
592 void Controller::SetEnableCursorBlink( bool enable )
594 DALI_ASSERT_DEBUG( NULL != mImpl->mEventData && "TextInput disabled" );
596 if( mImpl->mEventData )
598 mImpl->mEventData->mCursorBlinkEnabled = enable;
601 mImpl->mEventData->mDecorator )
603 mImpl->mEventData->mDecorator->StopCursorBlink();
608 bool Controller::GetEnableCursorBlink() const
610 if( mImpl->mEventData )
612 return mImpl->mEventData->mCursorBlinkEnabled;
618 const Vector2& Controller::GetScrollPosition() const
620 if( mImpl->mEventData )
622 return mImpl->mEventData->mScrollPosition;
625 return Vector2::ZERO;
628 const Vector2& Controller::GetAlignmentOffset() const
630 return mImpl->mAlignmentOffset;
633 Vector3 Controller::GetNaturalSize()
635 DALI_LOG_INFO( gLogFilter, Debug::Verbose, "-->Controller::GetNaturalSize\n" );
638 // Make sure the model is up-to-date before layouting
639 ProcessModifyEvents();
641 if( mImpl->mRecalculateNaturalSize )
643 // Operations that can be done only once until the text changes.
644 const OperationsMask onlyOnceOperations = static_cast<OperationsMask>( CONVERT_TO_UTF32 |
652 // Make sure the model is up-to-date before layouting
653 mImpl->UpdateModel( onlyOnceOperations );
655 // Operations that need to be done if the size changes.
656 const OperationsMask sizeOperations = static_cast<OperationsMask>( LAYOUT |
660 DoRelayout( Size( MAX_FLOAT, MAX_FLOAT ),
661 static_cast<OperationsMask>( onlyOnceOperations |
663 naturalSize.GetVectorXY() );
665 // Do not do again the only once operations.
666 mImpl->mOperationsPending = static_cast<OperationsMask>( mImpl->mOperationsPending & ~onlyOnceOperations );
668 // Do the size related operations again.
669 mImpl->mOperationsPending = static_cast<OperationsMask>( mImpl->mOperationsPending | sizeOperations );
671 // Stores the natural size to avoid recalculate it again
672 // unless the text/style changes.
673 mImpl->mVisualModel->SetNaturalSize( naturalSize.GetVectorXY() );
675 mImpl->mRecalculateNaturalSize = false;
677 DALI_LOG_INFO( gLogFilter, Debug::Verbose, "<--Controller::GetNaturalSize calculated %f,%f,%f\n", naturalSize.x, naturalSize.y, naturalSize.z );
681 naturalSize = mImpl->mVisualModel->GetNaturalSize();
683 DALI_LOG_INFO( gLogFilter, Debug::Verbose, "<--Controller::GetNaturalSize cached %f,%f,%f\n", naturalSize.x, naturalSize.y, naturalSize.z );
686 naturalSize.x = ConvertToEven( naturalSize.x );
687 naturalSize.y = ConvertToEven( naturalSize.y );
692 float Controller::GetHeightForWidth( float width )
694 DALI_LOG_INFO( gLogFilter, Debug::Verbose, "-->Controller::GetHeightForWidth %p width %f\n", this, width );
695 // Make sure the model is up-to-date before layouting
696 ProcessModifyEvents();
699 if( fabsf( width - mImpl->mVisualModel->mControlSize.width ) > Math::MACHINE_EPSILON_1000 )
701 // Operations that can be done only once until the text changes.
702 const OperationsMask onlyOnceOperations = static_cast<OperationsMask>( CONVERT_TO_UTF32 |
710 // Make sure the model is up-to-date before layouting
711 mImpl->UpdateModel( onlyOnceOperations );
713 // Operations that need to be done if the size changes.
714 const OperationsMask sizeOperations = static_cast<OperationsMask>( LAYOUT |
718 DoRelayout( Size( width, MAX_FLOAT ),
719 static_cast<OperationsMask>( onlyOnceOperations |
723 // Do not do again the only once operations.
724 mImpl->mOperationsPending = static_cast<OperationsMask>( mImpl->mOperationsPending & ~onlyOnceOperations );
726 // Do the size related operations again.
727 mImpl->mOperationsPending = static_cast<OperationsMask>( mImpl->mOperationsPending | sizeOperations );
728 DALI_LOG_INFO( gLogFilter, Debug::Verbose, "<--Controller::GetHeightForWidth calculated %f\n", layoutSize.height );
732 layoutSize = mImpl->mVisualModel->GetActualSize();
733 DALI_LOG_INFO( gLogFilter, Debug::Verbose, "<--Controller::GetHeightForWidth cached %f\n", layoutSize.height );
736 return layoutSize.height;
739 bool Controller::Relayout( const Size& size )
741 DALI_LOG_INFO( gLogFilter, Debug::Verbose, "-->Controller::Relayout %p size %f,%f\n", this, size.width, size.height );
743 if( ( size.width < Math::MACHINE_EPSILON_1000 ) || ( size.height < Math::MACHINE_EPSILON_1000 ) )
745 bool glyphsRemoved( false );
746 if( 0u != mImpl->mVisualModel->mGlyphPositions.Count() )
748 mImpl->mVisualModel->mGlyphPositions.Clear();
749 glyphsRemoved = true;
751 // Not worth to relayout if width or height is equal to zero.
752 DALI_LOG_INFO( gLogFilter, Debug::Verbose, "<--Controller::Relayout (skipped)\n" );
753 return glyphsRemoved;
756 const bool newSize = ( size != mImpl->mVisualModel->mControlSize );
760 DALI_LOG_INFO( gLogFilter, Debug::Verbose, "new size (previous size %f,%f)\n", mImpl->mVisualModel->mControlSize.width, mImpl->mVisualModel->mControlSize.height );
762 // Operations that need to be done if the size changes.
763 mImpl->mOperationsPending = static_cast<OperationsMask>( mImpl->mOperationsPending |
769 mImpl->mVisualModel->mControlSize = size;
772 // Make sure the model is up-to-date before layouting
773 ProcessModifyEvents();
774 mImpl->UpdateModel( mImpl->mOperationsPending );
777 bool updated = DoRelayout( mImpl->mVisualModel->mControlSize,
778 mImpl->mOperationsPending,
781 // Do not re-do any operation until something changes.
782 mImpl->mOperationsPending = NO_OPERATION;
784 // Keep the current offset and alignment as it will be used to update the decorator's positions (if the size changes).
786 if( newSize && mImpl->mEventData )
788 offset = mImpl->mAlignmentOffset + mImpl->mEventData->mScrollPosition;
791 // After doing the text layout, the alignment offset to place the actor in the desired position can be calculated.
792 CalculateTextAlignment( size );
794 if( mImpl->mEventData )
798 // If there is a new size, the scroll position needs to be clamped.
799 mImpl->ClampHorizontalScroll( layoutSize );
801 // Update the decorator's positions is needed if there is a new size.
802 mImpl->mEventData->mDecorator->UpdatePositions( mImpl->mAlignmentOffset + mImpl->mEventData->mScrollPosition - offset );
805 // Move the cursor, grab handle etc.
806 updated = mImpl->ProcessInputEvents() || updated;
809 DALI_LOG_INFO( gLogFilter, Debug::Verbose, "<--Controller::Relayout\n" );
813 void Controller::ProcessModifyEvents()
815 Vector<ModifyEvent>& events = mImpl->mModifyEvents;
817 if( 0u == events.Count() )
823 for( Vector<ModifyEvent>::ConstIterator it = events.Begin(),
824 endIt = events.End();
828 const ModifyEvent& event = *it;
830 if( ModifyEvent::TEXT_REPLACED == event.type )
832 // A (single) replace event should come first, otherwise we wasted time processing NOOP events
833 DALI_ASSERT_DEBUG( it == events.Begin() && "Unexpected TEXT_REPLACED event" );
837 else if( ModifyEvent::TEXT_INSERTED == event.type )
841 else if( ModifyEvent::TEXT_DELETED == event.type )
843 // Placeholder-text cannot be deleted
844 if( !mImpl->IsShowingPlaceholderText() )
851 if( mImpl->mEventData )
853 // When the text is being modified, delay cursor blinking
854 mImpl->mEventData->mDecorator->DelayCursorBlink();
857 // Discard temporary text
861 void Controller::ResetText()
864 mImpl->mLogicalModel->mText.Clear();
867 // We have cleared everything including the placeholder-text
868 mImpl->PlaceholderCleared();
870 // The natural size needs to be re-calculated.
871 mImpl->mRecalculateNaturalSize = true;
873 // Apply modifications to the model
874 mImpl->mOperationsPending = ALL_OPERATIONS;
877 void Controller::ResetCursorPosition( CharacterIndex cursorIndex )
879 // Reset the cursor position
880 if( NULL != mImpl->mEventData )
882 mImpl->mEventData->mPrimaryCursorPosition = cursorIndex;
884 // Update the cursor if it's in editing mode.
885 if ( EventData::IsEditingState( mImpl->mEventData->mState ) )
887 mImpl->mEventData->mUpdateCursorPosition = true;
892 void Controller::ResetScrollPosition()
894 if( NULL != mImpl->mEventData )
896 // Reset the scroll position.
897 mImpl->mEventData->mScrollPosition = Vector2::ZERO;
898 mImpl->mEventData->mScrollAfterUpdatePosition = true;
902 void Controller::TextReplacedEvent()
907 // The natural size needs to be re-calculated.
908 mImpl->mRecalculateNaturalSize = true;
910 // Apply modifications to the model
911 mImpl->mOperationsPending = ALL_OPERATIONS;
912 mImpl->UpdateModel( ALL_OPERATIONS );
913 mImpl->mOperationsPending = static_cast<OperationsMask>( LAYOUT |
919 void Controller::TextInsertedEvent()
921 DALI_ASSERT_DEBUG( NULL != mImpl->mEventData && "Unexpected TextInsertedEvent" );
923 // TODO - Optimize this
926 // The natural size needs to be re-calculated.
927 mImpl->mRecalculateNaturalSize = true;
929 // Apply modifications to the model; TODO - Optimize this
930 mImpl->mOperationsPending = ALL_OPERATIONS;
931 mImpl->UpdateModel( ALL_OPERATIONS );
932 mImpl->mOperationsPending = static_cast<OperationsMask>( LAYOUT |
937 // Queue a cursor reposition event; this must wait until after DoRelayout()
938 if ( EventData::IsEditingState( mImpl->mEventData->mState ) )
940 mImpl->mEventData->mUpdateCursorPosition = true;
941 mImpl->mEventData->mScrollAfterUpdatePosition = true;
945 void Controller::TextDeletedEvent()
947 DALI_ASSERT_DEBUG( NULL != mImpl->mEventData && "Unexpected TextDeletedEvent" );
949 // TODO - Optimize this
952 // The natural size needs to be re-calculated.
953 mImpl->mRecalculateNaturalSize = true;
955 // Apply modifications to the model; TODO - Optimize this
956 mImpl->mOperationsPending = ALL_OPERATIONS;
957 mImpl->UpdateModel( ALL_OPERATIONS );
958 mImpl->mOperationsPending = static_cast<OperationsMask>( LAYOUT |
963 // Queue a cursor reposition event; this must wait until after DoRelayout()
964 mImpl->mEventData->mUpdateCursorPosition = true;
965 if( 0u != mImpl->mLogicalModel->mText.Count() )
967 mImpl->mEventData->mScrollAfterDelete = true;
971 bool Controller::DoRelayout( const Size& size,
972 OperationsMask operationsRequired,
975 DALI_LOG_INFO( gLogFilter, Debug::Verbose, "-->Controller::DoRelayout %p size %f,%f\n", this, size.width, size.height );
976 bool viewUpdated( false );
978 // Calculate the operations to be done.
979 const OperationsMask operations = static_cast<OperationsMask>( mImpl->mOperationsPending & operationsRequired );
981 if( LAYOUT & operations )
983 // Some vectors with data needed to layout and reorder may be void
984 // after the first time the text has been laid out.
985 // Fill the vectors again.
987 const Length numberOfGlyphs = mImpl->mVisualModel->mGlyphs.Count();
989 if( 0u == numberOfGlyphs )
991 // Nothing else to do if there is no glyphs.
992 DALI_LOG_INFO( gLogFilter, Debug::Verbose, "<--Controller::DoRelayout no glyphs, view updated true\n" );
996 const Vector<LineBreakInfo>& lineBreakInfo = mImpl->mLogicalModel->mLineBreakInfo;
997 const Vector<WordBreakInfo>& wordBreakInfo = mImpl->mLogicalModel->mWordBreakInfo;
998 const Vector<CharacterDirection>& characterDirection = mImpl->mLogicalModel->mCharacterDirections;
999 const Vector<GlyphInfo>& glyphs = mImpl->mVisualModel->mGlyphs;
1000 const Vector<CharacterIndex>& glyphsToCharactersMap = mImpl->mVisualModel->mGlyphsToCharacters;
1001 const Vector<Length>& charactersPerGlyph = mImpl->mVisualModel->mCharactersPerGlyph;
1002 const Character* const textBuffer = mImpl->mLogicalModel->mText.Begin();
1004 // Set the layout parameters.
1005 LayoutParameters layoutParameters( size,
1007 lineBreakInfo.Begin(),
1008 wordBreakInfo.Begin(),
1009 ( 0u != characterDirection.Count() ) ? characterDirection.Begin() : NULL,
1012 glyphsToCharactersMap.Begin(),
1013 charactersPerGlyph.Begin() );
1015 // The laid-out lines.
1016 // It's not possible to know in how many lines the text is going to be laid-out,
1017 // but it can be resized at least with the number of 'paragraphs' to avoid
1018 // some re-allocations.
1019 Vector<LineRun>& lines = mImpl->mVisualModel->mLines;
1021 // Delete any previous laid out lines before setting the new ones.
1024 // The capacity of the bidirectional paragraph info is the number of paragraphs.
1025 lines.Reserve( mImpl->mLogicalModel->mBidirectionalParagraphInfo.Capacity() );
1027 // Resize the vector of positions to have the same size than the vector of glyphs.
1028 Vector<Vector2>& glyphPositions = mImpl->mVisualModel->mGlyphPositions;
1029 glyphPositions.Resize( numberOfGlyphs );
1031 // Whether the last character is a new paragraph character.
1032 layoutParameters.isLastNewParagraph = TextAbstraction::IsNewParagraph( *( textBuffer + ( mImpl->mLogicalModel->mText.Count() - 1u ) ) );
1034 // Update the visual model.
1035 viewUpdated = mImpl->mLayoutEngine.LayoutText( layoutParameters,
1042 // Reorder the lines
1043 if( REORDER & operations )
1045 Vector<BidirectionalParagraphInfoRun>& bidirectionalInfo = mImpl->mLogicalModel->mBidirectionalParagraphInfo;
1047 // Check first if there are paragraphs with bidirectional info.
1048 if( 0u != bidirectionalInfo.Count() )
1051 const Length numberOfLines = mImpl->mVisualModel->mLines.Count();
1053 // Reorder the lines.
1054 Vector<BidirectionalLineInfoRun> lineBidirectionalInfoRuns;
1055 lineBidirectionalInfoRuns.Reserve( numberOfLines ); // Reserve because is not known yet how many lines have right to left characters.
1056 ReorderLines( bidirectionalInfo,
1058 lineBidirectionalInfoRuns );
1060 // Set the bidirectional info into the model.
1061 const Length numberOfBidirectionalInfoRuns = lineBidirectionalInfoRuns.Count();
1062 mImpl->mLogicalModel->SetVisualToLogicalMap( lineBidirectionalInfoRuns.Begin(),
1063 numberOfBidirectionalInfoRuns );
1065 // Set the bidirectional info per line into the layout parameters.
1066 layoutParameters.lineBidirectionalInfoRunsBuffer = lineBidirectionalInfoRuns.Begin();
1067 layoutParameters.numberOfBidirectionalInfoRuns = numberOfBidirectionalInfoRuns;
1069 // Get the character to glyph conversion table and set into the layout.
1070 layoutParameters.charactersToGlyphsBuffer = mImpl->mVisualModel->mCharactersToGlyph.Begin();
1072 // Get the glyphs per character table and set into the layout.
1073 layoutParameters.glyphsPerCharacterBuffer = mImpl->mVisualModel->mGlyphsPerCharacter.Begin();
1075 // Re-layout the text. Reorder those lines with right to left characters.
1076 mImpl->mLayoutEngine.ReLayoutRightToLeftLines( layoutParameters,
1079 // Free the allocated memory used to store the conversion table in the bidirectional line info run.
1080 for( Vector<BidirectionalLineInfoRun>::Iterator it = lineBidirectionalInfoRuns.Begin(),
1081 endIt = lineBidirectionalInfoRuns.End();
1085 BidirectionalLineInfoRun& bidiLineInfo = *it;
1087 free( bidiLineInfo.visualToLogicalMap );
1092 // Sets the actual size.
1093 if( UPDATE_ACTUAL_SIZE & operations )
1095 mImpl->mVisualModel->SetActualSize( layoutSize );
1101 layoutSize = mImpl->mVisualModel->GetActualSize();
1104 if( ALIGN & operations )
1106 // The laid-out lines.
1107 Vector<LineRun>& lines = mImpl->mVisualModel->mLines;
1109 mImpl->mLayoutEngine.Align( layoutSize,
1115 DALI_LOG_INFO( gLogFilter, Debug::Verbose, "<--Controller::DoRelayout, view updated %s\n", ( viewUpdated ? "true" : "false" ) );
1119 void Controller::SetMultiLineEnabled( bool enable )
1121 const LayoutEngine::Layout layout = enable ? LayoutEngine::MULTI_LINE_BOX : LayoutEngine::SINGLE_LINE_BOX;
1123 if( layout != mImpl->mLayoutEngine.GetLayout() )
1125 // Set the layout type.
1126 mImpl->mLayoutEngine.SetLayout( layout );
1128 // Set the flags to redo the layout operations
1129 const OperationsMask layoutOperations = static_cast<OperationsMask>( LAYOUT |
1130 UPDATE_ACTUAL_SIZE |
1134 mImpl->mOperationsPending = static_cast<OperationsMask>( mImpl->mOperationsPending | layoutOperations );
1136 mImpl->RequestRelayout();
1140 bool Controller::IsMultiLineEnabled() const
1142 return LayoutEngine::MULTI_LINE_BOX == mImpl->mLayoutEngine.GetLayout();
1145 void Controller::SetHorizontalAlignment( LayoutEngine::HorizontalAlignment alignment )
1147 if( alignment != mImpl->mLayoutEngine.GetHorizontalAlignment() )
1149 // Set the alignment.
1150 mImpl->mLayoutEngine.SetHorizontalAlignment( alignment );
1152 // Set the flag to redo the alignment operation.
1153 mImpl->mOperationsPending = static_cast<OperationsMask>( mImpl->mOperationsPending | ALIGN );
1155 mImpl->RequestRelayout();
1159 LayoutEngine::HorizontalAlignment Controller::GetHorizontalAlignment() const
1161 return mImpl->mLayoutEngine.GetHorizontalAlignment();
1164 void Controller::SetVerticalAlignment( LayoutEngine::VerticalAlignment alignment )
1166 if( alignment != mImpl->mLayoutEngine.GetVerticalAlignment() )
1168 // Set the alignment.
1169 mImpl->mLayoutEngine.SetVerticalAlignment( alignment );
1171 mImpl->mOperationsPending = static_cast<OperationsMask>( mImpl->mOperationsPending | ALIGN );
1173 mImpl->RequestRelayout();
1177 LayoutEngine::VerticalAlignment Controller::GetVerticalAlignment() const
1179 return mImpl->mLayoutEngine.GetVerticalAlignment();
1182 void Controller::CalculateTextAlignment( const Size& size )
1184 // Get the direction of the first character.
1185 const CharacterDirection firstParagraphDirection = mImpl->mLogicalModel->GetCharacterDirection( 0u );
1187 Size actualSize = mImpl->mVisualModel->GetActualSize();
1188 if( fabsf( actualSize.height ) < Math::MACHINE_EPSILON_1000 )
1190 // Get the line height of the default font.
1191 actualSize.height = mImpl->GetDefaultFontLineHeight();
1194 // If the first paragraph is right to left swap ALIGN_BEGIN and ALIGN_END;
1195 LayoutEngine::HorizontalAlignment horizontalAlignment = mImpl->mLayoutEngine.GetHorizontalAlignment();
1196 if( firstParagraphDirection &&
1197 ( LayoutEngine::HORIZONTAL_ALIGN_CENTER != horizontalAlignment ) )
1199 if( LayoutEngine::HORIZONTAL_ALIGN_BEGIN == horizontalAlignment )
1201 horizontalAlignment = LayoutEngine::HORIZONTAL_ALIGN_END;
1205 horizontalAlignment = LayoutEngine::HORIZONTAL_ALIGN_BEGIN;
1209 switch( horizontalAlignment )
1211 case LayoutEngine::HORIZONTAL_ALIGN_BEGIN:
1213 mImpl->mAlignmentOffset.x = 0.f;
1216 case LayoutEngine::HORIZONTAL_ALIGN_CENTER:
1218 mImpl->mAlignmentOffset.x = floorf( 0.5f * ( size.width - actualSize.width ) ); // try to avoid pixel alignment.
1221 case LayoutEngine::HORIZONTAL_ALIGN_END:
1223 mImpl->mAlignmentOffset.x = size.width - actualSize.width;
1228 const LayoutEngine::VerticalAlignment verticalAlignment = mImpl->mLayoutEngine.GetVerticalAlignment();
1229 switch( verticalAlignment )
1231 case LayoutEngine::VERTICAL_ALIGN_TOP:
1233 mImpl->mAlignmentOffset.y = 0.f;
1236 case LayoutEngine::VERTICAL_ALIGN_CENTER:
1238 mImpl->mAlignmentOffset.y = floorf( 0.5f * ( size.height - actualSize.height ) ); // try to avoid pixel alignment.
1241 case LayoutEngine::VERTICAL_ALIGN_BOTTOM:
1243 mImpl->mAlignmentOffset.y = size.height - actualSize.height;
1249 LayoutEngine& Controller::GetLayoutEngine()
1251 return mImpl->mLayoutEngine;
1254 View& Controller::GetView()
1256 return mImpl->mView;
1259 void Controller::KeyboardFocusGainEvent()
1261 DALI_ASSERT_DEBUG( mImpl->mEventData && "Unexpected KeyboardFocusGainEvent" );
1263 if( mImpl->mEventData )
1265 if( ( EventData::INACTIVE == mImpl->mEventData->mState ) ||
1266 ( EventData::INTERRUPTED == mImpl->mEventData->mState ) )
1268 mImpl->ChangeState( EventData::EDITING );
1269 mImpl->mEventData->mUpdateCursorPosition = true; //If editing started without tap event, cursor update must be triggered.
1272 if( mImpl->IsShowingPlaceholderText() )
1274 // Show alternative placeholder-text when editing
1275 ShowPlaceholderText();
1278 mImpl->RequestRelayout();
1282 void Controller::KeyboardFocusLostEvent()
1284 DALI_ASSERT_DEBUG( mImpl->mEventData && "Unexpected KeyboardFocusLostEvent" );
1286 if( mImpl->mEventData )
1288 if ( EventData::INTERRUPTED != mImpl->mEventData->mState )
1290 mImpl->ChangeState( EventData::INACTIVE );
1292 if( !mImpl->IsShowingRealText() )
1294 // Revert to regular placeholder-text when not editing
1295 ShowPlaceholderText();
1299 mImpl->RequestRelayout();
1302 bool Controller::KeyEvent( const Dali::KeyEvent& keyEvent )
1304 DALI_ASSERT_DEBUG( mImpl->mEventData && "Unexpected KeyEvent" );
1306 bool textChanged( false );
1308 if( mImpl->mEventData &&
1309 keyEvent.state == KeyEvent::Down )
1311 int keyCode = keyEvent.keyCode;
1312 const std::string& keyString = keyEvent.keyPressed;
1314 // Pre-process to separate modifying events from non-modifying input events.
1315 if( Dali::DALI_KEY_ESCAPE == keyCode )
1317 // Escape key is a special case which causes focus loss
1318 KeyboardFocusLostEvent();
1320 else if( Dali::DALI_KEY_CURSOR_LEFT == keyCode ||
1321 Dali::DALI_KEY_CURSOR_RIGHT == keyCode ||
1322 Dali::DALI_KEY_CURSOR_UP == keyCode ||
1323 Dali::DALI_KEY_CURSOR_DOWN == keyCode )
1325 Event event( Event::CURSOR_KEY_EVENT );
1326 event.p1.mInt = keyCode;
1327 mImpl->mEventData->mEventQueue.push_back( event );
1329 else if( Dali::DALI_KEY_BACKSPACE == keyCode )
1331 textChanged = BackspaceKeyEvent();
1333 else if ( IsKey( keyEvent, Dali::DALI_KEY_POWER ) )
1335 mImpl->ChangeState( EventData::INTERRUPTED ); // State is not INACTIVE as expect to return to edit mode.
1336 // Avoids calling the InsertText() method which can delete selected text
1338 else if ( IsKey( keyEvent, Dali::DALI_KEY_MENU ) ||
1339 IsKey( keyEvent, Dali::DALI_KEY_HOME ) )
1341 mImpl->ChangeState( EventData::INACTIVE );
1342 // Menu/Home key behaviour does not allow edit mode to resume like Power key
1343 // Avoids calling the InsertText() method which can delete selected text
1345 else if( Dali::DALI_KEY_SHIFT_LEFT == keyCode )
1347 // DALI_KEY_SHIFT_LEFT is the key code for the Left Shift. It's sent (by the imf?) when the predictive text is enabled
1348 // and a character is typed after the type of a upper case latin character.
1354 DALI_LOG_INFO( gLogFilter, Debug::Verbose, "Controller::KeyEvent %p keyString %s\n", this, keyString.c_str() );
1356 // IMF manager is no longer handling key-events
1357 mImpl->ClearPreEditFlag();
1359 InsertText( keyString, COMMIT );
1363 if ( ( mImpl->mEventData->mState != EventData::INTERRUPTED ) &&
1364 ( mImpl->mEventData->mState != EventData::INACTIVE ) )
1366 mImpl->ChangeState( EventData::EDITING );
1369 mImpl->RequestRelayout();
1374 // Do this last since it provides callbacks into application code
1375 mImpl->mControlInterface.TextChanged();
1381 void Controller::InsertText( const std::string& text, Controller::InsertType type )
1383 bool removedPrevious( false );
1384 bool maxLengthReached( false );
1386 DALI_ASSERT_DEBUG( NULL != mImpl->mEventData && "Unexpected InsertText" )
1387 DALI_LOG_INFO( gLogFilter, Debug::Verbose, "Controller::InsertText %p %s (%s) mPrimaryCursorPosition %d mPreEditFlag %d mPreEditStartPosition %d mPreEditLength %d\n",
1388 this, text.c_str(), (COMMIT == type ? "COMMIT" : "PRE_EDIT"),
1389 mImpl->mEventData->mPrimaryCursorPosition, mImpl->mEventData->mPreEditFlag, mImpl->mEventData->mPreEditStartPosition, mImpl->mEventData->mPreEditLength );
1391 // TODO: At the moment the underline runs are only for pre-edit.
1392 mImpl->mVisualModel->mUnderlineRuns.Clear();
1394 Vector<Character> utf32Characters;
1395 Length characterCount( 0u );
1397 // Remove the previous IMF pre-edit (predicitive text)
1398 if( mImpl->mEventData &&
1399 mImpl->mEventData->mPreEditFlag &&
1400 0 != mImpl->mEventData->mPreEditLength )
1402 CharacterIndex offset = mImpl->mEventData->mPrimaryCursorPosition - mImpl->mEventData->mPreEditStartPosition;
1404 removedPrevious = RemoveText( -static_cast<int>(offset), mImpl->mEventData->mPreEditLength );
1406 mImpl->mEventData->mPrimaryCursorPosition = mImpl->mEventData->mPreEditStartPosition;
1407 mImpl->mEventData->mPreEditLength = 0;
1411 // Remove the previous Selection
1412 removedPrevious = RemoveSelectedText();
1417 // Convert text into UTF-32
1418 utf32Characters.Resize( text.size() );
1420 // This is a bit horrible but std::string returns a (signed) char*
1421 const uint8_t* utf8 = reinterpret_cast<const uint8_t*>( text.c_str() );
1423 // Transform a text array encoded in utf8 into an array encoded in utf32.
1424 // It returns the actual number of characters.
1425 characterCount = Utf8ToUtf32( utf8, text.size(), utf32Characters.Begin() );
1426 utf32Characters.Resize( characterCount );
1428 DALI_ASSERT_DEBUG( text.size() >= utf32Characters.Count() && "Invalid UTF32 conversion length" );
1429 DALI_LOG_INFO( gLogFilter, Debug::Verbose, "UTF8 size %d, UTF32 size %d\n", text.size(), utf32Characters.Count() );
1432 if( 0u != utf32Characters.Count() ) // Check if Utf8ToUtf32 conversion succeeded
1434 // The placeholder text is no longer needed
1435 if( mImpl->IsShowingPlaceholderText() )
1440 mImpl->ChangeState( EventData::EDITING );
1442 // Handle the IMF (predicitive text) state changes
1443 if( mImpl->mEventData )
1445 if( COMMIT == type )
1447 // IMF manager is no longer handling key-events
1448 mImpl->ClearPreEditFlag();
1452 if( !mImpl->mEventData->mPreEditFlag )
1454 DALI_LOG_INFO( gLogFilter, Debug::Verbose, "Entered PreEdit state" );
1456 // Record the start of the pre-edit text
1457 mImpl->mEventData->mPreEditStartPosition = mImpl->mEventData->mPrimaryCursorPosition;
1460 mImpl->mEventData->mPreEditLength = utf32Characters.Count();
1461 mImpl->mEventData->mPreEditFlag = true;
1463 DALI_LOG_INFO( gLogFilter, Debug::Verbose, "mPreEditStartPosition %d mPreEditLength %d\n", mImpl->mEventData->mPreEditStartPosition, mImpl->mEventData->mPreEditLength );
1467 const Length numberOfCharactersInModel = mImpl->mLogicalModel->mText.Count();
1469 // Restrict new text to fit within Maximum characters setting
1470 Length maxSizeOfNewText = std::min ( ( mImpl->mMaximumNumberOfCharacters - numberOfCharactersInModel ), characterCount );
1471 maxLengthReached = ( characterCount > maxSizeOfNewText );
1473 // The cursor position.
1474 CharacterIndex& cursorIndex = mImpl->mEventData->mPrimaryCursorPosition;
1476 // Insert at current cursor position.
1477 Vector<Character>& modifyText = mImpl->mLogicalModel->mText;
1479 if( cursorIndex < numberOfCharactersInModel )
1481 modifyText.Insert( modifyText.Begin() + cursorIndex, utf32Characters.Begin(), utf32Characters.Begin() + maxSizeOfNewText );
1485 modifyText.Insert( modifyText.End(), utf32Characters.Begin(), utf32Characters.Begin() + maxSizeOfNewText );
1488 cursorIndex += maxSizeOfNewText;
1490 DALI_LOG_INFO( gLogFilter, Debug::Verbose, "Inserted %d characters, new size %d new cursor %d\n", maxSizeOfNewText, mImpl->mLogicalModel->mText.Count(), mImpl->mEventData->mPrimaryCursorPosition );
1493 if( 0u == mImpl->mLogicalModel->mText.Count() &&
1494 mImpl->IsPlaceholderAvailable() )
1496 // Show place-holder if empty after removing the pre-edit text
1497 ShowPlaceholderText();
1498 mImpl->mEventData->mUpdateCursorPosition = true;
1499 mImpl->ClearPreEditFlag();
1501 else if( removedPrevious ||
1502 0 != utf32Characters.Count() )
1504 // Queue an inserted event
1505 mImpl->QueueModifyEvent( ModifyEvent::TEXT_INSERTED );
1508 if( maxLengthReached )
1510 DALI_LOG_INFO( gLogFilter, Debug::Verbose, "MaxLengthReached (%d)\n", mImpl->mLogicalModel->mText.Count() );
1512 mImpl->ResetImfManager();
1514 // Do this last since it provides callbacks into application code
1515 mImpl->mControlInterface.MaxLengthReached();
1519 bool Controller::RemoveSelectedText()
1521 bool textRemoved( false );
1523 if( EventData::SELECTING == mImpl->mEventData->mState )
1525 std::string removedString;
1526 mImpl->RetrieveSelection( removedString, true );
1528 if( !removedString.empty() )
1531 mImpl->ChangeState( EventData::EDITING );
1538 void Controller::TapEvent( unsigned int tapCount, float x, float y )
1540 DALI_ASSERT_DEBUG( mImpl->mEventData && "Unexpected TapEvent" );
1542 if( NULL != mImpl->mEventData )
1544 DALI_LOG_INFO( gLogFilter, Debug::Concise, "TapEvent state:%d \n", mImpl->mEventData->mState );
1546 if( 1u == tapCount )
1548 // This is to avoid unnecessary relayouts when tapping an empty text-field
1549 bool relayoutNeeded( false );
1551 if ( EventData::EDITING_WITH_PASTE_POPUP == mImpl->mEventData->mState || EventData::EDITING_WITH_PASTE_POPUP == mImpl->mEventData->mState )
1553 mImpl->ChangeState( EventData::EDITING_WITH_GRAB_HANDLE); // If Popup shown hide it here so can be shown again if required.
1556 if( mImpl->IsShowingRealText() && ( EventData::INACTIVE != mImpl->mEventData->mState ) )
1558 // Already in an active state so show a popup
1559 if ( !mImpl->IsClipboardEmpty() )
1561 // Shows Paste popup but could show full popup with Selection options. ( EDITING_WITH_POPUP )
1562 mImpl->ChangeState( EventData::EDITING_WITH_PASTE_POPUP );
1566 mImpl->ChangeState( EventData::EDITING_WITH_GRAB_HANDLE );
1568 relayoutNeeded = true;
1572 if( mImpl->IsShowingPlaceholderText() && !mImpl->IsFocusedPlaceholderAvailable() )
1574 // Hide placeholder text
1578 if ( EventData::INACTIVE == mImpl->mEventData->mState )
1580 mImpl->ChangeState( EventData::EDITING );
1582 else if ( !mImpl->IsClipboardEmpty() )
1584 mImpl->ChangeState( EventData::EDITING_WITH_POPUP );
1586 relayoutNeeded = true;
1589 // Handles & cursors must be repositioned after Relayout() i.e. after the Model has been updated
1590 if( relayoutNeeded )
1592 Event event( Event::TAP_EVENT );
1593 event.p1.mUint = tapCount;
1594 event.p2.mFloat = x;
1595 event.p3.mFloat = y;
1596 mImpl->mEventData->mEventQueue.push_back( event );
1598 mImpl->RequestRelayout();
1601 else if( 2u == tapCount )
1603 if( mImpl->mEventData->mSelectionEnabled &&
1604 mImpl->IsShowingRealText() )
1606 SelectEvent( x, y, false );
1611 // Reset keyboard as tap event has occurred.
1612 mImpl->ResetImfManager();
1615 void Controller::PanEvent( Gesture::State state, const Vector2& displacement )
1616 // Show cursor and grabhandle on first tap, this matches the behaviour of tapping when already editing
1618 DALI_ASSERT_DEBUG( mImpl->mEventData && "Unexpected PanEvent" );
1620 if( mImpl->mEventData )
1622 Event event( Event::PAN_EVENT );
1623 event.p1.mInt = state;
1624 event.p2.mFloat = displacement.x;
1625 event.p3.mFloat = displacement.y;
1626 mImpl->mEventData->mEventQueue.push_back( event );
1628 mImpl->RequestRelayout();
1632 void Controller::LongPressEvent( Gesture::State state, float x, float y )
1634 DALI_ASSERT_DEBUG( mImpl->mEventData && "Unexpected LongPressEvent" );
1636 if( state == Gesture::Started &&
1639 if( ! mImpl->IsShowingRealText() )
1641 Event event( Event::LONG_PRESS_EVENT );
1642 event.p1.mInt = state;
1643 mImpl->mEventData->mEventQueue.push_back( event );
1644 mImpl->RequestRelayout();
1648 // The 1st long-press on inactive text-field is treated as tap
1649 if( EventData::INACTIVE == mImpl->mEventData->mState )
1651 mImpl->ChangeState( EventData::EDITING );
1653 Event event( Event::TAP_EVENT );
1655 event.p2.mFloat = x;
1656 event.p3.mFloat = y;
1657 mImpl->mEventData->mEventQueue.push_back( event );
1659 mImpl->RequestRelayout();
1663 // Reset the imf manger to commit the pre-edit before selecting the text.
1664 mImpl->ResetImfManager();
1666 SelectEvent( x, y, false );
1672 void Controller::SelectEvent( float x, float y, bool selectAll )
1674 DALI_LOG_INFO( gLogFilter, Debug::Verbose, "Controller::SelectEvent\n" );
1676 if( mImpl->mEventData )
1678 mImpl->ChangeState( EventData::SELECTING );
1682 Event event( Event::SELECT_ALL );
1683 mImpl->mEventData->mEventQueue.push_back( event );
1687 Event event( Event::SELECT );
1688 event.p2.mFloat = x;
1689 event.p3.mFloat = y;
1690 mImpl->mEventData->mEventQueue.push_back( event );
1693 mImpl->RequestRelayout();
1697 void Controller::GetTargetSize( Vector2& targetSize )
1699 targetSize = mImpl->mVisualModel->mControlSize;
1702 void Controller::AddDecoration( Actor& actor, bool needsClipping )
1704 mImpl->mControlInterface.AddDecoration( actor, needsClipping );
1707 void Controller::DecorationEvent( HandleType handleType, HandleState state, float x, float y )
1709 DALI_ASSERT_DEBUG( mImpl->mEventData && "Unexpected DecorationEvent" );
1711 if( mImpl->mEventData )
1713 switch( handleType )
1717 Event event( Event::GRAB_HANDLE_EVENT );
1718 event.p1.mUint = state;
1719 event.p2.mFloat = x;
1720 event.p3.mFloat = y;
1722 mImpl->mEventData->mEventQueue.push_back( event );
1725 case LEFT_SELECTION_HANDLE:
1727 Event event( Event::LEFT_SELECTION_HANDLE_EVENT );
1728 event.p1.mUint = state;
1729 event.p2.mFloat = x;
1730 event.p3.mFloat = y;
1732 mImpl->mEventData->mEventQueue.push_back( event );
1735 case RIGHT_SELECTION_HANDLE:
1737 Event event( Event::RIGHT_SELECTION_HANDLE_EVENT );
1738 event.p1.mUint = state;
1739 event.p2.mFloat = x;
1740 event.p3.mFloat = y;
1742 mImpl->mEventData->mEventQueue.push_back( event );
1745 case LEFT_SELECTION_HANDLE_MARKER:
1746 case RIGHT_SELECTION_HANDLE_MARKER:
1748 // Markers do not move the handles.
1751 case HANDLE_TYPE_COUNT:
1753 DALI_ASSERT_DEBUG( !"Controller::HandleEvent. Unexpected handle type" );
1757 mImpl->RequestRelayout();
1761 void Controller::PasteText( const std::string& stringToPaste )
1763 InsertText( stringToPaste, Text::Controller::COMMIT );
1764 mImpl->ChangeState( EventData::EDITING );
1765 mImpl->RequestRelayout();
1767 // Do this last since it provides callbacks into application code
1768 mImpl->mControlInterface.TextChanged();
1771 void Controller::PasteClipboardItemEvent()
1773 // Retrieve the clipboard contents first
1774 ClipboardEventNotifier notifier( ClipboardEventNotifier::Get() );
1775 std::string stringToPaste( notifier.GetContent() );
1777 // Commit the current pre-edit text; the contents of the clipboard should be appended
1778 mImpl->ResetImfManager();
1781 PasteText( stringToPaste );
1784 void Controller::TextPopupButtonTouched( Dali::Toolkit::TextSelectionPopup::Buttons button )
1786 if( NULL == mImpl->mEventData )
1793 case Toolkit::TextSelectionPopup::CUT:
1795 mImpl->SendSelectionToClipboard( true ); // Synchronous call to modify text
1796 mImpl->mOperationsPending = ALL_OPERATIONS;
1798 // This is to reset the virtual keyboard to Upper-case
1799 if( 0u == mImpl->mLogicalModel->mText.Count() )
1804 if( 0u != mImpl->mLogicalModel->mText.Count() ||
1805 !mImpl->IsPlaceholderAvailable() )
1807 mImpl->QueueModifyEvent( ModifyEvent::TEXT_DELETED );
1811 ShowPlaceholderText();
1812 mImpl->mEventData->mUpdateCursorPosition = true;
1814 mImpl->RequestRelayout();
1815 mImpl->mControlInterface.TextChanged();
1818 case Toolkit::TextSelectionPopup::COPY:
1820 mImpl->SendSelectionToClipboard( false ); // Text not modified
1821 mImpl->RequestRelayout(); // Handles, Selection Highlight, Popup
1824 case Toolkit::TextSelectionPopup::PASTE:
1826 std::string stringToPaste("");
1827 mImpl->GetTextFromClipboard( 0, stringToPaste ); // Paste latest item from system clipboard
1828 PasteText( stringToPaste );
1831 case Toolkit::TextSelectionPopup::SELECT:
1833 const Vector2& currentCursorPosition = mImpl->mEventData->mDecorator->GetPosition( PRIMARY_CURSOR );
1835 if( mImpl->mEventData->mSelectionEnabled )
1837 // Creates a SELECT event.
1838 SelectEvent( currentCursorPosition.x, currentCursorPosition.y, false );
1842 case Toolkit::TextSelectionPopup::SELECT_ALL:
1844 // Creates a SELECT_ALL event
1845 SelectEvent( 0.f, 0.f, true );
1848 case Toolkit::TextSelectionPopup::CLIPBOARD:
1850 mImpl->ShowClipboard();
1853 case Toolkit::TextSelectionPopup::NONE:
1861 ImfManager::ImfCallbackData Controller::OnImfEvent( ImfManager& imfManager, const ImfManager::ImfEventData& imfEvent )
1863 bool update = false;
1864 bool requestRelayout = false;
1867 unsigned int cursorPosition( 0 );
1869 switch ( imfEvent.eventName )
1871 case ImfManager::COMMIT:
1873 InsertText( imfEvent.predictiveString, Text::Controller::COMMIT );
1875 requestRelayout = true;
1878 case ImfManager::PREEDIT:
1880 InsertText( imfEvent.predictiveString, Text::Controller::PRE_EDIT );
1882 requestRelayout = true;
1885 case ImfManager::DELETESURROUNDING:
1887 update = RemoveText( imfEvent.cursorOffset, imfEvent.numberOfChars );
1891 if( 0u != mImpl->mLogicalModel->mText.Count() ||
1892 !mImpl->IsPlaceholderAvailable() )
1894 mImpl->QueueModifyEvent( ModifyEvent::TEXT_DELETED );
1898 ShowPlaceholderText();
1899 mImpl->mEventData->mUpdateCursorPosition = true;
1902 requestRelayout = true;
1905 case ImfManager::GETSURROUNDING:
1908 cursorPosition = GetLogicalCursorPosition();
1910 imfManager.SetSurroundingText( text );
1911 imfManager.SetCursorPosition( cursorPosition );
1914 case ImfManager::VOID:
1921 if( ImfManager::GETSURROUNDING != imfEvent.eventName )
1924 cursorPosition = GetLogicalCursorPosition();
1927 if( requestRelayout )
1929 mImpl->mOperationsPending = ALL_OPERATIONS;
1930 mImpl->RequestRelayout();
1932 // Do this last since it provides callbacks into application code
1933 mImpl->mControlInterface.TextChanged();
1936 ImfManager::ImfCallbackData callbackData( update, cursorPosition, text, false );
1938 return callbackData;
1941 Controller::~Controller()
1946 bool Controller::BackspaceKeyEvent()
1948 DALI_LOG_INFO( gLogFilter, Debug::Verbose, "Controller::KeyEvent %p DALI_KEY_BACKSPACE\n", this );
1950 // IMF manager is no longer handling key-events
1951 mImpl->ClearPreEditFlag();
1953 bool removed( false );
1955 if( EventData::SELECTING == mImpl->mEventData->mState )
1957 removed = RemoveSelectedText();
1959 else if( mImpl->mEventData->mPrimaryCursorPosition > 0 )
1961 // Remove the character before the current cursor position
1962 removed = RemoveText( -1, 1 );
1967 DALI_LOG_INFO( gLogFilter, Debug::Verbose, "Controller::KeyEvent %p DALI_KEY_BACKSPACE RemovedText\n", this );
1968 // Notifiy the IMF manager after text changed
1969 // Automatic Upper-case and restarting prediction on an existing word require this.
1972 if( 0u != mImpl->mLogicalModel->mText.Count() ||
1973 !mImpl->IsPlaceholderAvailable() )
1975 mImpl->QueueModifyEvent( ModifyEvent::TEXT_DELETED );
1979 ShowPlaceholderText();
1980 mImpl->mEventData->mUpdateCursorPosition = true;
1987 void Controller::NotifyImfManager()
1989 if( mImpl->mEventData )
1991 if( mImpl->mEventData->mImfManager )
1993 // Notifying IMF of a cursor change triggers a surrounding text request so updating it now.
1996 mImpl->mEventData->mImfManager.SetSurroundingText( text );
1998 mImpl->mEventData->mImfManager.SetCursorPosition( GetLogicalCursorPosition() );
1999 mImpl->mEventData->mImfManager.NotifyCursorPosition();
2004 void Controller::ShowPlaceholderText()
2006 if( mImpl->IsPlaceholderAvailable() )
2008 DALI_ASSERT_DEBUG( mImpl->mEventData && "No placeholder text available" );
2010 mImpl->mEventData->mIsShowingPlaceholderText = true;
2012 // Disable handles when showing place-holder text
2013 mImpl->mEventData->mDecorator->SetHandleActive( GRAB_HANDLE, false );
2014 mImpl->mEventData->mDecorator->SetHandleActive( LEFT_SELECTION_HANDLE, false );
2015 mImpl->mEventData->mDecorator->SetHandleActive( RIGHT_SELECTION_HANDLE, false );
2017 const char* text( NULL );
2020 // TODO - Switch placeholder text styles when changing state
2021 if( EventData::INACTIVE != mImpl->mEventData->mState &&
2022 0u != mImpl->mEventData->mPlaceholderTextActive.c_str() )
2024 text = mImpl->mEventData->mPlaceholderTextActive.c_str();
2025 size = mImpl->mEventData->mPlaceholderTextActive.size();
2029 text = mImpl->mEventData->mPlaceholderTextInactive.c_str();
2030 size = mImpl->mEventData->mPlaceholderTextInactive.size();
2033 // Reset model for showing placeholder.
2034 mImpl->mLogicalModel->mText.Clear();
2036 mImpl->mVisualModel->SetTextColor( mImpl->mEventData->mPlaceholderTextColor );
2038 // Convert text into UTF-32
2039 Vector<Character>& utf32Characters = mImpl->mLogicalModel->mText;
2040 utf32Characters.Resize( size );
2042 // This is a bit horrible but std::string returns a (signed) char*
2043 const uint8_t* utf8 = reinterpret_cast<const uint8_t*>( text );
2045 // Transform a text array encoded in utf8 into an array encoded in utf32.
2046 // It returns the actual number of characters.
2047 Length characterCount = Utf8ToUtf32( utf8, size, utf32Characters.Begin() );
2048 utf32Characters.Resize( characterCount );
2050 // Reset the cursor position
2051 mImpl->mEventData->mPrimaryCursorPosition = 0;
2053 // The natural size needs to be re-calculated.
2054 mImpl->mRecalculateNaturalSize = true;
2056 // Apply modifications to the model
2057 mImpl->mOperationsPending = ALL_OPERATIONS;
2059 // Update the rest of the model during size negotiation
2060 mImpl->QueueModifyEvent( ModifyEvent::TEXT_REPLACED );
2064 void Controller::ClearModelData()
2066 // n.b. This does not Clear the mText from mLogicalModel
2067 mImpl->mLogicalModel->mScriptRuns.Clear();
2068 mImpl->mLogicalModel->mFontRuns.Clear();
2069 mImpl->mLogicalModel->mLineBreakInfo.Clear();
2070 mImpl->mLogicalModel->mWordBreakInfo.Clear();
2071 mImpl->mLogicalModel->mBidirectionalParagraphInfo.Clear();
2072 mImpl->mLogicalModel->mCharacterDirections.Clear();
2073 mImpl->mLogicalModel->mBidirectionalLineInfo.Clear();
2074 mImpl->mLogicalModel->mLogicalToVisualMap.Clear();
2075 mImpl->mLogicalModel->mVisualToLogicalMap.Clear();
2076 mImpl->mVisualModel->mGlyphs.Clear();
2077 mImpl->mVisualModel->mGlyphsToCharacters.Clear();
2078 mImpl->mVisualModel->mCharactersToGlyph.Clear();
2079 mImpl->mVisualModel->mCharactersPerGlyph.Clear();
2080 mImpl->mVisualModel->mGlyphsPerCharacter.Clear();
2081 mImpl->mVisualModel->mGlyphPositions.Clear();
2082 mImpl->mVisualModel->mLines.Clear();
2083 mImpl->mVisualModel->ClearCaches();
2086 void Controller::ClearFontData()
2088 mImpl->mFontDefaults->mFontId = 0u; // Remove old font ID
2089 mImpl->mLogicalModel->mFontRuns.Clear();
2090 mImpl->mVisualModel->mGlyphs.Clear();
2091 mImpl->mVisualModel->mGlyphsToCharacters.Clear();
2092 mImpl->mVisualModel->mCharactersToGlyph.Clear();
2093 mImpl->mVisualModel->mCharactersPerGlyph.Clear();
2094 mImpl->mVisualModel->mGlyphsPerCharacter.Clear();
2095 mImpl->mVisualModel->mGlyphPositions.Clear();
2096 mImpl->mVisualModel->mLines.Clear();
2097 mImpl->mVisualModel->ClearCaches();
2100 Controller::Controller( ControlInterface& controlInterface )
2103 mImpl = new Controller::Impl( controlInterface );
2108 } // namespace Toolkit