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 Vector<ModifyEvent>& events = mImpl->mModifyEvents;
789 if( 0u == events.Count() )
795 for( Vector<ModifyEvent>::ConstIterator it = events.Begin(),
796 endIt = events.End();
800 const ModifyEvent& event = *it;
802 if( ModifyEvent::TEXT_REPLACED == event.type )
804 // A (single) replace event should come first, otherwise we wasted time processing NOOP events
805 DALI_ASSERT_DEBUG( it == events.Begin() && "Unexpected TEXT_REPLACED event" );
809 else if( ModifyEvent::TEXT_INSERTED == event.type )
813 else if( ModifyEvent::TEXT_DELETED == event.type )
815 // Placeholder-text cannot be deleted
816 if( !mImpl->IsShowingPlaceholderText() )
823 if( mImpl->mEventData )
825 // When the text is being modified, delay cursor blinking
826 mImpl->mEventData->mDecorator->DelayCursorBlink();
829 // Discard temporary text
833 void Controller::ResetText()
836 mImpl->mLogicalModel->mText.Clear();
839 // We have cleared everything including the placeholder-text
840 mImpl->PlaceholderCleared();
842 // The natural size needs to be re-calculated.
843 mImpl->mRecalculateNaturalSize = true;
845 // Apply modifications to the model
846 mImpl->mOperationsPending = ALL_OPERATIONS;
849 void Controller::ResetCursorPosition( CharacterIndex cursorIndex )
851 // Reset the cursor position
852 if( NULL != mImpl->mEventData )
854 mImpl->mEventData->mPrimaryCursorPosition = cursorIndex;
856 // Update the cursor if it's in editing mode.
857 if ( EventData::IsEditingState( mImpl->mEventData->mState ) )
859 mImpl->mEventData->mUpdateCursorPosition = true;
864 void Controller::ResetScrollPosition()
866 if( NULL != mImpl->mEventData )
868 // Reset the scroll position.
869 mImpl->mEventData->mScrollPosition = Vector2::ZERO;
870 mImpl->mEventData->mScrollAfterUpdatePosition = true;
874 void Controller::TextReplacedEvent()
879 // The natural size needs to be re-calculated.
880 mImpl->mRecalculateNaturalSize = true;
882 // Apply modifications to the model
883 mImpl->mOperationsPending = ALL_OPERATIONS;
884 mImpl->UpdateModel( ALL_OPERATIONS );
885 mImpl->mOperationsPending = static_cast<OperationsMask>( LAYOUT |
891 void Controller::TextInsertedEvent()
893 DALI_ASSERT_DEBUG( NULL != mImpl->mEventData && "Unexpected TextInsertedEvent" );
895 // TODO - Optimize this
898 // The natural size needs to be re-calculated.
899 mImpl->mRecalculateNaturalSize = true;
901 // Apply modifications to the model; TODO - Optimize this
902 mImpl->mOperationsPending = ALL_OPERATIONS;
903 mImpl->UpdateModel( ALL_OPERATIONS );
904 mImpl->mOperationsPending = static_cast<OperationsMask>( LAYOUT |
909 // Queue a cursor reposition event; this must wait until after DoRelayout()
910 if ( EventData::IsEditingState( mImpl->mEventData->mState ) )
912 mImpl->mEventData->mUpdateCursorPosition = true;
913 mImpl->mEventData->mScrollAfterUpdatePosition = true;
917 void Controller::TextDeletedEvent()
919 DALI_ASSERT_DEBUG( NULL != mImpl->mEventData && "Unexpected TextDeletedEvent" );
921 // TODO - Optimize this
924 // The natural size needs to be re-calculated.
925 mImpl->mRecalculateNaturalSize = true;
927 // Apply modifications to the model; TODO - Optimize this
928 mImpl->mOperationsPending = ALL_OPERATIONS;
929 mImpl->UpdateModel( ALL_OPERATIONS );
930 mImpl->mOperationsPending = static_cast<OperationsMask>( LAYOUT |
935 // Queue a cursor reposition event; this must wait until after DoRelayout()
936 mImpl->mEventData->mUpdateCursorPosition = true;
937 if( 0u != mImpl->mLogicalModel->mText.Count() )
939 mImpl->mEventData->mScrollAfterDelete = true;
943 bool Controller::DoRelayout( const Size& size,
944 OperationsMask operationsRequired,
947 DALI_LOG_INFO( gLogFilter, Debug::Verbose, "-->Controller::DoRelayout %p size %f,%f\n", this, size.width, size.height );
948 bool viewUpdated( false );
950 // Calculate the operations to be done.
951 const OperationsMask operations = static_cast<OperationsMask>( mImpl->mOperationsPending & operationsRequired );
953 if( LAYOUT & operations )
955 // Some vectors with data needed to layout and reorder may be void
956 // after the first time the text has been laid out.
957 // Fill the vectors again.
959 const Length numberOfGlyphs = mImpl->mVisualModel->mGlyphs.Count();
961 if( 0u == numberOfGlyphs )
963 // Nothing else to do if there is no glyphs.
964 DALI_LOG_INFO( gLogFilter, Debug::Verbose, "<--Controller::DoRelayout no glyphs, view updated true\n" );
968 const Vector<LineBreakInfo>& lineBreakInfo = mImpl->mLogicalModel->mLineBreakInfo;
969 const Vector<WordBreakInfo>& wordBreakInfo = mImpl->mLogicalModel->mWordBreakInfo;
970 const Vector<CharacterDirection>& characterDirection = mImpl->mLogicalModel->mCharacterDirections;
971 const Vector<GlyphInfo>& glyphs = mImpl->mVisualModel->mGlyphs;
972 const Vector<CharacterIndex>& glyphsToCharactersMap = mImpl->mVisualModel->mGlyphsToCharacters;
973 const Vector<Length>& charactersPerGlyph = mImpl->mVisualModel->mCharactersPerGlyph;
974 const Character* const textBuffer = mImpl->mLogicalModel->mText.Begin();
976 // Set the layout parameters.
977 LayoutParameters layoutParameters( size,
979 lineBreakInfo.Begin(),
980 wordBreakInfo.Begin(),
981 ( 0u != characterDirection.Count() ) ? characterDirection.Begin() : NULL,
984 glyphsToCharactersMap.Begin(),
985 charactersPerGlyph.Begin() );
987 // The laid-out lines.
988 // It's not possible to know in how many lines the text is going to be laid-out,
989 // but it can be resized at least with the number of 'paragraphs' to avoid
990 // some re-allocations.
991 Vector<LineRun>& lines = mImpl->mVisualModel->mLines;
993 // Delete any previous laid out lines before setting the new ones.
996 // The capacity of the bidirectional paragraph info is the number of paragraphs.
997 lines.Reserve( mImpl->mLogicalModel->mBidirectionalParagraphInfo.Capacity() );
999 // Resize the vector of positions to have the same size than the vector of glyphs.
1000 Vector<Vector2>& glyphPositions = mImpl->mVisualModel->mGlyphPositions;
1001 glyphPositions.Resize( numberOfGlyphs );
1003 // Whether the last character is a new paragraph character.
1004 layoutParameters.isLastNewParagraph = TextAbstraction::IsNewParagraph( *( textBuffer + ( mImpl->mLogicalModel->mText.Count() - 1u ) ) );
1006 // Update the visual model.
1007 viewUpdated = mImpl->mLayoutEngine.LayoutText( layoutParameters,
1014 // Reorder the lines
1015 if( REORDER & operations )
1017 Vector<BidirectionalParagraphInfoRun>& bidirectionalInfo = mImpl->mLogicalModel->mBidirectionalParagraphInfo;
1019 // Check first if there are paragraphs with bidirectional info.
1020 if( 0u != bidirectionalInfo.Count() )
1023 const Length numberOfLines = mImpl->mVisualModel->mLines.Count();
1025 // Reorder the lines.
1026 Vector<BidirectionalLineInfoRun> lineBidirectionalInfoRuns;
1027 lineBidirectionalInfoRuns.Reserve( numberOfLines ); // Reserve because is not known yet how many lines have right to left characters.
1028 ReorderLines( bidirectionalInfo,
1030 lineBidirectionalInfoRuns );
1032 // Set the bidirectional info into the model.
1033 const Length numberOfBidirectionalInfoRuns = lineBidirectionalInfoRuns.Count();
1034 mImpl->mLogicalModel->SetVisualToLogicalMap( lineBidirectionalInfoRuns.Begin(),
1035 numberOfBidirectionalInfoRuns );
1037 // Set the bidirectional info per line into the layout parameters.
1038 layoutParameters.lineBidirectionalInfoRunsBuffer = lineBidirectionalInfoRuns.Begin();
1039 layoutParameters.numberOfBidirectionalInfoRuns = numberOfBidirectionalInfoRuns;
1041 // Get the character to glyph conversion table and set into the layout.
1042 layoutParameters.charactersToGlyphsBuffer = mImpl->mVisualModel->mCharactersToGlyph.Begin();
1044 // Get the glyphs per character table and set into the layout.
1045 layoutParameters.glyphsPerCharacterBuffer = mImpl->mVisualModel->mGlyphsPerCharacter.Begin();
1047 // Re-layout the text. Reorder those lines with right to left characters.
1048 mImpl->mLayoutEngine.ReLayoutRightToLeftLines( layoutParameters,
1051 // Free the allocated memory used to store the conversion table in the bidirectional line info run.
1052 for( Vector<BidirectionalLineInfoRun>::Iterator it = lineBidirectionalInfoRuns.Begin(),
1053 endIt = lineBidirectionalInfoRuns.End();
1057 BidirectionalLineInfoRun& bidiLineInfo = *it;
1059 free( bidiLineInfo.visualToLogicalMap );
1064 // Sets the actual size.
1065 if( UPDATE_ACTUAL_SIZE & operations )
1067 mImpl->mVisualModel->SetActualSize( layoutSize );
1073 layoutSize = mImpl->mVisualModel->GetActualSize();
1076 if( ALIGN & operations )
1078 // The laid-out lines.
1079 Vector<LineRun>& lines = mImpl->mVisualModel->mLines;
1081 mImpl->mLayoutEngine.Align( layoutSize,
1087 DALI_LOG_INFO( gLogFilter, Debug::Verbose, "<--Controller::DoRelayout, view updated %s\n", ( viewUpdated ? "true" : "false" ) );
1091 void Controller::SetMultiLineEnabled( bool enable )
1093 const LayoutEngine::Layout layout = enable ? LayoutEngine::MULTI_LINE_BOX : LayoutEngine::SINGLE_LINE_BOX;
1095 if( layout != mImpl->mLayoutEngine.GetLayout() )
1097 // Set the layout type.
1098 mImpl->mLayoutEngine.SetLayout( layout );
1100 // Set the flags to redo the layout operations
1101 const OperationsMask layoutOperations = static_cast<OperationsMask>( LAYOUT |
1102 UPDATE_ACTUAL_SIZE |
1106 mImpl->mOperationsPending = static_cast<OperationsMask>( mImpl->mOperationsPending | layoutOperations );
1108 mImpl->RequestRelayout();
1112 bool Controller::IsMultiLineEnabled() const
1114 return LayoutEngine::MULTI_LINE_BOX == mImpl->mLayoutEngine.GetLayout();
1117 void Controller::SetHorizontalAlignment( LayoutEngine::HorizontalAlignment alignment )
1119 if( alignment != mImpl->mLayoutEngine.GetHorizontalAlignment() )
1121 // Set the alignment.
1122 mImpl->mLayoutEngine.SetHorizontalAlignment( alignment );
1124 // Set the flag to redo the alignment operation.
1125 mImpl->mOperationsPending = static_cast<OperationsMask>( mImpl->mOperationsPending | ALIGN );
1127 mImpl->RequestRelayout();
1131 LayoutEngine::HorizontalAlignment Controller::GetHorizontalAlignment() const
1133 return mImpl->mLayoutEngine.GetHorizontalAlignment();
1136 void Controller::SetVerticalAlignment( LayoutEngine::VerticalAlignment alignment )
1138 if( alignment != mImpl->mLayoutEngine.GetVerticalAlignment() )
1140 // Set the alignment.
1141 mImpl->mLayoutEngine.SetVerticalAlignment( alignment );
1143 mImpl->mOperationsPending = static_cast<OperationsMask>( mImpl->mOperationsPending | ALIGN );
1145 mImpl->RequestRelayout();
1149 LayoutEngine::VerticalAlignment Controller::GetVerticalAlignment() const
1151 return mImpl->mLayoutEngine.GetVerticalAlignment();
1154 void Controller::CalculateTextAlignment( const Size& size )
1156 // Get the direction of the first character.
1157 const CharacterDirection firstParagraphDirection = mImpl->mLogicalModel->GetCharacterDirection( 0u );
1159 Size actualSize = mImpl->mVisualModel->GetActualSize();
1160 if( fabsf( actualSize.height ) < Math::MACHINE_EPSILON_1000 )
1162 // Get the line height of the default font.
1163 actualSize.height = mImpl->GetDefaultFontLineHeight();
1166 // If the first paragraph is right to left swap ALIGN_BEGIN and ALIGN_END;
1167 LayoutEngine::HorizontalAlignment horizontalAlignment = mImpl->mLayoutEngine.GetHorizontalAlignment();
1168 if( firstParagraphDirection &&
1169 ( LayoutEngine::HORIZONTAL_ALIGN_CENTER != horizontalAlignment ) )
1171 if( LayoutEngine::HORIZONTAL_ALIGN_BEGIN == horizontalAlignment )
1173 horizontalAlignment = LayoutEngine::HORIZONTAL_ALIGN_END;
1177 horizontalAlignment = LayoutEngine::HORIZONTAL_ALIGN_BEGIN;
1181 switch( horizontalAlignment )
1183 case LayoutEngine::HORIZONTAL_ALIGN_BEGIN:
1185 mImpl->mAlignmentOffset.x = 0.f;
1188 case LayoutEngine::HORIZONTAL_ALIGN_CENTER:
1190 mImpl->mAlignmentOffset.x = floorf( 0.5f * ( size.width - actualSize.width ) ); // try to avoid pixel alignment.
1193 case LayoutEngine::HORIZONTAL_ALIGN_END:
1195 mImpl->mAlignmentOffset.x = size.width - actualSize.width;
1200 const LayoutEngine::VerticalAlignment verticalAlignment = mImpl->mLayoutEngine.GetVerticalAlignment();
1201 switch( verticalAlignment )
1203 case LayoutEngine::VERTICAL_ALIGN_TOP:
1205 mImpl->mAlignmentOffset.y = 0.f;
1208 case LayoutEngine::VERTICAL_ALIGN_CENTER:
1210 mImpl->mAlignmentOffset.y = floorf( 0.5f * ( size.height - actualSize.height ) ); // try to avoid pixel alignment.
1213 case LayoutEngine::VERTICAL_ALIGN_BOTTOM:
1215 mImpl->mAlignmentOffset.y = size.height - actualSize.height;
1221 LayoutEngine& Controller::GetLayoutEngine()
1223 return mImpl->mLayoutEngine;
1226 View& Controller::GetView()
1228 return mImpl->mView;
1231 void Controller::KeyboardFocusGainEvent()
1233 DALI_ASSERT_DEBUG( mImpl->mEventData && "Unexpected KeyboardFocusGainEvent" );
1235 if( mImpl->mEventData )
1237 if( ( EventData::INACTIVE == mImpl->mEventData->mState ) ||
1238 ( EventData::INTERRUPTED == mImpl->mEventData->mState ) )
1240 mImpl->ChangeState( EventData::EDITING );
1241 mImpl->mEventData->mUpdateCursorPosition = true; //If editing started without tap event, cursor update must be triggered.
1244 if( mImpl->IsShowingPlaceholderText() )
1246 // Show alternative placeholder-text when editing
1247 ShowPlaceholderText();
1250 mImpl->RequestRelayout();
1254 void Controller::KeyboardFocusLostEvent()
1256 DALI_ASSERT_DEBUG( mImpl->mEventData && "Unexpected KeyboardFocusLostEvent" );
1258 if( mImpl->mEventData )
1260 if ( EventData::INTERRUPTED != mImpl->mEventData->mState )
1262 mImpl->ChangeState( EventData::INACTIVE );
1264 if( !mImpl->IsShowingRealText() )
1266 // Revert to regular placeholder-text when not editing
1267 ShowPlaceholderText();
1271 mImpl->RequestRelayout();
1274 bool Controller::KeyEvent( const Dali::KeyEvent& keyEvent )
1276 DALI_ASSERT_DEBUG( mImpl->mEventData && "Unexpected KeyEvent" );
1278 bool textChanged( false );
1280 if( mImpl->mEventData &&
1281 keyEvent.state == KeyEvent::Down )
1283 int keyCode = keyEvent.keyCode;
1284 const std::string& keyString = keyEvent.keyPressed;
1286 // Pre-process to separate modifying events from non-modifying input events.
1287 if( Dali::DALI_KEY_ESCAPE == keyCode )
1289 // Escape key is a special case which causes focus loss
1290 KeyboardFocusLostEvent();
1292 else if( Dali::DALI_KEY_CURSOR_LEFT == keyCode ||
1293 Dali::DALI_KEY_CURSOR_RIGHT == keyCode ||
1294 Dali::DALI_KEY_CURSOR_UP == keyCode ||
1295 Dali::DALI_KEY_CURSOR_DOWN == keyCode )
1297 Event event( Event::CURSOR_KEY_EVENT );
1298 event.p1.mInt = keyCode;
1299 mImpl->mEventData->mEventQueue.push_back( event );
1301 else if( Dali::DALI_KEY_BACKSPACE == keyCode )
1303 textChanged = BackspaceKeyEvent();
1305 else if ( IsKey( keyEvent, Dali::DALI_KEY_POWER ) )
1307 mImpl->ChangeState( EventData::INTERRUPTED ); // State is not INACTIVE as expect to return to edit mode.
1308 // Avoids calling the InsertText() method which can delete selected text
1310 else if ( IsKey( keyEvent, Dali::DALI_KEY_MENU ) ||
1311 IsKey( keyEvent, Dali::DALI_KEY_HOME ) )
1313 mImpl->ChangeState( EventData::INACTIVE );
1314 // Menu/Home key behaviour does not allow edit mode to resume like Power key
1315 // Avoids calling the InsertText() method which can delete selected text
1317 else if( Dali::DALI_KEY_SHIFT_LEFT == keyCode )
1319 // DALI_KEY_SHIFT_LEFT is the key code for the Left Shift. It's sent (by the imf?) when the predictive text is enabled
1320 // and a character is typed after the type of a upper case latin character.
1326 DALI_LOG_INFO( gLogFilter, Debug::Verbose, "Controller::KeyEvent %p keyString %s\n", this, keyString.c_str() );
1328 // IMF manager is no longer handling key-events
1329 mImpl->ClearPreEditFlag();
1331 InsertText( keyString, COMMIT );
1335 if ( ( mImpl->mEventData->mState != EventData::INTERRUPTED ) &&
1336 ( mImpl->mEventData->mState != EventData::INACTIVE ) )
1338 mImpl->ChangeState( EventData::EDITING );
1341 mImpl->RequestRelayout();
1346 // Do this last since it provides callbacks into application code
1347 mImpl->mControlInterface.TextChanged();
1353 void Controller::InsertText( const std::string& text, Controller::InsertType type )
1355 bool removedPrevious( false );
1356 bool maxLengthReached( false );
1358 DALI_ASSERT_DEBUG( NULL != mImpl->mEventData && "Unexpected InsertText" )
1359 DALI_LOG_INFO( gLogFilter, Debug::Verbose, "Controller::InsertText %p %s (%s) mPrimaryCursorPosition %d mPreEditFlag %d mPreEditStartPosition %d mPreEditLength %d\n",
1360 this, text.c_str(), (COMMIT == type ? "COMMIT" : "PRE_EDIT"),
1361 mImpl->mEventData->mPrimaryCursorPosition, mImpl->mEventData->mPreEditFlag, mImpl->mEventData->mPreEditStartPosition, mImpl->mEventData->mPreEditLength );
1363 // TODO: At the moment the underline runs are only for pre-edit.
1364 mImpl->mVisualModel->mUnderlineRuns.Clear();
1366 Vector<Character> utf32Characters;
1367 Length characterCount( 0u );
1369 // Remove the previous IMF pre-edit (predicitive text)
1370 if( mImpl->mEventData &&
1371 mImpl->mEventData->mPreEditFlag &&
1372 0 != mImpl->mEventData->mPreEditLength )
1374 CharacterIndex offset = mImpl->mEventData->mPrimaryCursorPosition - mImpl->mEventData->mPreEditStartPosition;
1376 removedPrevious = RemoveText( -static_cast<int>(offset), mImpl->mEventData->mPreEditLength );
1378 mImpl->mEventData->mPrimaryCursorPosition = mImpl->mEventData->mPreEditStartPosition;
1379 mImpl->mEventData->mPreEditLength = 0;
1383 // Remove the previous Selection
1384 removedPrevious = RemoveSelectedText();
1389 // Convert text into UTF-32
1390 utf32Characters.Resize( text.size() );
1392 // This is a bit horrible but std::string returns a (signed) char*
1393 const uint8_t* utf8 = reinterpret_cast<const uint8_t*>( text.c_str() );
1395 // Transform a text array encoded in utf8 into an array encoded in utf32.
1396 // It returns the actual number of characters.
1397 characterCount = Utf8ToUtf32( utf8, text.size(), utf32Characters.Begin() );
1398 utf32Characters.Resize( characterCount );
1400 DALI_ASSERT_DEBUG( text.size() >= utf32Characters.Count() && "Invalid UTF32 conversion length" );
1401 DALI_LOG_INFO( gLogFilter, Debug::Verbose, "UTF8 size %d, UTF32 size %d\n", text.size(), utf32Characters.Count() );
1404 if( 0u != utf32Characters.Count() ) // Check if Utf8ToUtf32 conversion succeeded
1406 // The placeholder text is no longer needed
1407 if( mImpl->IsShowingPlaceholderText() )
1412 mImpl->ChangeState( EventData::EDITING );
1414 // Handle the IMF (predicitive text) state changes
1415 if( mImpl->mEventData )
1417 if( COMMIT == type )
1419 // IMF manager is no longer handling key-events
1420 mImpl->ClearPreEditFlag();
1424 if( !mImpl->mEventData->mPreEditFlag )
1426 DALI_LOG_INFO( gLogFilter, Debug::Verbose, "Entered PreEdit state" );
1428 // Record the start of the pre-edit text
1429 mImpl->mEventData->mPreEditStartPosition = mImpl->mEventData->mPrimaryCursorPosition;
1432 mImpl->mEventData->mPreEditLength = utf32Characters.Count();
1433 mImpl->mEventData->mPreEditFlag = true;
1435 DALI_LOG_INFO( gLogFilter, Debug::Verbose, "mPreEditStartPosition %d mPreEditLength %d\n", mImpl->mEventData->mPreEditStartPosition, mImpl->mEventData->mPreEditLength );
1439 const Length numberOfCharactersInModel = mImpl->mLogicalModel->mText.Count();
1441 // Restrict new text to fit within Maximum characters setting
1442 Length maxSizeOfNewText = std::min ( ( mImpl->mMaximumNumberOfCharacters - numberOfCharactersInModel ), characterCount );
1443 maxLengthReached = ( characterCount > maxSizeOfNewText );
1445 // The cursor position.
1446 CharacterIndex& cursorIndex = mImpl->mEventData->mPrimaryCursorPosition;
1448 // Insert at current cursor position.
1449 Vector<Character>& modifyText = mImpl->mLogicalModel->mText;
1451 if( cursorIndex < numberOfCharactersInModel )
1453 modifyText.Insert( modifyText.Begin() + cursorIndex, utf32Characters.Begin(), utf32Characters.Begin() + maxSizeOfNewText );
1457 modifyText.Insert( modifyText.End(), utf32Characters.Begin(), utf32Characters.Begin() + maxSizeOfNewText );
1460 cursorIndex += maxSizeOfNewText;
1462 DALI_LOG_INFO( gLogFilter, Debug::Verbose, "Inserted %d characters, new size %d new cursor %d\n", maxSizeOfNewText, mImpl->mLogicalModel->mText.Count(), mImpl->mEventData->mPrimaryCursorPosition );
1465 if( 0u == mImpl->mLogicalModel->mText.Count() &&
1466 mImpl->IsPlaceholderAvailable() )
1468 // Show place-holder if empty after removing the pre-edit text
1469 ShowPlaceholderText();
1470 mImpl->mEventData->mUpdateCursorPosition = true;
1471 mImpl->ClearPreEditFlag();
1473 else if( removedPrevious ||
1474 0 != utf32Characters.Count() )
1476 // Queue an inserted event
1477 mImpl->QueueModifyEvent( ModifyEvent::TEXT_INSERTED );
1480 if( maxLengthReached )
1482 DALI_LOG_INFO( gLogFilter, Debug::Verbose, "MaxLengthReached (%d)\n", mImpl->mLogicalModel->mText.Count() );
1484 mImpl->ResetImfManager();
1486 // Do this last since it provides callbacks into application code
1487 mImpl->mControlInterface.MaxLengthReached();
1491 bool Controller::RemoveSelectedText()
1493 bool textRemoved( false );
1495 if( EventData::SELECTING == mImpl->mEventData->mState )
1497 std::string removedString;
1498 mImpl->RetrieveSelection( removedString, true );
1500 if( !removedString.empty() )
1503 mImpl->ChangeState( EventData::EDITING );
1510 void Controller::TapEvent( unsigned int tapCount, float x, float y )
1512 DALI_ASSERT_DEBUG( mImpl->mEventData && "Unexpected TapEvent" );
1514 if( NULL != mImpl->mEventData )
1516 DALI_LOG_INFO( gLogFilter, Debug::Concise, "TapEvent state:%d \n", mImpl->mEventData->mState );
1518 if( 1u == tapCount )
1520 // This is to avoid unnecessary relayouts when tapping an empty text-field
1521 bool relayoutNeeded( false );
1523 if ( EventData::EDITING_WITH_PASTE_POPUP == mImpl->mEventData->mState || EventData::EDITING_WITH_PASTE_POPUP == mImpl->mEventData->mState )
1525 mImpl->ChangeState( EventData::EDITING_WITH_GRAB_HANDLE); // If Popup shown hide it here so can be shown again if required.
1528 if( mImpl->IsShowingRealText() && ( EventData::INACTIVE != mImpl->mEventData->mState ) )
1530 // Already in an active state so show a popup
1531 if ( !mImpl->IsClipboardEmpty() )
1533 // Shows Paste popup but could show full popup with Selection options. ( EDITING_WITH_POPUP )
1534 mImpl->ChangeState( EventData::EDITING_WITH_PASTE_POPUP );
1538 mImpl->ChangeState( EventData::EDITING_WITH_GRAB_HANDLE );
1540 relayoutNeeded = true;
1544 if( mImpl->IsShowingPlaceholderText() && !mImpl->IsFocusedPlaceholderAvailable() )
1546 // Hide placeholder text
1550 if ( EventData::INACTIVE == mImpl->mEventData->mState )
1552 mImpl->ChangeState( EventData::EDITING );
1554 else if ( !mImpl->IsClipboardEmpty() )
1556 mImpl->ChangeState( EventData::EDITING_WITH_POPUP );
1558 relayoutNeeded = true;
1561 // Handles & cursors must be repositioned after Relayout() i.e. after the Model has been updated
1562 if( relayoutNeeded )
1564 Event event( Event::TAP_EVENT );
1565 event.p1.mUint = tapCount;
1566 event.p2.mFloat = x;
1567 event.p3.mFloat = y;
1568 mImpl->mEventData->mEventQueue.push_back( event );
1570 mImpl->RequestRelayout();
1573 else if( 2u == tapCount )
1575 if( mImpl->mEventData->mSelectionEnabled &&
1576 mImpl->IsShowingRealText() )
1578 SelectEvent( x, y, false );
1583 // Reset keyboard as tap event has occurred.
1584 mImpl->ResetImfManager();
1587 void Controller::PanEvent( Gesture::State state, const Vector2& displacement )
1588 // Show cursor and grabhandle on first tap, this matches the behaviour of tapping when already editing
1590 DALI_ASSERT_DEBUG( mImpl->mEventData && "Unexpected PanEvent" );
1592 if( mImpl->mEventData )
1594 Event event( Event::PAN_EVENT );
1595 event.p1.mInt = state;
1596 event.p2.mFloat = displacement.x;
1597 event.p3.mFloat = displacement.y;
1598 mImpl->mEventData->mEventQueue.push_back( event );
1600 mImpl->RequestRelayout();
1604 void Controller::LongPressEvent( Gesture::State state, float x, float y )
1606 DALI_ASSERT_DEBUG( mImpl->mEventData && "Unexpected LongPressEvent" );
1608 if( state == Gesture::Started &&
1611 if( ! mImpl->IsShowingRealText() )
1613 Event event( Event::LONG_PRESS_EVENT );
1614 event.p1.mInt = state;
1615 mImpl->mEventData->mEventQueue.push_back( event );
1616 mImpl->RequestRelayout();
1620 // The 1st long-press on inactive text-field is treated as tap
1621 if( EventData::INACTIVE == mImpl->mEventData->mState )
1623 mImpl->ChangeState( EventData::EDITING );
1625 Event event( Event::TAP_EVENT );
1627 event.p2.mFloat = x;
1628 event.p3.mFloat = y;
1629 mImpl->mEventData->mEventQueue.push_back( event );
1631 mImpl->RequestRelayout();
1635 // Reset the imf manger to commit the pre-edit before selecting the text.
1636 mImpl->ResetImfManager();
1638 SelectEvent( x, y, false );
1644 void Controller::SelectEvent( float x, float y, bool selectAll )
1646 DALI_LOG_INFO( gLogFilter, Debug::Verbose, "Controller::SelectEvent\n" );
1648 if( mImpl->mEventData )
1650 mImpl->ChangeState( EventData::SELECTING );
1654 Event event( Event::SELECT_ALL );
1655 mImpl->mEventData->mEventQueue.push_back( event );
1659 Event event( Event::SELECT );
1660 event.p2.mFloat = x;
1661 event.p3.mFloat = y;
1662 mImpl->mEventData->mEventQueue.push_back( event );
1665 mImpl->RequestRelayout();
1669 void Controller::GetTargetSize( Vector2& targetSize )
1671 targetSize = mImpl->mVisualModel->mControlSize;
1674 void Controller::AddDecoration( Actor& actor, bool needsClipping )
1676 mImpl->mControlInterface.AddDecoration( actor, needsClipping );
1679 void Controller::DecorationEvent( HandleType handleType, HandleState state, float x, float y )
1681 DALI_ASSERT_DEBUG( mImpl->mEventData && "Unexpected DecorationEvent" );
1683 if( mImpl->mEventData )
1685 switch( handleType )
1689 Event event( Event::GRAB_HANDLE_EVENT );
1690 event.p1.mUint = state;
1691 event.p2.mFloat = x;
1692 event.p3.mFloat = y;
1694 mImpl->mEventData->mEventQueue.push_back( event );
1697 case LEFT_SELECTION_HANDLE:
1699 Event event( Event::LEFT_SELECTION_HANDLE_EVENT );
1700 event.p1.mUint = state;
1701 event.p2.mFloat = x;
1702 event.p3.mFloat = y;
1704 mImpl->mEventData->mEventQueue.push_back( event );
1707 case RIGHT_SELECTION_HANDLE:
1709 Event event( Event::RIGHT_SELECTION_HANDLE_EVENT );
1710 event.p1.mUint = state;
1711 event.p2.mFloat = x;
1712 event.p3.mFloat = y;
1714 mImpl->mEventData->mEventQueue.push_back( event );
1717 case LEFT_SELECTION_HANDLE_MARKER:
1718 case RIGHT_SELECTION_HANDLE_MARKER:
1720 // Markers do not move the handles.
1723 case HANDLE_TYPE_COUNT:
1725 DALI_ASSERT_DEBUG( !"Controller::HandleEvent. Unexpected handle type" );
1729 mImpl->RequestRelayout();
1733 void Controller::PasteText( const std::string& stringToPaste )
1735 InsertText( stringToPaste, Text::Controller::COMMIT );
1736 mImpl->ChangeState( EventData::EDITING );
1737 mImpl->RequestRelayout();
1739 // Do this last since it provides callbacks into application code
1740 mImpl->mControlInterface.TextChanged();
1743 void Controller::PasteClipboardItemEvent()
1745 // Retrieve the clipboard contents first
1746 ClipboardEventNotifier notifier( ClipboardEventNotifier::Get() );
1747 std::string stringToPaste( notifier.GetContent() );
1749 // Commit the current pre-edit text; the contents of the clipboard should be appended
1750 mImpl->ResetImfManager();
1753 PasteText( stringToPaste );
1756 void Controller::TextPopupButtonTouched( Dali::Toolkit::TextSelectionPopup::Buttons button )
1758 if( NULL == mImpl->mEventData )
1765 case Toolkit::TextSelectionPopup::CUT:
1767 mImpl->SendSelectionToClipboard( true ); // Synchronous call to modify text
1768 mImpl->mOperationsPending = ALL_OPERATIONS;
1770 // This is to reset the virtual keyboard to Upper-case
1771 if( 0u == mImpl->mLogicalModel->mText.Count() )
1776 if( 0u != mImpl->mLogicalModel->mText.Count() ||
1777 !mImpl->IsPlaceholderAvailable() )
1779 mImpl->QueueModifyEvent( ModifyEvent::TEXT_DELETED );
1783 ShowPlaceholderText();
1784 mImpl->mEventData->mUpdateCursorPosition = true;
1786 mImpl->RequestRelayout();
1787 mImpl->mControlInterface.TextChanged();
1790 case Toolkit::TextSelectionPopup::COPY:
1792 mImpl->SendSelectionToClipboard( false ); // Text not modified
1793 mImpl->RequestRelayout(); // Handles, Selection Highlight, Popup
1796 case Toolkit::TextSelectionPopup::PASTE:
1798 std::string stringToPaste("");
1799 mImpl->GetTextFromClipboard( 0, stringToPaste ); // Paste latest item from system clipboard
1800 PasteText( stringToPaste );
1803 case Toolkit::TextSelectionPopup::SELECT:
1805 const Vector2& currentCursorPosition = mImpl->mEventData->mDecorator->GetPosition( PRIMARY_CURSOR );
1807 if( mImpl->mEventData->mSelectionEnabled )
1809 // Creates a SELECT event.
1810 SelectEvent( currentCursorPosition.x, currentCursorPosition.y, false );
1814 case Toolkit::TextSelectionPopup::SELECT_ALL:
1816 // Creates a SELECT_ALL event
1817 SelectEvent( 0.f, 0.f, true );
1820 case Toolkit::TextSelectionPopup::CLIPBOARD:
1822 mImpl->ShowClipboard();
1825 case Toolkit::TextSelectionPopup::NONE:
1833 ImfManager::ImfCallbackData Controller::OnImfEvent( ImfManager& imfManager, const ImfManager::ImfEventData& imfEvent )
1835 bool update = false;
1836 bool requestRelayout = false;
1839 unsigned int cursorPosition( 0 );
1841 switch ( imfEvent.eventName )
1843 case ImfManager::COMMIT:
1845 InsertText( imfEvent.predictiveString, Text::Controller::COMMIT );
1847 requestRelayout = true;
1850 case ImfManager::PREEDIT:
1852 InsertText( imfEvent.predictiveString, Text::Controller::PRE_EDIT );
1854 requestRelayout = true;
1857 case ImfManager::DELETESURROUNDING:
1859 update = RemoveText( imfEvent.cursorOffset, imfEvent.numberOfChars );
1863 if( 0u != mImpl->mLogicalModel->mText.Count() ||
1864 !mImpl->IsPlaceholderAvailable() )
1866 mImpl->QueueModifyEvent( ModifyEvent::TEXT_DELETED );
1870 ShowPlaceholderText();
1871 mImpl->mEventData->mUpdateCursorPosition = true;
1874 requestRelayout = true;
1877 case ImfManager::GETSURROUNDING:
1880 cursorPosition = GetLogicalCursorPosition();
1882 imfManager.SetSurroundingText( text );
1883 imfManager.SetCursorPosition( cursorPosition );
1886 case ImfManager::VOID:
1893 if( ImfManager::GETSURROUNDING != imfEvent.eventName )
1896 cursorPosition = GetLogicalCursorPosition();
1899 if( requestRelayout )
1901 mImpl->mOperationsPending = ALL_OPERATIONS;
1902 mImpl->RequestRelayout();
1904 // Do this last since it provides callbacks into application code
1905 mImpl->mControlInterface.TextChanged();
1908 ImfManager::ImfCallbackData callbackData( update, cursorPosition, text, false );
1910 return callbackData;
1913 Controller::~Controller()
1918 bool Controller::BackspaceKeyEvent()
1920 DALI_LOG_INFO( gLogFilter, Debug::Verbose, "Controller::KeyEvent %p DALI_KEY_BACKSPACE\n", this );
1922 // IMF manager is no longer handling key-events
1923 mImpl->ClearPreEditFlag();
1925 bool removed( false );
1927 if( EventData::SELECTING == mImpl->mEventData->mState )
1929 removed = RemoveSelectedText();
1931 else if( mImpl->mEventData->mPrimaryCursorPosition > 0 )
1933 // Remove the character before the current cursor position
1934 removed = RemoveText( -1, 1 );
1939 DALI_LOG_INFO( gLogFilter, Debug::Verbose, "Controller::KeyEvent %p DALI_KEY_BACKSPACE RemovedText\n", this );
1940 // Notifiy the IMF manager after text changed
1941 // Automatic Upper-case and restarting prediction on an existing word require this.
1944 if( 0u != mImpl->mLogicalModel->mText.Count() ||
1945 !mImpl->IsPlaceholderAvailable() )
1947 mImpl->QueueModifyEvent( ModifyEvent::TEXT_DELETED );
1951 ShowPlaceholderText();
1952 mImpl->mEventData->mUpdateCursorPosition = true;
1959 void Controller::NotifyImfManager()
1961 if( mImpl->mEventData )
1963 if( mImpl->mEventData->mImfManager )
1965 // Notifying IMF of a cursor change triggers a surrounding text request so updating it now.
1968 mImpl->mEventData->mImfManager.SetSurroundingText( text );
1970 mImpl->mEventData->mImfManager.SetCursorPosition( GetLogicalCursorPosition() );
1971 mImpl->mEventData->mImfManager.NotifyCursorPosition();
1976 void Controller::ShowPlaceholderText()
1978 if( mImpl->IsPlaceholderAvailable() )
1980 DALI_ASSERT_DEBUG( mImpl->mEventData && "No placeholder text available" );
1982 mImpl->mEventData->mIsShowingPlaceholderText = true;
1984 // Disable handles when showing place-holder text
1985 mImpl->mEventData->mDecorator->SetHandleActive( GRAB_HANDLE, false );
1986 mImpl->mEventData->mDecorator->SetHandleActive( LEFT_SELECTION_HANDLE, false );
1987 mImpl->mEventData->mDecorator->SetHandleActive( RIGHT_SELECTION_HANDLE, false );
1989 const char* text( NULL );
1992 // TODO - Switch placeholder text styles when changing state
1993 if( EventData::INACTIVE != mImpl->mEventData->mState &&
1994 0u != mImpl->mEventData->mPlaceholderTextActive.c_str() )
1996 text = mImpl->mEventData->mPlaceholderTextActive.c_str();
1997 size = mImpl->mEventData->mPlaceholderTextActive.size();
2001 text = mImpl->mEventData->mPlaceholderTextInactive.c_str();
2002 size = mImpl->mEventData->mPlaceholderTextInactive.size();
2005 // Reset model for showing placeholder.
2006 mImpl->mLogicalModel->mText.Clear();
2008 mImpl->mVisualModel->SetTextColor( mImpl->mEventData->mPlaceholderTextColor );
2010 // Convert text into UTF-32
2011 Vector<Character>& utf32Characters = mImpl->mLogicalModel->mText;
2012 utf32Characters.Resize( size );
2014 // This is a bit horrible but std::string returns a (signed) char*
2015 const uint8_t* utf8 = reinterpret_cast<const uint8_t*>( text );
2017 // Transform a text array encoded in utf8 into an array encoded in utf32.
2018 // It returns the actual number of characters.
2019 Length characterCount = Utf8ToUtf32( utf8, size, utf32Characters.Begin() );
2020 utf32Characters.Resize( characterCount );
2022 // Reset the cursor position
2023 mImpl->mEventData->mPrimaryCursorPosition = 0;
2025 // The natural size needs to be re-calculated.
2026 mImpl->mRecalculateNaturalSize = true;
2028 // Apply modifications to the model
2029 mImpl->mOperationsPending = ALL_OPERATIONS;
2031 // Update the rest of the model during size negotiation
2032 mImpl->QueueModifyEvent( ModifyEvent::TEXT_REPLACED );
2036 void Controller::ClearModelData()
2038 // n.b. This does not Clear the mText from mLogicalModel
2039 mImpl->mLogicalModel->mScriptRuns.Clear();
2040 mImpl->mLogicalModel->mFontRuns.Clear();
2041 mImpl->mLogicalModel->mLineBreakInfo.Clear();
2042 mImpl->mLogicalModel->mWordBreakInfo.Clear();
2043 mImpl->mLogicalModel->mBidirectionalParagraphInfo.Clear();
2044 mImpl->mLogicalModel->mCharacterDirections.Clear();
2045 mImpl->mLogicalModel->mBidirectionalLineInfo.Clear();
2046 mImpl->mLogicalModel->mLogicalToVisualMap.Clear();
2047 mImpl->mLogicalModel->mVisualToLogicalMap.Clear();
2048 mImpl->mVisualModel->mGlyphs.Clear();
2049 mImpl->mVisualModel->mGlyphsToCharacters.Clear();
2050 mImpl->mVisualModel->mCharactersToGlyph.Clear();
2051 mImpl->mVisualModel->mCharactersPerGlyph.Clear();
2052 mImpl->mVisualModel->mGlyphsPerCharacter.Clear();
2053 mImpl->mVisualModel->mGlyphPositions.Clear();
2054 mImpl->mVisualModel->mLines.Clear();
2055 mImpl->mVisualModel->ClearCaches();
2058 void Controller::ClearFontData()
2060 mImpl->mFontDefaults->mFontId = 0u; // Remove old font ID
2061 mImpl->mLogicalModel->mFontRuns.Clear();
2062 mImpl->mVisualModel->mGlyphs.Clear();
2063 mImpl->mVisualModel->mGlyphsToCharacters.Clear();
2064 mImpl->mVisualModel->mCharactersToGlyph.Clear();
2065 mImpl->mVisualModel->mCharactersPerGlyph.Clear();
2066 mImpl->mVisualModel->mGlyphsPerCharacter.Clear();
2067 mImpl->mVisualModel->mGlyphPositions.Clear();
2068 mImpl->mVisualModel->mLines.Clear();
2069 mImpl->mVisualModel->ClearCaches();
2072 Controller::Controller( ControlInterface& controlInterface )
2075 mImpl = new Controller::Impl( controlInterface );
2080 } // namespace Toolkit