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/text-controller-impl.h>
36 #if defined(DEBUG_ENABLED)
37 Debug::Filter* gLogFilter = Debug::Filter::New(Debug::NoLogging, true, "LOG_TEXT_CONTROLS");
40 const float MAX_FLOAT = std::numeric_limits<float>::max();
41 const unsigned int POINTS_PER_INCH = 72;
43 const std::string EMPTY_STRING("");
44 const unsigned int ZERO = 0u;
46 float ConvertToEven( float value )
48 int intValue(static_cast<int>( value ));
49 return static_cast<float>(intValue % 2 == 0) ? intValue : (intValue + 1);
63 ControllerPtr Controller::New( ControlInterface& controlInterface )
65 return ControllerPtr( new Controller( controlInterface ) );
68 void Controller::EnableTextInput( DecoratorPtr decorator )
70 if( !mImpl->mEventData )
72 mImpl->mEventData = new EventData( decorator );
76 void Controller::SetText( const std::string& text )
78 DALI_LOG_INFO( gLogFilter, Debug::Verbose, "Controller::SetText\n" );
80 // Reset keyboard as text changed
81 mImpl->ResetImfManager();
83 // Remove the previously set text
86 CharacterIndex lastCursorIndex = 0u;
88 if( mImpl->mEventData )
90 // If popup shown then hide it by switching to Editing state
91 if( ( EventData::SELECTING == mImpl->mEventData->mState ) ||
92 ( EventData::EDITING_WITH_POPUP == mImpl->mEventData->mState ) ||
93 ( EventData::EDITING_WITH_GRAB_HANDLE == mImpl->mEventData->mState ) ||
94 ( EventData::EDITING_WITH_PASTE_POPUP == mImpl->mEventData->mState ) )
96 mImpl->ChangeState( EventData::EDITING );
102 // Convert text into UTF-32
103 Vector<Character>& utf32Characters = mImpl->mLogicalModel->mText;
104 utf32Characters.Resize( text.size() );
106 // This is a bit horrible but std::string returns a (signed) char*
107 const uint8_t* utf8 = reinterpret_cast<const uint8_t*>( text.c_str() );
109 // Transform a text array encoded in utf8 into an array encoded in utf32.
110 // It returns the actual number of characters.
111 Length characterCount = Utf8ToUtf32( utf8, text.size(), utf32Characters.Begin() );
112 utf32Characters.Resize( characterCount );
114 DALI_ASSERT_DEBUG( text.size() >= characterCount && "Invalid UTF32 conversion length" );
115 DALI_LOG_INFO( gLogFilter, Debug::Verbose, "Controller::SetText %p UTF8 size %d, UTF32 size %d\n", this, text.size(), mImpl->mLogicalModel->mText.Count() );
117 // To reset the cursor position
118 lastCursorIndex = characterCount;
120 // Update the rest of the model during size negotiation
121 mImpl->QueueModifyEvent( ModifyEvent::TEXT_REPLACED );
123 // The natural size needs to be re-calculated.
124 mImpl->mRecalculateNaturalSize = true;
126 // Apply modifications to the model
127 mImpl->mOperationsPending = ALL_OPERATIONS;
131 ShowPlaceholderText();
134 // Resets the cursor position.
135 ResetCursorPosition( lastCursorIndex );
137 // Scrolls the text to make the cursor visible.
138 ResetScrollPosition();
140 mImpl->RequestRelayout();
142 if( mImpl->mEventData )
144 // Cancel previously queued events
145 mImpl->mEventData->mEventQueue.clear();
148 // Notify IMF as text changed
151 // Do this last since it provides callbacks into application code
152 mImpl->mControlInterface.TextChanged();
155 void Controller::GetText( std::string& text ) const
157 if( ! mImpl->IsShowingPlaceholderText() )
159 Vector<Character>& utf32Characters = mImpl->mLogicalModel->mText;
161 if( 0u != utf32Characters.Count() )
163 Utf32ToUtf8( &utf32Characters[0], utf32Characters.Count(), text );
168 DALI_LOG_INFO( gLogFilter, Debug::Verbose, "Controller::GetText %p empty (but showing placeholder)\n", this );
172 unsigned int Controller::GetLogicalCursorPosition() const
174 if( mImpl->mEventData )
176 return mImpl->mEventData->mPrimaryCursorPosition;
182 void Controller::SetPlaceholderText( PlaceholderType type, const std::string& text )
184 if( mImpl->mEventData )
186 if( PLACEHOLDER_TYPE_INACTIVE == type )
188 mImpl->mEventData->mPlaceholderTextInactive = text;
192 mImpl->mEventData->mPlaceholderTextActive = text;
195 // Update placeholder if there is no text
196 if( mImpl->IsShowingPlaceholderText() ||
197 0u == mImpl->mLogicalModel->mText.Count() )
199 ShowPlaceholderText();
204 void Controller::GetPlaceholderText( PlaceholderType type, std::string& text ) const
206 if( mImpl->mEventData )
208 if( PLACEHOLDER_TYPE_INACTIVE == type )
210 text = mImpl->mEventData->mPlaceholderTextInactive;
214 text = mImpl->mEventData->mPlaceholderTextActive;
219 void Controller::SetMaximumNumberOfCharacters( int maxCharacters )
221 if ( maxCharacters >= 0 )
223 mImpl->mMaximumNumberOfCharacters = maxCharacters;
227 int Controller::GetMaximumNumberOfCharacters()
229 return mImpl->mMaximumNumberOfCharacters;
232 void Controller::SetDefaultFontFamily( const std::string& defaultFontFamily )
234 if( !mImpl->mFontDefaults )
236 mImpl->mFontDefaults = new FontDefaults();
239 mImpl->mFontDefaults->mFontDescription.family = defaultFontFamily;
240 DALI_LOG_INFO( gLogFilter, Debug::General, "Controller::SetDefaultFontFamily %s\n", defaultFontFamily.c_str());
241 mImpl->mUserDefinedFontFamily = true;
243 // Clear the font-specific data
246 mImpl->mOperationsPending = ALL_OPERATIONS;
247 mImpl->mRecalculateNaturalSize = true;
249 mImpl->RequestRelayout();
252 const std::string& Controller::GetDefaultFontFamily() const
254 if( mImpl->mFontDefaults )
256 return mImpl->mFontDefaults->mFontDescription.family;
262 void Controller::SetDefaultFontStyle( const std::string& style )
264 if( !mImpl->mFontDefaults )
266 mImpl->mFontDefaults = new FontDefaults();
269 mImpl->mFontDefaults->mFontStyle = style;
272 const std::string& Controller::GetDefaultFontStyle() const
274 if( mImpl->mFontDefaults )
276 return mImpl->mFontDefaults->mFontStyle;
282 void Controller::SetDefaultFontWidth( FontWidth width )
284 if( !mImpl->mFontDefaults )
286 mImpl->mFontDefaults = new FontDefaults();
289 mImpl->mFontDefaults->mFontDescription.width = width;
291 // Clear the font-specific data
294 mImpl->mOperationsPending = ALL_OPERATIONS;
295 mImpl->mRecalculateNaturalSize = true;
297 mImpl->RequestRelayout();
300 FontWidth Controller::GetDefaultFontWidth() const
302 if( mImpl->mFontDefaults )
304 return mImpl->mFontDefaults->mFontDescription.width;
307 return TextAbstraction::FontWidth::NORMAL;
310 void Controller::SetDefaultFontWeight( FontWeight weight )
312 if( !mImpl->mFontDefaults )
314 mImpl->mFontDefaults = new FontDefaults();
317 mImpl->mFontDefaults->mFontDescription.weight = weight;
319 // Clear the font-specific data
322 mImpl->mOperationsPending = ALL_OPERATIONS;
323 mImpl->mRecalculateNaturalSize = true;
325 mImpl->RequestRelayout();
328 FontWeight Controller::GetDefaultFontWeight() const
330 if( mImpl->mFontDefaults )
332 return mImpl->mFontDefaults->mFontDescription.weight;
335 return TextAbstraction::FontWeight::NORMAL;
338 void Controller::SetDefaultFontSlant( FontSlant slant )
340 if( !mImpl->mFontDefaults )
342 mImpl->mFontDefaults = new FontDefaults();
345 mImpl->mFontDefaults->mFontDescription.slant = slant;
347 // Clear the font-specific data
350 mImpl->mOperationsPending = ALL_OPERATIONS;
351 mImpl->mRecalculateNaturalSize = true;
353 mImpl->RequestRelayout();
356 FontSlant Controller::GetDefaultFontSlant() const
358 if( mImpl->mFontDefaults )
360 return mImpl->mFontDefaults->mFontDescription.slant;
363 return TextAbstraction::FontSlant::NORMAL;
366 void Controller::SetDefaultPointSize( float pointSize )
368 if( !mImpl->mFontDefaults )
370 mImpl->mFontDefaults = new FontDefaults();
373 mImpl->mFontDefaults->mDefaultPointSize = pointSize;
375 unsigned int horizontalDpi( 0u );
376 unsigned int verticalDpi( 0u );
377 mImpl->mFontClient.GetDpi( horizontalDpi, verticalDpi );
379 // Adjust the metrics if the fixed-size font should be down-scaled
380 int maxEmojiSize( pointSize/POINTS_PER_INCH * verticalDpi );
381 DALI_LOG_INFO( gLogFilter, Debug::General, "Controller::SetDefaultPointSize %p setting MaxEmojiSize %d\n", this, maxEmojiSize );
382 mImpl->mMetrics->SetMaxEmojiSize( maxEmojiSize );
384 // Clear the font-specific data
387 mImpl->mOperationsPending = ALL_OPERATIONS;
388 mImpl->mRecalculateNaturalSize = true;
390 mImpl->RequestRelayout();
393 float Controller::GetDefaultPointSize() const
395 if( mImpl->mFontDefaults )
397 return mImpl->mFontDefaults->mDefaultPointSize;
403 void Controller::UpdateAfterFontChange( std::string& newDefaultFont )
405 DALI_LOG_INFO( gLogFilter, Debug::Concise, "Controller::UpdateAfterFontChange");
407 if ( !mImpl->mUserDefinedFontFamily ) // If user defined font then should not update when system font changes
409 DALI_LOG_INFO( gLogFilter, Debug::Concise, "Controller::UpdateAfterFontChange newDefaultFont(%s)\n", newDefaultFont.c_str() );
411 mImpl->mFontDefaults->mFontDescription.family = newDefaultFont;
412 mImpl->UpdateModel( ALL_OPERATIONS );
413 mImpl->QueueModifyEvent( ModifyEvent::TEXT_REPLACED );
414 mImpl->mRecalculateNaturalSize = true;
415 mImpl->RequestRelayout();
419 void Controller::SetTextColor( const Vector4& textColor )
421 mImpl->mTextColor = textColor;
423 if( !mImpl->IsShowingPlaceholderText() )
425 mImpl->mVisualModel->SetTextColor( textColor );
427 mImpl->RequestRelayout();
431 const Vector4& Controller::GetTextColor() const
433 return mImpl->mTextColor;
436 bool Controller::RemoveText( int cursorOffset, int numberOfChars )
438 bool removed( false );
440 DALI_LOG_INFO( gLogFilter, Debug::General, "Controller::RemoveText %p mText.Count() %d cursor %d cursorOffset %d numberOfChars %d\n",
441 this, mImpl->mLogicalModel->mText.Count(), mImpl->mEventData->mPrimaryCursorPosition, cursorOffset, numberOfChars );
443 if( !mImpl->IsShowingPlaceholderText() )
445 // Delete at current cursor position
446 Vector<Character>& currentText = mImpl->mLogicalModel->mText;
447 CharacterIndex& oldCursorIndex = mImpl->mEventData->mPrimaryCursorPosition;
449 CharacterIndex cursorIndex = oldCursorIndex;
451 // Validate the cursor position & number of characters
452 if( static_cast< CharacterIndex >( std::abs( cursorOffset ) ) <= cursorIndex )
454 cursorIndex = oldCursorIndex + cursorOffset;
457 if( ( cursorIndex + numberOfChars ) > currentText.Count() )
459 numberOfChars = currentText.Count() - cursorIndex;
462 if( ( cursorIndex + numberOfChars ) <= currentText.Count() )
464 Vector<Character>::Iterator first = currentText.Begin() + cursorIndex;
465 Vector<Character>::Iterator last = first + numberOfChars;
467 currentText.Erase( first, last );
469 // Cursor position retreat
470 oldCursorIndex = cursorIndex;
472 DALI_LOG_INFO( gLogFilter, Debug::General, "Controller::RemoveText %p removed %d\n", this, numberOfChars );
480 void Controller::SetPlaceholderTextColor( const Vector4& textColor )
482 if( mImpl->mEventData )
484 mImpl->mEventData->mPlaceholderTextColor = textColor;
487 if( mImpl->IsShowingPlaceholderText() )
489 mImpl->mVisualModel->SetTextColor( textColor );
490 mImpl->RequestRelayout();
494 const Vector4& Controller::GetPlaceholderTextColor() const
496 if( mImpl->mEventData )
498 return mImpl->mEventData->mPlaceholderTextColor;
504 void Controller::SetShadowOffset( const Vector2& shadowOffset )
506 mImpl->mVisualModel->SetShadowOffset( shadowOffset );
508 mImpl->RequestRelayout();
511 const Vector2& Controller::GetShadowOffset() const
513 return mImpl->mVisualModel->GetShadowOffset();
516 void Controller::SetShadowColor( const Vector4& shadowColor )
518 mImpl->mVisualModel->SetShadowColor( shadowColor );
520 mImpl->RequestRelayout();
523 const Vector4& Controller::GetShadowColor() const
525 return mImpl->mVisualModel->GetShadowColor();
528 void Controller::SetUnderlineColor( const Vector4& color )
530 mImpl->mVisualModel->SetUnderlineColor( color );
532 mImpl->RequestRelayout();
535 const Vector4& Controller::GetUnderlineColor() const
537 return mImpl->mVisualModel->GetUnderlineColor();
540 void Controller::SetUnderlineEnabled( bool enabled )
542 mImpl->mVisualModel->SetUnderlineEnabled( enabled );
544 mImpl->RequestRelayout();
547 bool Controller::IsUnderlineEnabled() const
549 return mImpl->mVisualModel->IsUnderlineEnabled();
552 void Controller::SetUnderlineHeight( float height )
554 mImpl->mVisualModel->SetUnderlineHeight( height );
556 mImpl->RequestRelayout();
559 float Controller::GetUnderlineHeight() const
561 return mImpl->mVisualModel->GetUnderlineHeight();
564 void Controller::SetEnableCursorBlink( bool enable )
566 DALI_ASSERT_DEBUG( NULL != mImpl->mEventData && "TextInput disabled" );
568 if( mImpl->mEventData )
570 mImpl->mEventData->mCursorBlinkEnabled = enable;
573 mImpl->mEventData->mDecorator )
575 mImpl->mEventData->mDecorator->StopCursorBlink();
580 bool Controller::GetEnableCursorBlink() const
582 if( mImpl->mEventData )
584 return mImpl->mEventData->mCursorBlinkEnabled;
590 const Vector2& Controller::GetScrollPosition() const
592 if( mImpl->mEventData )
594 return mImpl->mEventData->mScrollPosition;
597 return Vector2::ZERO;
600 const Vector2& Controller::GetAlignmentOffset() const
602 return mImpl->mAlignmentOffset;
605 Vector3 Controller::GetNaturalSize()
607 DALI_LOG_INFO( gLogFilter, Debug::Verbose, "-->Controller::GetNaturalSize\n" );
610 // Make sure the model is up-to-date before layouting
611 ProcessModifyEvents();
613 if( mImpl->mRecalculateNaturalSize )
615 // Operations that can be done only once until the text changes.
616 const OperationsMask onlyOnceOperations = static_cast<OperationsMask>( CONVERT_TO_UTF32 |
624 // Make sure the model is up-to-date before layouting
625 mImpl->UpdateModel( onlyOnceOperations );
627 // Operations that need to be done if the size changes.
628 const OperationsMask sizeOperations = static_cast<OperationsMask>( LAYOUT |
632 DoRelayout( Size( MAX_FLOAT, MAX_FLOAT ),
633 static_cast<OperationsMask>( onlyOnceOperations |
635 naturalSize.GetVectorXY() );
637 // Do not do again the only once operations.
638 mImpl->mOperationsPending = static_cast<OperationsMask>( mImpl->mOperationsPending & ~onlyOnceOperations );
640 // Do the size related operations again.
641 mImpl->mOperationsPending = static_cast<OperationsMask>( mImpl->mOperationsPending | sizeOperations );
643 // Stores the natural size to avoid recalculate it again
644 // unless the text/style changes.
645 mImpl->mVisualModel->SetNaturalSize( naturalSize.GetVectorXY() );
647 mImpl->mRecalculateNaturalSize = false;
649 DALI_LOG_INFO( gLogFilter, Debug::Verbose, "<--Controller::GetNaturalSize calculated %f,%f,%f\n", naturalSize.x, naturalSize.y, naturalSize.z );
653 naturalSize = mImpl->mVisualModel->GetNaturalSize();
655 DALI_LOG_INFO( gLogFilter, Debug::Verbose, "<--Controller::GetNaturalSize cached %f,%f,%f\n", naturalSize.x, naturalSize.y, naturalSize.z );
658 naturalSize.x = ConvertToEven( naturalSize.x );
659 naturalSize.y = ConvertToEven( naturalSize.y );
664 float Controller::GetHeightForWidth( float width )
666 DALI_LOG_INFO( gLogFilter, Debug::Verbose, "-->Controller::GetHeightForWidth %p width %f\n", this, width );
667 // Make sure the model is up-to-date before layouting
668 ProcessModifyEvents();
671 if( fabsf( width - mImpl->mVisualModel->mControlSize.width ) > Math::MACHINE_EPSILON_1000 )
673 // Operations that can be done only once until the text changes.
674 const OperationsMask onlyOnceOperations = static_cast<OperationsMask>( CONVERT_TO_UTF32 |
682 // Make sure the model is up-to-date before layouting
683 mImpl->UpdateModel( onlyOnceOperations );
685 // Operations that need to be done if the size changes.
686 const OperationsMask sizeOperations = static_cast<OperationsMask>( LAYOUT |
690 DoRelayout( Size( width, MAX_FLOAT ),
691 static_cast<OperationsMask>( onlyOnceOperations |
695 // Do not do again the only once operations.
696 mImpl->mOperationsPending = static_cast<OperationsMask>( mImpl->mOperationsPending & ~onlyOnceOperations );
698 // Do the size related operations again.
699 mImpl->mOperationsPending = static_cast<OperationsMask>( mImpl->mOperationsPending | sizeOperations );
700 DALI_LOG_INFO( gLogFilter, Debug::Verbose, "<--Controller::GetHeightForWidth calculated %f\n", layoutSize.height );
704 layoutSize = mImpl->mVisualModel->GetActualSize();
705 DALI_LOG_INFO( gLogFilter, Debug::Verbose, "<--Controller::GetHeightForWidth cached %f\n", layoutSize.height );
708 return layoutSize.height;
711 bool Controller::Relayout( const Size& size )
713 DALI_LOG_INFO( gLogFilter, Debug::Verbose, "-->Controller::Relayout %p size %f,%f\n", this, size.width, size.height );
715 if( ( size.width < Math::MACHINE_EPSILON_1000 ) || ( size.height < Math::MACHINE_EPSILON_1000 ) )
717 bool glyphsRemoved( false );
718 if( 0u != mImpl->mVisualModel->mGlyphPositions.Count() )
720 mImpl->mVisualModel->mGlyphPositions.Clear();
721 glyphsRemoved = true;
723 // Not worth to relayout if width or height is equal to zero.
724 DALI_LOG_INFO( gLogFilter, Debug::Verbose, "<--Controller::Relayout (skipped)\n" );
725 return glyphsRemoved;
728 const bool newSize = ( size != mImpl->mVisualModel->mControlSize );
732 DALI_LOG_INFO( gLogFilter, Debug::Verbose, "new size (previous size %f,%f)\n", mImpl->mVisualModel->mControlSize.width, mImpl->mVisualModel->mControlSize.height );
734 // Operations that need to be done if the size changes.
735 mImpl->mOperationsPending = static_cast<OperationsMask>( mImpl->mOperationsPending |
741 mImpl->mVisualModel->mControlSize = size;
744 // Make sure the model is up-to-date before layouting
745 ProcessModifyEvents();
746 mImpl->UpdateModel( mImpl->mOperationsPending );
749 bool updated = DoRelayout( mImpl->mVisualModel->mControlSize,
750 mImpl->mOperationsPending,
753 // Do not re-do any operation until something changes.
754 mImpl->mOperationsPending = NO_OPERATION;
756 // Keep the current offset and alignment as it will be used to update the decorator's positions (if the size changes).
758 if( newSize && mImpl->mEventData )
760 offset = mImpl->mAlignmentOffset + mImpl->mEventData->mScrollPosition;
763 // After doing the text layout, the alignment offset to place the actor in the desired position can be calculated.
764 CalculateTextAlignment( size );
766 if( mImpl->mEventData )
770 // If there is a new size, the scroll position needs to be clamped.
771 mImpl->ClampHorizontalScroll( layoutSize );
773 // Update the decorator's positions is needed if there is a new size.
774 mImpl->mEventData->mDecorator->UpdatePositions( mImpl->mAlignmentOffset + mImpl->mEventData->mScrollPosition - offset );
777 // Move the cursor, grab handle etc.
778 updated = mImpl->ProcessInputEvents() || updated;
781 DALI_LOG_INFO( gLogFilter, Debug::Verbose, "<--Controller::Relayout\n" );
785 void Controller::ProcessModifyEvents()
787 std::vector<ModifyEvent>& events = mImpl->mModifyEvents;
789 for( unsigned int i=0; i<events.size(); ++i )
791 if( ModifyEvent::TEXT_REPLACED == events[i].type )
793 // A (single) replace event should come first, otherwise we wasted time processing NOOP events
794 DALI_ASSERT_DEBUG( 0 == i && "Unexpected TEXT_REPLACED event" );
798 else if( ModifyEvent::TEXT_INSERTED == events[i].type )
802 else if( ModifyEvent::TEXT_DELETED == events[i].type )
804 // Placeholder-text cannot be deleted
805 if( !mImpl->IsShowingPlaceholderText() )
812 if( mImpl->mEventData &&
815 // When the text is being modified, delay cursor blinking
816 mImpl->mEventData->mDecorator->DelayCursorBlink();
819 // Discard temporary text
823 void Controller::ResetText()
826 mImpl->mLogicalModel->mText.Clear();
829 // We have cleared everything including the placeholder-text
830 mImpl->PlaceholderCleared();
832 // The natural size needs to be re-calculated.
833 mImpl->mRecalculateNaturalSize = true;
835 // Apply modifications to the model
836 mImpl->mOperationsPending = ALL_OPERATIONS;
839 void Controller::ResetCursorPosition( CharacterIndex cursorIndex )
841 // Reset the cursor position
842 if( NULL != mImpl->mEventData )
844 mImpl->mEventData->mPrimaryCursorPosition = cursorIndex;
846 // Update the cursor if it's in editing mode.
847 if ( EventData::IsEditingState( mImpl->mEventData->mState ) )
849 mImpl->mEventData->mUpdateCursorPosition = true;
854 void Controller::ResetScrollPosition()
856 if( NULL != mImpl->mEventData )
858 // Reset the scroll position.
859 mImpl->mEventData->mScrollPosition = Vector2::ZERO;
860 mImpl->mEventData->mScrollAfterUpdatePosition = true;
864 void Controller::TextReplacedEvent()
869 // The natural size needs to be re-calculated.
870 mImpl->mRecalculateNaturalSize = true;
872 // Apply modifications to the model
873 mImpl->mOperationsPending = ALL_OPERATIONS;
874 mImpl->UpdateModel( ALL_OPERATIONS );
875 mImpl->mOperationsPending = static_cast<OperationsMask>( LAYOUT |
881 void Controller::TextInsertedEvent()
883 DALI_ASSERT_DEBUG( NULL != mImpl->mEventData && "Unexpected TextInsertedEvent" );
885 // TODO - Optimize this
888 // The natural size needs to be re-calculated.
889 mImpl->mRecalculateNaturalSize = true;
891 // Apply modifications to the model; TODO - Optimize this
892 mImpl->mOperationsPending = ALL_OPERATIONS;
893 mImpl->UpdateModel( ALL_OPERATIONS );
894 mImpl->mOperationsPending = static_cast<OperationsMask>( LAYOUT |
899 // Queue a cursor reposition event; this must wait until after DoRelayout()
900 if ( EventData::IsEditingState( mImpl->mEventData->mState ) )
902 mImpl->mEventData->mUpdateCursorPosition = true;
903 mImpl->mEventData->mScrollAfterUpdatePosition = true;
907 void Controller::TextDeletedEvent()
909 DALI_ASSERT_DEBUG( NULL != mImpl->mEventData && "Unexpected TextDeletedEvent" );
911 // TODO - Optimize this
914 // The natural size needs to be re-calculated.
915 mImpl->mRecalculateNaturalSize = true;
917 // Apply modifications to the model; TODO - Optimize this
918 mImpl->mOperationsPending = ALL_OPERATIONS;
919 mImpl->UpdateModel( ALL_OPERATIONS );
920 mImpl->mOperationsPending = static_cast<OperationsMask>( LAYOUT |
925 // Queue a cursor reposition event; this must wait until after DoRelayout()
926 mImpl->mEventData->mUpdateCursorPosition = true;
927 if( 0u != mImpl->mLogicalModel->mText.Count() )
929 mImpl->mEventData->mScrollAfterDelete = true;
933 bool Controller::DoRelayout( const Size& size,
934 OperationsMask operationsRequired,
937 DALI_LOG_INFO( gLogFilter, Debug::Verbose, "-->Controller::DoRelayout %p size %f,%f\n", this, size.width, size.height );
938 bool viewUpdated( false );
940 // Calculate the operations to be done.
941 const OperationsMask operations = static_cast<OperationsMask>( mImpl->mOperationsPending & operationsRequired );
943 if( LAYOUT & operations )
945 // Some vectors with data needed to layout and reorder may be void
946 // after the first time the text has been laid out.
947 // Fill the vectors again.
949 const Length numberOfGlyphs = mImpl->mVisualModel->mGlyphs.Count();
951 if( 0u == numberOfGlyphs )
953 // Nothing else to do if there is no glyphs.
954 DALI_LOG_INFO( gLogFilter, Debug::Verbose, "<--Controller::DoRelayout no glyphs, view updated true\n" );
958 const Vector<LineBreakInfo>& lineBreakInfo = mImpl->mLogicalModel->mLineBreakInfo;
959 const Vector<WordBreakInfo>& wordBreakInfo = mImpl->mLogicalModel->mWordBreakInfo;
960 const Vector<CharacterDirection>& characterDirection = mImpl->mLogicalModel->mCharacterDirections;
961 const Vector<GlyphInfo>& glyphs = mImpl->mVisualModel->mGlyphs;
962 const Vector<CharacterIndex>& glyphsToCharactersMap = mImpl->mVisualModel->mGlyphsToCharacters;
963 const Vector<Length>& charactersPerGlyph = mImpl->mVisualModel->mCharactersPerGlyph;
964 const Character* const textBuffer = mImpl->mLogicalModel->mText.Begin();
966 // Set the layout parameters.
967 LayoutParameters layoutParameters( size,
969 lineBreakInfo.Begin(),
970 wordBreakInfo.Begin(),
971 ( 0u != characterDirection.Count() ) ? characterDirection.Begin() : NULL,
974 glyphsToCharactersMap.Begin(),
975 charactersPerGlyph.Begin() );
977 // The laid-out lines.
978 // It's not possible to know in how many lines the text is going to be laid-out,
979 // but it can be resized at least with the number of 'paragraphs' to avoid
980 // some re-allocations.
981 Vector<LineRun>& lines = mImpl->mVisualModel->mLines;
983 // Delete any previous laid out lines before setting the new ones.
986 // The capacity of the bidirectional paragraph info is the number of paragraphs.
987 lines.Reserve( mImpl->mLogicalModel->mBidirectionalParagraphInfo.Capacity() );
989 // Resize the vector of positions to have the same size than the vector of glyphs.
990 Vector<Vector2>& glyphPositions = mImpl->mVisualModel->mGlyphPositions;
991 glyphPositions.Resize( numberOfGlyphs );
993 // Whether the last character is a new paragraph character.
994 layoutParameters.isLastNewParagraph = TextAbstraction::IsNewParagraph( *( textBuffer + ( mImpl->mLogicalModel->mText.Count() - 1u ) ) );
996 // Update the visual model.
997 viewUpdated = mImpl->mLayoutEngine.LayoutText( layoutParameters,
1004 // Reorder the lines
1005 if( REORDER & operations )
1007 Vector<BidirectionalParagraphInfoRun>& bidirectionalInfo = mImpl->mLogicalModel->mBidirectionalParagraphInfo;
1009 // Check first if there are paragraphs with bidirectional info.
1010 if( 0u != bidirectionalInfo.Count() )
1013 const Length numberOfLines = mImpl->mVisualModel->mLines.Count();
1015 // Reorder the lines.
1016 Vector<BidirectionalLineInfoRun> lineBidirectionalInfoRuns;
1017 lineBidirectionalInfoRuns.Reserve( numberOfLines ); // Reserve because is not known yet how many lines have right to left characters.
1018 ReorderLines( bidirectionalInfo,
1020 lineBidirectionalInfoRuns );
1022 // Set the bidirectional info into the model.
1023 const Length numberOfBidirectionalInfoRuns = lineBidirectionalInfoRuns.Count();
1024 mImpl->mLogicalModel->SetVisualToLogicalMap( lineBidirectionalInfoRuns.Begin(),
1025 numberOfBidirectionalInfoRuns );
1027 // Set the bidirectional info per line into the layout parameters.
1028 layoutParameters.lineBidirectionalInfoRunsBuffer = lineBidirectionalInfoRuns.Begin();
1029 layoutParameters.numberOfBidirectionalInfoRuns = numberOfBidirectionalInfoRuns;
1031 // Get the character to glyph conversion table and set into the layout.
1032 layoutParameters.charactersToGlyphsBuffer = mImpl->mVisualModel->mCharactersToGlyph.Begin();
1034 // Get the glyphs per character table and set into the layout.
1035 layoutParameters.glyphsPerCharacterBuffer = mImpl->mVisualModel->mGlyphsPerCharacter.Begin();
1037 // Re-layout the text. Reorder those lines with right to left characters.
1038 mImpl->mLayoutEngine.ReLayoutRightToLeftLines( layoutParameters,
1041 // Free the allocated memory used to store the conversion table in the bidirectional line info run.
1042 for( Vector<BidirectionalLineInfoRun>::Iterator it = lineBidirectionalInfoRuns.Begin(),
1043 endIt = lineBidirectionalInfoRuns.End();
1047 BidirectionalLineInfoRun& bidiLineInfo = *it;
1049 free( bidiLineInfo.visualToLogicalMap );
1054 // Sets the actual size.
1055 if( UPDATE_ACTUAL_SIZE & operations )
1057 mImpl->mVisualModel->SetActualSize( layoutSize );
1063 layoutSize = mImpl->mVisualModel->GetActualSize();
1066 if( ALIGN & operations )
1068 // The laid-out lines.
1069 Vector<LineRun>& lines = mImpl->mVisualModel->mLines;
1071 mImpl->mLayoutEngine.Align( layoutSize,
1077 DALI_LOG_INFO( gLogFilter, Debug::Verbose, "<--Controller::DoRelayout, view updated %s\n", ( viewUpdated ? "true" : "false" ) );
1081 void Controller::SetMultiLineEnabled( bool enable )
1083 const LayoutEngine::Layout layout = enable ? LayoutEngine::MULTI_LINE_BOX : LayoutEngine::SINGLE_LINE_BOX;
1085 if( layout != mImpl->mLayoutEngine.GetLayout() )
1087 // Set the layout type.
1088 mImpl->mLayoutEngine.SetLayout( layout );
1090 // Set the flags to redo the layout operations
1091 const OperationsMask layoutOperations = static_cast<OperationsMask>( LAYOUT |
1092 UPDATE_ACTUAL_SIZE |
1096 mImpl->mOperationsPending = static_cast<OperationsMask>( mImpl->mOperationsPending | layoutOperations );
1098 mImpl->RequestRelayout();
1102 bool Controller::IsMultiLineEnabled() const
1104 return LayoutEngine::MULTI_LINE_BOX == mImpl->mLayoutEngine.GetLayout();
1107 void Controller::SetHorizontalAlignment( LayoutEngine::HorizontalAlignment alignment )
1109 if( alignment != mImpl->mLayoutEngine.GetHorizontalAlignment() )
1111 // Set the alignment.
1112 mImpl->mLayoutEngine.SetHorizontalAlignment( alignment );
1114 // Set the flag to redo the alignment operation.
1115 mImpl->mOperationsPending = static_cast<OperationsMask>( mImpl->mOperationsPending | ALIGN );
1117 mImpl->RequestRelayout();
1121 LayoutEngine::HorizontalAlignment Controller::GetHorizontalAlignment() const
1123 return mImpl->mLayoutEngine.GetHorizontalAlignment();
1126 void Controller::SetVerticalAlignment( LayoutEngine::VerticalAlignment alignment )
1128 if( alignment != mImpl->mLayoutEngine.GetVerticalAlignment() )
1130 // Set the alignment.
1131 mImpl->mLayoutEngine.SetVerticalAlignment( alignment );
1133 mImpl->mOperationsPending = static_cast<OperationsMask>( mImpl->mOperationsPending | ALIGN );
1135 mImpl->RequestRelayout();
1139 LayoutEngine::VerticalAlignment Controller::GetVerticalAlignment() const
1141 return mImpl->mLayoutEngine.GetVerticalAlignment();
1144 void Controller::CalculateTextAlignment( const Size& size )
1146 // Get the direction of the first character.
1147 const CharacterDirection firstParagraphDirection = mImpl->mLogicalModel->GetCharacterDirection( 0u );
1149 Size actualSize = mImpl->mVisualModel->GetActualSize();
1150 if( fabsf( actualSize.height ) < Math::MACHINE_EPSILON_1000 )
1152 // Get the line height of the default font.
1153 actualSize.height = mImpl->GetDefaultFontLineHeight();
1156 // If the first paragraph is right to left swap ALIGN_BEGIN and ALIGN_END;
1157 LayoutEngine::HorizontalAlignment horizontalAlignment = mImpl->mLayoutEngine.GetHorizontalAlignment();
1158 if( firstParagraphDirection &&
1159 ( LayoutEngine::HORIZONTAL_ALIGN_CENTER != horizontalAlignment ) )
1161 if( LayoutEngine::HORIZONTAL_ALIGN_BEGIN == horizontalAlignment )
1163 horizontalAlignment = LayoutEngine::HORIZONTAL_ALIGN_END;
1167 horizontalAlignment = LayoutEngine::HORIZONTAL_ALIGN_BEGIN;
1171 switch( horizontalAlignment )
1173 case LayoutEngine::HORIZONTAL_ALIGN_BEGIN:
1175 mImpl->mAlignmentOffset.x = 0.f;
1178 case LayoutEngine::HORIZONTAL_ALIGN_CENTER:
1180 mImpl->mAlignmentOffset.x = floorf( 0.5f * ( size.width - actualSize.width ) ); // try to avoid pixel alignment.
1183 case LayoutEngine::HORIZONTAL_ALIGN_END:
1185 mImpl->mAlignmentOffset.x = size.width - actualSize.width;
1190 const LayoutEngine::VerticalAlignment verticalAlignment = mImpl->mLayoutEngine.GetVerticalAlignment();
1191 switch( verticalAlignment )
1193 case LayoutEngine::VERTICAL_ALIGN_TOP:
1195 mImpl->mAlignmentOffset.y = 0.f;
1198 case LayoutEngine::VERTICAL_ALIGN_CENTER:
1200 mImpl->mAlignmentOffset.y = floorf( 0.5f * ( size.height - actualSize.height ) ); // try to avoid pixel alignment.
1203 case LayoutEngine::VERTICAL_ALIGN_BOTTOM:
1205 mImpl->mAlignmentOffset.y = size.height - actualSize.height;
1211 LayoutEngine& Controller::GetLayoutEngine()
1213 return mImpl->mLayoutEngine;
1216 View& Controller::GetView()
1218 return mImpl->mView;
1221 void Controller::KeyboardFocusGainEvent()
1223 DALI_ASSERT_DEBUG( mImpl->mEventData && "Unexpected KeyboardFocusGainEvent" );
1225 if( mImpl->mEventData )
1227 if( ( EventData::INACTIVE == mImpl->mEventData->mState ) ||
1228 ( EventData::INTERRUPTED == mImpl->mEventData->mState ) )
1230 mImpl->ChangeState( EventData::EDITING );
1231 mImpl->mEventData->mUpdateCursorPosition = true; //If editing started without tap event, cursor update must be triggered.
1234 if( mImpl->IsShowingPlaceholderText() )
1236 // Show alternative placeholder-text when editing
1237 ShowPlaceholderText();
1240 mImpl->RequestRelayout();
1244 void Controller::KeyboardFocusLostEvent()
1246 DALI_ASSERT_DEBUG( mImpl->mEventData && "Unexpected KeyboardFocusLostEvent" );
1248 if( mImpl->mEventData )
1250 if ( EventData::INTERRUPTED != mImpl->mEventData->mState )
1252 mImpl->ChangeState( EventData::INACTIVE );
1254 if( !mImpl->IsShowingRealText() )
1256 // Revert to regular placeholder-text when not editing
1257 ShowPlaceholderText();
1261 mImpl->RequestRelayout();
1264 bool Controller::KeyEvent( const Dali::KeyEvent& keyEvent )
1266 DALI_ASSERT_DEBUG( mImpl->mEventData && "Unexpected KeyEvent" );
1268 bool textChanged( false );
1270 if( mImpl->mEventData &&
1271 keyEvent.state == KeyEvent::Down )
1273 int keyCode = keyEvent.keyCode;
1274 const std::string& keyString = keyEvent.keyPressed;
1276 // Pre-process to separate modifying events from non-modifying input events.
1277 if( Dali::DALI_KEY_ESCAPE == keyCode )
1279 // Escape key is a special case which causes focus loss
1280 KeyboardFocusLostEvent();
1282 else if( Dali::DALI_KEY_CURSOR_LEFT == keyCode ||
1283 Dali::DALI_KEY_CURSOR_RIGHT == keyCode ||
1284 Dali::DALI_KEY_CURSOR_UP == keyCode ||
1285 Dali::DALI_KEY_CURSOR_DOWN == keyCode )
1287 Event event( Event::CURSOR_KEY_EVENT );
1288 event.p1.mInt = keyCode;
1289 mImpl->mEventData->mEventQueue.push_back( event );
1291 else if( Dali::DALI_KEY_BACKSPACE == keyCode )
1293 textChanged = BackspaceKeyEvent();
1295 else if ( IsKey( keyEvent, Dali::DALI_KEY_POWER ) )
1297 mImpl->ChangeState( EventData::INTERRUPTED ); // State is not INACTIVE as expect to return to edit mode.
1298 // Avoids calling the InsertText() method which can delete selected text
1300 else if ( IsKey( keyEvent, Dali::DALI_KEY_MENU ) ||
1301 IsKey( keyEvent, Dali::DALI_KEY_HOME ) )
1303 mImpl->ChangeState( EventData::INACTIVE );
1304 // Menu/Home key behaviour does not allow edit mode to resume like Power key
1305 // Avoids calling the InsertText() method which can delete selected text
1307 else if( Dali::DALI_KEY_SHIFT_LEFT == keyCode )
1309 // DALI_KEY_SHIFT_LEFT is the key code for the Left Shift. It's sent (by the imf?) when the predictive text is enabled
1310 // and a character is typed after the type of a upper case latin character.
1316 DALI_LOG_INFO( gLogFilter, Debug::Verbose, "Controller::KeyEvent %p keyString %s\n", this, keyString.c_str() );
1318 // IMF manager is no longer handling key-events
1319 mImpl->ClearPreEditFlag();
1321 InsertText( keyString, COMMIT );
1325 if ( ( mImpl->mEventData->mState != EventData::INTERRUPTED ) &&
1326 ( mImpl->mEventData->mState != EventData::INACTIVE ) )
1328 mImpl->ChangeState( EventData::EDITING );
1331 mImpl->RequestRelayout();
1336 // Do this last since it provides callbacks into application code
1337 mImpl->mControlInterface.TextChanged();
1343 void Controller::InsertText( const std::string& text, Controller::InsertType type )
1345 bool removedPrevious( false );
1346 bool maxLengthReached( false );
1348 DALI_ASSERT_DEBUG( NULL != mImpl->mEventData && "Unexpected InsertText" )
1349 DALI_LOG_INFO( gLogFilter, Debug::Verbose, "Controller::InsertText %p %s (%s) mPrimaryCursorPosition %d mPreEditFlag %d mPreEditStartPosition %d mPreEditLength %d\n",
1350 this, text.c_str(), (COMMIT == type ? "COMMIT" : "PRE_EDIT"),
1351 mImpl->mEventData->mPrimaryCursorPosition, mImpl->mEventData->mPreEditFlag, mImpl->mEventData->mPreEditStartPosition, mImpl->mEventData->mPreEditLength );
1353 // TODO: At the moment the underline runs are only for pre-edit.
1354 mImpl->mVisualModel->mUnderlineRuns.Clear();
1356 Vector<Character> utf32Characters;
1357 Length characterCount( 0u );
1359 // Remove the previous IMF pre-edit (predicitive text)
1360 if( mImpl->mEventData &&
1361 mImpl->mEventData->mPreEditFlag &&
1362 0 != mImpl->mEventData->mPreEditLength )
1364 CharacterIndex offset = mImpl->mEventData->mPrimaryCursorPosition - mImpl->mEventData->mPreEditStartPosition;
1366 removedPrevious = RemoveText( -static_cast<int>(offset), mImpl->mEventData->mPreEditLength );
1368 mImpl->mEventData->mPrimaryCursorPosition = mImpl->mEventData->mPreEditStartPosition;
1369 mImpl->mEventData->mPreEditLength = 0;
1373 // Remove the previous Selection
1374 removedPrevious = RemoveSelectedText();
1379 // Convert text into UTF-32
1380 utf32Characters.Resize( text.size() );
1382 // This is a bit horrible but std::string returns a (signed) char*
1383 const uint8_t* utf8 = reinterpret_cast<const uint8_t*>( text.c_str() );
1385 // Transform a text array encoded in utf8 into an array encoded in utf32.
1386 // It returns the actual number of characters.
1387 characterCount = Utf8ToUtf32( utf8, text.size(), utf32Characters.Begin() );
1388 utf32Characters.Resize( characterCount );
1390 DALI_ASSERT_DEBUG( text.size() >= utf32Characters.Count() && "Invalid UTF32 conversion length" );
1391 DALI_LOG_INFO( gLogFilter, Debug::Verbose, "UTF8 size %d, UTF32 size %d\n", text.size(), utf32Characters.Count() );
1394 if( 0u != utf32Characters.Count() ) // Check if Utf8ToUtf32 conversion succeeded
1396 // The placeholder text is no longer needed
1397 if( mImpl->IsShowingPlaceholderText() )
1402 mImpl->ChangeState( EventData::EDITING );
1404 // Handle the IMF (predicitive text) state changes
1405 if( mImpl->mEventData )
1407 if( COMMIT == type )
1409 // IMF manager is no longer handling key-events
1410 mImpl->ClearPreEditFlag();
1414 if( !mImpl->mEventData->mPreEditFlag )
1416 DALI_LOG_INFO( gLogFilter, Debug::Verbose, "Entered PreEdit state" );
1418 // Record the start of the pre-edit text
1419 mImpl->mEventData->mPreEditStartPosition = mImpl->mEventData->mPrimaryCursorPosition;
1422 mImpl->mEventData->mPreEditLength = utf32Characters.Count();
1423 mImpl->mEventData->mPreEditFlag = true;
1425 DALI_LOG_INFO( gLogFilter, Debug::Verbose, "mPreEditStartPosition %d mPreEditLength %d\n", mImpl->mEventData->mPreEditStartPosition, mImpl->mEventData->mPreEditLength );
1429 const Length numberOfCharactersInModel = mImpl->mLogicalModel->mText.Count();
1431 // Restrict new text to fit within Maximum characters setting
1432 Length maxSizeOfNewText = std::min ( ( mImpl->mMaximumNumberOfCharacters - numberOfCharactersInModel ), characterCount );
1433 maxLengthReached = ( characterCount > maxSizeOfNewText );
1435 // Insert at current cursor position
1436 CharacterIndex& cursorIndex = mImpl->mEventData->mPrimaryCursorPosition;
1438 Vector<Character>& modifyText = mImpl->mLogicalModel->mText;
1440 if( cursorIndex < numberOfCharactersInModel )
1442 modifyText.Insert( modifyText.Begin() + cursorIndex, utf32Characters.Begin(), utf32Characters.Begin() + maxSizeOfNewText );
1446 modifyText.Insert( modifyText.End(), utf32Characters.Begin(), utf32Characters.Begin() + maxSizeOfNewText );
1449 cursorIndex += maxSizeOfNewText;
1451 DALI_LOG_INFO( gLogFilter, Debug::Verbose, "Inserted %d characters, new size %d new cursor %d\n", maxSizeOfNewText, mImpl->mLogicalModel->mText.Count(), mImpl->mEventData->mPrimaryCursorPosition );
1454 if( 0u == mImpl->mLogicalModel->mText.Count() &&
1455 mImpl->IsPlaceholderAvailable() )
1457 // Show place-holder if empty after removing the pre-edit text
1458 ShowPlaceholderText();
1459 mImpl->mEventData->mUpdateCursorPosition = true;
1460 mImpl->ClearPreEditFlag();
1462 else if( removedPrevious ||
1463 0 != utf32Characters.Count() )
1465 // Queue an inserted event
1466 mImpl->QueueModifyEvent( ModifyEvent::TEXT_INSERTED );
1469 if( maxLengthReached )
1471 DALI_LOG_INFO( gLogFilter, Debug::Verbose, "MaxLengthReached (%d)\n", mImpl->mLogicalModel->mText.Count() );
1473 mImpl->ResetImfManager();
1475 // Do this last since it provides callbacks into application code
1476 mImpl->mControlInterface.MaxLengthReached();
1480 bool Controller::RemoveSelectedText()
1482 bool textRemoved( false );
1484 if( EventData::SELECTING == mImpl->mEventData->mState )
1486 std::string removedString;
1487 mImpl->RetrieveSelection( removedString, true );
1489 if( !removedString.empty() )
1492 mImpl->ChangeState( EventData::EDITING );
1499 void Controller::TapEvent( unsigned int tapCount, float x, float y )
1501 DALI_ASSERT_DEBUG( mImpl->mEventData && "Unexpected TapEvent" );
1503 if( NULL != mImpl->mEventData )
1505 DALI_LOG_INFO( gLogFilter, Debug::Concise, "TapEvent state:%d \n", mImpl->mEventData->mState );
1507 if( 1u == tapCount )
1509 // This is to avoid unnecessary relayouts when tapping an empty text-field
1510 bool relayoutNeeded( false );
1512 if ( EventData::EDITING_WITH_PASTE_POPUP == mImpl->mEventData->mState || EventData::EDITING_WITH_PASTE_POPUP == mImpl->mEventData->mState )
1514 mImpl->ChangeState( EventData::EDITING_WITH_GRAB_HANDLE); // If Popup shown hide it here so can be shown again if required.
1517 if( mImpl->IsShowingRealText() && ( EventData::INACTIVE != mImpl->mEventData->mState ) )
1519 // Already in an active state so show a popup
1520 if ( !mImpl->IsClipboardEmpty() )
1522 // Shows Paste popup but could show full popup with Selection options. ( EDITING_WITH_POPUP )
1523 mImpl->ChangeState( EventData::EDITING_WITH_PASTE_POPUP );
1527 mImpl->ChangeState( EventData::EDITING_WITH_GRAB_HANDLE );
1529 relayoutNeeded = true;
1533 if( mImpl->IsShowingPlaceholderText() && !mImpl->IsFocusedPlaceholderAvailable() )
1535 // Hide placeholder text
1539 if ( EventData::INACTIVE == mImpl->mEventData->mState )
1541 mImpl->ChangeState( EventData::EDITING );
1543 else if ( !mImpl->IsClipboardEmpty() )
1545 mImpl->ChangeState( EventData::EDITING_WITH_POPUP );
1547 relayoutNeeded = true;
1550 // Handles & cursors must be repositioned after Relayout() i.e. after the Model has been updated
1551 if( relayoutNeeded )
1553 Event event( Event::TAP_EVENT );
1554 event.p1.mUint = tapCount;
1555 event.p2.mFloat = x;
1556 event.p3.mFloat = y;
1557 mImpl->mEventData->mEventQueue.push_back( event );
1559 mImpl->RequestRelayout();
1562 else if( 2u == tapCount )
1564 if( mImpl->mEventData->mSelectionEnabled &&
1565 mImpl->IsShowingRealText() )
1567 SelectEvent( x, y, false );
1572 // Reset keyboard as tap event has occurred.
1573 mImpl->ResetImfManager();
1576 void Controller::PanEvent( Gesture::State state, const Vector2& displacement )
1577 // Show cursor and grabhandle on first tap, this matches the behaviour of tapping when already editing
1579 DALI_ASSERT_DEBUG( mImpl->mEventData && "Unexpected PanEvent" );
1581 if( mImpl->mEventData )
1583 Event event( Event::PAN_EVENT );
1584 event.p1.mInt = state;
1585 event.p2.mFloat = displacement.x;
1586 event.p3.mFloat = displacement.y;
1587 mImpl->mEventData->mEventQueue.push_back( event );
1589 mImpl->RequestRelayout();
1593 void Controller::LongPressEvent( Gesture::State state, float x, float y )
1595 DALI_ASSERT_DEBUG( mImpl->mEventData && "Unexpected LongPressEvent" );
1597 if( state == Gesture::Started &&
1600 if( ! mImpl->IsShowingRealText() )
1602 Event event( Event::LONG_PRESS_EVENT );
1603 event.p1.mInt = state;
1604 mImpl->mEventData->mEventQueue.push_back( event );
1605 mImpl->RequestRelayout();
1609 // The 1st long-press on inactive text-field is treated as tap
1610 if( EventData::INACTIVE == mImpl->mEventData->mState )
1612 mImpl->ChangeState( EventData::EDITING );
1614 Event event( Event::TAP_EVENT );
1616 event.p2.mFloat = x;
1617 event.p3.mFloat = y;
1618 mImpl->mEventData->mEventQueue.push_back( event );
1620 mImpl->RequestRelayout();
1624 // Reset the imf manger to commit the pre-edit before selecting the text.
1625 mImpl->ResetImfManager();
1627 SelectEvent( x, y, false );
1633 void Controller::SelectEvent( float x, float y, bool selectAll )
1635 DALI_LOG_INFO( gLogFilter, Debug::Verbose, "Controller::SelectEvent\n" );
1637 if( mImpl->mEventData )
1639 mImpl->ChangeState( EventData::SELECTING );
1643 Event event( Event::SELECT_ALL );
1644 mImpl->mEventData->mEventQueue.push_back( event );
1648 Event event( Event::SELECT );
1649 event.p2.mFloat = x;
1650 event.p3.mFloat = y;
1651 mImpl->mEventData->mEventQueue.push_back( event );
1654 mImpl->RequestRelayout();
1658 void Controller::GetTargetSize( Vector2& targetSize )
1660 targetSize = mImpl->mVisualModel->mControlSize;
1663 void Controller::AddDecoration( Actor& actor, bool needsClipping )
1665 mImpl->mControlInterface.AddDecoration( actor, needsClipping );
1668 void Controller::DecorationEvent( HandleType handleType, HandleState state, float x, float y )
1670 DALI_ASSERT_DEBUG( mImpl->mEventData && "Unexpected DecorationEvent" );
1672 if( mImpl->mEventData )
1674 switch( handleType )
1678 Event event( Event::GRAB_HANDLE_EVENT );
1679 event.p1.mUint = state;
1680 event.p2.mFloat = x;
1681 event.p3.mFloat = y;
1683 mImpl->mEventData->mEventQueue.push_back( event );
1686 case LEFT_SELECTION_HANDLE:
1688 Event event( Event::LEFT_SELECTION_HANDLE_EVENT );
1689 event.p1.mUint = state;
1690 event.p2.mFloat = x;
1691 event.p3.mFloat = y;
1693 mImpl->mEventData->mEventQueue.push_back( event );
1696 case RIGHT_SELECTION_HANDLE:
1698 Event event( Event::RIGHT_SELECTION_HANDLE_EVENT );
1699 event.p1.mUint = state;
1700 event.p2.mFloat = x;
1701 event.p3.mFloat = y;
1703 mImpl->mEventData->mEventQueue.push_back( event );
1706 case LEFT_SELECTION_HANDLE_MARKER:
1707 case RIGHT_SELECTION_HANDLE_MARKER:
1709 // Markers do not move the handles.
1712 case HANDLE_TYPE_COUNT:
1714 DALI_ASSERT_DEBUG( !"Controller::HandleEvent. Unexpected handle type" );
1718 mImpl->RequestRelayout();
1722 void Controller::PasteText( const std::string& stringToPaste )
1724 InsertText( stringToPaste, Text::Controller::COMMIT );
1725 mImpl->ChangeState( EventData::EDITING );
1726 mImpl->RequestRelayout();
1728 // Do this last since it provides callbacks into application code
1729 mImpl->mControlInterface.TextChanged();
1732 void Controller::PasteClipboardItemEvent()
1734 // Retrieve the clipboard contents first
1735 ClipboardEventNotifier notifier( ClipboardEventNotifier::Get() );
1736 std::string stringToPaste( notifier.GetContent() );
1738 // Commit the current pre-edit text; the contents of the clipboard should be appended
1739 mImpl->ResetImfManager();
1742 PasteText( stringToPaste );
1745 void Controller::TextPopupButtonTouched( Dali::Toolkit::TextSelectionPopup::Buttons button )
1747 if( NULL == mImpl->mEventData )
1754 case Toolkit::TextSelectionPopup::CUT:
1756 mImpl->SendSelectionToClipboard( true ); // Synchronous call to modify text
1757 mImpl->mOperationsPending = ALL_OPERATIONS;
1759 // This is to reset the virtual keyboard to Upper-case
1760 if( 0u == mImpl->mLogicalModel->mText.Count() )
1765 if( 0u != mImpl->mLogicalModel->mText.Count() ||
1766 !mImpl->IsPlaceholderAvailable() )
1768 mImpl->QueueModifyEvent( ModifyEvent::TEXT_DELETED );
1772 ShowPlaceholderText();
1773 mImpl->mEventData->mUpdateCursorPosition = true;
1775 mImpl->RequestRelayout();
1776 mImpl->mControlInterface.TextChanged();
1779 case Toolkit::TextSelectionPopup::COPY:
1781 mImpl->SendSelectionToClipboard( false ); // Text not modified
1782 mImpl->RequestRelayout(); // Handles, Selection Highlight, Popup
1785 case Toolkit::TextSelectionPopup::PASTE:
1787 std::string stringToPaste("");
1788 mImpl->GetTextFromClipboard( 0, stringToPaste ); // Paste latest item from system clipboard
1789 PasteText( stringToPaste );
1792 case Toolkit::TextSelectionPopup::SELECT:
1794 const Vector2& currentCursorPosition = mImpl->mEventData->mDecorator->GetPosition( PRIMARY_CURSOR );
1796 if( mImpl->mEventData->mSelectionEnabled )
1798 // Creates a SELECT event.
1799 SelectEvent( currentCursorPosition.x, currentCursorPosition.y, false );
1803 case Toolkit::TextSelectionPopup::SELECT_ALL:
1805 // Creates a SELECT_ALL event
1806 SelectEvent( 0.f, 0.f, true );
1809 case Toolkit::TextSelectionPopup::CLIPBOARD:
1811 mImpl->ShowClipboard();
1814 case Toolkit::TextSelectionPopup::NONE:
1822 ImfManager::ImfCallbackData Controller::OnImfEvent( ImfManager& imfManager, const ImfManager::ImfEventData& imfEvent )
1824 bool update = false;
1825 bool requestRelayout = false;
1828 unsigned int cursorPosition( 0 );
1830 switch ( imfEvent.eventName )
1832 case ImfManager::COMMIT:
1834 InsertText( imfEvent.predictiveString, Text::Controller::COMMIT );
1836 requestRelayout = true;
1839 case ImfManager::PREEDIT:
1841 InsertText( imfEvent.predictiveString, Text::Controller::PRE_EDIT );
1843 requestRelayout = true;
1846 case ImfManager::DELETESURROUNDING:
1848 update = RemoveText( imfEvent.cursorOffset, imfEvent.numberOfChars );
1852 if( 0u != mImpl->mLogicalModel->mText.Count() ||
1853 !mImpl->IsPlaceholderAvailable() )
1855 mImpl->QueueModifyEvent( ModifyEvent::TEXT_DELETED );
1859 ShowPlaceholderText();
1860 mImpl->mEventData->mUpdateCursorPosition = true;
1863 requestRelayout = true;
1866 case ImfManager::GETSURROUNDING:
1869 cursorPosition = GetLogicalCursorPosition();
1871 imfManager.SetSurroundingText( text );
1872 imfManager.SetCursorPosition( cursorPosition );
1875 case ImfManager::VOID:
1882 if( ImfManager::GETSURROUNDING != imfEvent.eventName )
1885 cursorPosition = GetLogicalCursorPosition();
1888 if( requestRelayout )
1890 mImpl->mOperationsPending = ALL_OPERATIONS;
1891 mImpl->RequestRelayout();
1893 // Do this last since it provides callbacks into application code
1894 mImpl->mControlInterface.TextChanged();
1897 ImfManager::ImfCallbackData callbackData( update, cursorPosition, text, false );
1899 return callbackData;
1902 Controller::~Controller()
1907 bool Controller::BackspaceKeyEvent()
1909 DALI_LOG_INFO( gLogFilter, Debug::Verbose, "Controller::KeyEvent %p DALI_KEY_BACKSPACE\n", this );
1911 // IMF manager is no longer handling key-events
1912 mImpl->ClearPreEditFlag();
1914 bool removed( false );
1916 if( EventData::SELECTING == mImpl->mEventData->mState )
1918 removed = RemoveSelectedText();
1920 else if( mImpl->mEventData->mPrimaryCursorPosition > 0 )
1922 // Remove the character before the current cursor position
1923 removed = RemoveText( -1, 1 );
1928 DALI_LOG_INFO( gLogFilter, Debug::Verbose, "Controller::KeyEvent %p DALI_KEY_BACKSPACE RemovedText\n", this );
1929 // Notifiy the IMF manager after text changed
1930 // Automatic Upper-case and restarting prediction on an existing word require this.
1933 if( 0u != mImpl->mLogicalModel->mText.Count() ||
1934 !mImpl->IsPlaceholderAvailable() )
1936 mImpl->QueueModifyEvent( ModifyEvent::TEXT_DELETED );
1940 ShowPlaceholderText();
1941 mImpl->mEventData->mUpdateCursorPosition = true;
1948 void Controller::NotifyImfManager()
1950 if( mImpl->mEventData )
1952 if( mImpl->mEventData->mImfManager )
1954 // Notifying IMF of a cursor change triggers a surrounding text request so updating it now.
1957 mImpl->mEventData->mImfManager.SetSurroundingText( text );
1959 mImpl->mEventData->mImfManager.SetCursorPosition( GetLogicalCursorPosition() );
1960 mImpl->mEventData->mImfManager.NotifyCursorPosition();
1965 void Controller::ShowPlaceholderText()
1967 if( mImpl->IsPlaceholderAvailable() )
1969 DALI_ASSERT_DEBUG( mImpl->mEventData && "No placeholder text available" );
1971 mImpl->mEventData->mIsShowingPlaceholderText = true;
1973 // Disable handles when showing place-holder text
1974 mImpl->mEventData->mDecorator->SetHandleActive( GRAB_HANDLE, false );
1975 mImpl->mEventData->mDecorator->SetHandleActive( LEFT_SELECTION_HANDLE, false );
1976 mImpl->mEventData->mDecorator->SetHandleActive( RIGHT_SELECTION_HANDLE, false );
1978 const char* text( NULL );
1981 // TODO - Switch placeholder text styles when changing state
1982 if( EventData::INACTIVE != mImpl->mEventData->mState &&
1983 0u != mImpl->mEventData->mPlaceholderTextActive.c_str() )
1985 text = mImpl->mEventData->mPlaceholderTextActive.c_str();
1986 size = mImpl->mEventData->mPlaceholderTextActive.size();
1990 text = mImpl->mEventData->mPlaceholderTextInactive.c_str();
1991 size = mImpl->mEventData->mPlaceholderTextInactive.size();
1994 // Reset model for showing placeholder.
1995 mImpl->mLogicalModel->mText.Clear();
1997 mImpl->mVisualModel->SetTextColor( mImpl->mEventData->mPlaceholderTextColor );
1999 // Convert text into UTF-32
2000 Vector<Character>& utf32Characters = mImpl->mLogicalModel->mText;
2001 utf32Characters.Resize( size );
2003 // This is a bit horrible but std::string returns a (signed) char*
2004 const uint8_t* utf8 = reinterpret_cast<const uint8_t*>( text );
2006 // Transform a text array encoded in utf8 into an array encoded in utf32.
2007 // It returns the actual number of characters.
2008 Length characterCount = Utf8ToUtf32( utf8, size, utf32Characters.Begin() );
2009 utf32Characters.Resize( characterCount );
2011 // Reset the cursor position
2012 mImpl->mEventData->mPrimaryCursorPosition = 0;
2014 // The natural size needs to be re-calculated.
2015 mImpl->mRecalculateNaturalSize = true;
2017 // Apply modifications to the model
2018 mImpl->mOperationsPending = ALL_OPERATIONS;
2020 // Update the rest of the model during size negotiation
2021 mImpl->QueueModifyEvent( ModifyEvent::TEXT_REPLACED );
2025 void Controller::ClearModelData()
2027 // n.b. This does not Clear the mText from mLogicalModel
2028 mImpl->mLogicalModel->mScriptRuns.Clear();
2029 mImpl->mLogicalModel->mFontRuns.Clear();
2030 mImpl->mLogicalModel->mLineBreakInfo.Clear();
2031 mImpl->mLogicalModel->mWordBreakInfo.Clear();
2032 mImpl->mLogicalModel->mBidirectionalParagraphInfo.Clear();
2033 mImpl->mLogicalModel->mCharacterDirections.Clear();
2034 mImpl->mLogicalModel->mBidirectionalLineInfo.Clear();
2035 mImpl->mLogicalModel->mLogicalToVisualMap.Clear();
2036 mImpl->mLogicalModel->mVisualToLogicalMap.Clear();
2037 mImpl->mVisualModel->mGlyphs.Clear();
2038 mImpl->mVisualModel->mGlyphsToCharacters.Clear();
2039 mImpl->mVisualModel->mCharactersToGlyph.Clear();
2040 mImpl->mVisualModel->mCharactersPerGlyph.Clear();
2041 mImpl->mVisualModel->mGlyphsPerCharacter.Clear();
2042 mImpl->mVisualModel->mGlyphPositions.Clear();
2043 mImpl->mVisualModel->mLines.Clear();
2044 mImpl->mVisualModel->ClearCaches();
2047 void Controller::ClearFontData()
2049 mImpl->mFontDefaults->mFontId = 0u; // Remove old font ID
2050 mImpl->mLogicalModel->mFontRuns.Clear();
2051 mImpl->mVisualModel->mGlyphs.Clear();
2052 mImpl->mVisualModel->mGlyphsToCharacters.Clear();
2053 mImpl->mVisualModel->mCharactersToGlyph.Clear();
2054 mImpl->mVisualModel->mCharactersPerGlyph.Clear();
2055 mImpl->mVisualModel->mGlyphsPerCharacter.Clear();
2056 mImpl->mVisualModel->mGlyphPositions.Clear();
2057 mImpl->mVisualModel->mLines.Clear();
2058 mImpl->mVisualModel->ClearCaches();
2061 Controller::Controller( ControlInterface& controlInterface )
2064 mImpl = new Controller::Impl( controlInterface );
2069 } // namespace Toolkit