2 * Copyright (c) 2015 Samsung Electronics Co., Ltd.
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
8 * http://www.apache.org/licenses/LICENSE-2.0
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
19 #include <dali-toolkit/internal/text/text-controller.h>
23 #include <dali/public-api/adaptor-framework/key.h>
24 #include <dali/integration-api/debug.h>
25 #include <dali/devel-api/adaptor-framework/clipboard-event-notifier.h>
28 #include <dali-toolkit/internal/text/bidirectional-support.h>
29 #include <dali-toolkit/internal/text/character-set-conversion.h>
30 #include <dali-toolkit/internal/text/layouts/layout-parameters.h>
31 #include <dali-toolkit/internal/text/markup-processor.h>
32 #include <dali-toolkit/internal/text/text-controller-impl.h>
37 #if defined(DEBUG_ENABLED)
38 Debug::Filter* gLogFilter = Debug::Filter::New(Debug::NoLogging, true, "LOG_TEXT_CONTROLS");
41 const float MAX_FLOAT = std::numeric_limits<float>::max();
42 const unsigned int POINTS_PER_INCH = 72;
44 const std::string EMPTY_STRING("");
45 const unsigned int ZERO = 0u;
47 float ConvertToEven( float value )
49 int intValue(static_cast<int>( value ));
50 return static_cast<float>(intValue % 2 == 0) ? intValue : (intValue + 1);
64 ControllerPtr Controller::New( ControlInterface& controlInterface )
66 return ControllerPtr( new Controller( controlInterface ) );
69 void Controller::EnableTextInput( DecoratorPtr decorator )
71 if( !mImpl->mEventData )
73 mImpl->mEventData = new EventData( decorator );
77 void Controller::SetMarkupProcessorEnabled( bool enable )
79 mImpl->mMarkupProcessorEnabled = enable;
82 bool Controller::IsMarkupProcessorEnabled() const
84 return mImpl->mMarkupProcessorEnabled;
87 void Controller::SetText( const std::string& text )
89 DALI_LOG_INFO( gLogFilter, Debug::Verbose, "Controller::SetText\n" );
91 // Reset keyboard as text changed
92 mImpl->ResetImfManager();
94 // Remove the previously set text and style.
100 CharacterIndex lastCursorIndex = 0u;
102 if( mImpl->mEventData )
104 // If popup shown then hide it by switching to Editing state
105 if( ( EventData::SELECTING == mImpl->mEventData->mState ) ||
106 ( EventData::EDITING_WITH_POPUP == mImpl->mEventData->mState ) ||
107 ( EventData::EDITING_WITH_GRAB_HANDLE == mImpl->mEventData->mState ) ||
108 ( EventData::EDITING_WITH_PASTE_POPUP == mImpl->mEventData->mState ) )
110 mImpl->ChangeState( EventData::EDITING );
116 MarkupProcessData markupProcessData( mImpl->mLogicalModel->mColorRuns );
118 Length textSize = 0u;
119 const uint8_t* utf8 = NULL;
120 if( mImpl->mMarkupProcessorEnabled )
122 ProcessMarkupString( text, markupProcessData );
123 textSize = markupProcessData.markupProcessedText.size();
125 // This is a bit horrible but std::string returns a (signed) char*
126 utf8 = reinterpret_cast<const uint8_t*>( markupProcessData.markupProcessedText.c_str() );
130 textSize = text.size();
132 // This is a bit horrible but std::string returns a (signed) char*
133 utf8 = reinterpret_cast<const uint8_t*>( text.c_str() );
136 // Convert text into UTF-32
137 Vector<Character>& utf32Characters = mImpl->mLogicalModel->mText;
138 utf32Characters.Resize( textSize );
140 // Transform a text array encoded in utf8 into an array encoded in utf32.
141 // It returns the actual number of characters.
142 Length characterCount = Utf8ToUtf32( utf8, textSize, utf32Characters.Begin() );
143 utf32Characters.Resize( characterCount );
145 DALI_ASSERT_DEBUG( textSize >= characterCount && "Invalid UTF32 conversion length" );
146 DALI_LOG_INFO( gLogFilter, Debug::Verbose, "Controller::SetText %p UTF8 size %d, UTF32 size %d\n", this, textSize, mImpl->mLogicalModel->mText.Count() );
148 // To reset the cursor position
149 lastCursorIndex = characterCount;
151 // Update the rest of the model during size negotiation
152 mImpl->QueueModifyEvent( ModifyEvent::TEXT_REPLACED );
154 // The natural size needs to be re-calculated.
155 mImpl->mRecalculateNaturalSize = true;
157 // Apply modifications to the model
158 mImpl->mOperationsPending = ALL_OPERATIONS;
162 ShowPlaceholderText();
165 // Resets the cursor position.
166 ResetCursorPosition( lastCursorIndex );
168 // Scrolls the text to make the cursor visible.
169 ResetScrollPosition();
171 mImpl->RequestRelayout();
173 if( mImpl->mEventData )
175 // Cancel previously queued events
176 mImpl->mEventData->mEventQueue.clear();
179 // Notify IMF as text changed
182 // Do this last since it provides callbacks into application code
183 mImpl->mControlInterface.TextChanged();
186 void Controller::GetText( std::string& text ) const
188 if( ! mImpl->IsShowingPlaceholderText() )
190 Vector<Character>& utf32Characters = mImpl->mLogicalModel->mText;
192 if( 0u != utf32Characters.Count() )
194 Utf32ToUtf8( &utf32Characters[0], utf32Characters.Count(), text );
199 DALI_LOG_INFO( gLogFilter, Debug::Verbose, "Controller::GetText %p empty (but showing placeholder)\n", this );
203 unsigned int Controller::GetLogicalCursorPosition() const
205 if( mImpl->mEventData )
207 return mImpl->mEventData->mPrimaryCursorPosition;
213 void Controller::SetPlaceholderText( PlaceholderType type, const std::string& text )
215 if( mImpl->mEventData )
217 if( PLACEHOLDER_TYPE_INACTIVE == type )
219 mImpl->mEventData->mPlaceholderTextInactive = text;
223 mImpl->mEventData->mPlaceholderTextActive = text;
226 // Update placeholder if there is no text
227 if( mImpl->IsShowingPlaceholderText() ||
228 0u == mImpl->mLogicalModel->mText.Count() )
230 ShowPlaceholderText();
235 void Controller::GetPlaceholderText( PlaceholderType type, std::string& text ) const
237 if( mImpl->mEventData )
239 if( PLACEHOLDER_TYPE_INACTIVE == type )
241 text = mImpl->mEventData->mPlaceholderTextInactive;
245 text = mImpl->mEventData->mPlaceholderTextActive;
250 void Controller::SetMaximumNumberOfCharacters( int maxCharacters )
252 if ( maxCharacters >= 0 )
254 mImpl->mMaximumNumberOfCharacters = maxCharacters;
258 int Controller::GetMaximumNumberOfCharacters()
260 return mImpl->mMaximumNumberOfCharacters;
263 void Controller::SetDefaultFontFamily( const std::string& defaultFontFamily )
265 if( !mImpl->mFontDefaults )
267 mImpl->mFontDefaults = new FontDefaults();
270 mImpl->mFontDefaults->mFontDescription.family = defaultFontFamily;
271 DALI_LOG_INFO( gLogFilter, Debug::General, "Controller::SetDefaultFontFamily %s\n", defaultFontFamily.c_str());
272 mImpl->mUserDefinedFontFamily = true;
274 // Clear the font-specific data
277 mImpl->mOperationsPending = ALL_OPERATIONS;
278 mImpl->mRecalculateNaturalSize = true;
280 mImpl->RequestRelayout();
283 const std::string& Controller::GetDefaultFontFamily() const
285 if( mImpl->mFontDefaults )
287 return mImpl->mFontDefaults->mFontDescription.family;
293 void Controller::SetDefaultFontStyle( const std::string& style )
295 if( !mImpl->mFontDefaults )
297 mImpl->mFontDefaults = new FontDefaults();
300 mImpl->mFontDefaults->mFontStyle = style;
303 const std::string& Controller::GetDefaultFontStyle() const
305 if( mImpl->mFontDefaults )
307 return mImpl->mFontDefaults->mFontStyle;
313 void Controller::SetDefaultFontWidth( FontWidth width )
315 if( !mImpl->mFontDefaults )
317 mImpl->mFontDefaults = new FontDefaults();
320 mImpl->mFontDefaults->mFontDescription.width = width;
322 // Clear the font-specific data
325 mImpl->mOperationsPending = ALL_OPERATIONS;
326 mImpl->mRecalculateNaturalSize = true;
328 mImpl->RequestRelayout();
331 FontWidth Controller::GetDefaultFontWidth() const
333 if( mImpl->mFontDefaults )
335 return mImpl->mFontDefaults->mFontDescription.width;
338 return TextAbstraction::FontWidth::NORMAL;
341 void Controller::SetDefaultFontWeight( FontWeight weight )
343 if( !mImpl->mFontDefaults )
345 mImpl->mFontDefaults = new FontDefaults();
348 mImpl->mFontDefaults->mFontDescription.weight = weight;
350 // Clear the font-specific data
353 mImpl->mOperationsPending = ALL_OPERATIONS;
354 mImpl->mRecalculateNaturalSize = true;
356 mImpl->RequestRelayout();
359 FontWeight Controller::GetDefaultFontWeight() const
361 if( mImpl->mFontDefaults )
363 return mImpl->mFontDefaults->mFontDescription.weight;
366 return TextAbstraction::FontWeight::NORMAL;
369 void Controller::SetDefaultFontSlant( FontSlant slant )
371 if( !mImpl->mFontDefaults )
373 mImpl->mFontDefaults = new FontDefaults();
376 mImpl->mFontDefaults->mFontDescription.slant = slant;
378 // Clear the font-specific data
381 mImpl->mOperationsPending = ALL_OPERATIONS;
382 mImpl->mRecalculateNaturalSize = true;
384 mImpl->RequestRelayout();
387 FontSlant Controller::GetDefaultFontSlant() const
389 if( mImpl->mFontDefaults )
391 return mImpl->mFontDefaults->mFontDescription.slant;
394 return TextAbstraction::FontSlant::NORMAL;
397 void Controller::SetDefaultPointSize( float pointSize )
399 if( !mImpl->mFontDefaults )
401 mImpl->mFontDefaults = new FontDefaults();
404 mImpl->mFontDefaults->mDefaultPointSize = pointSize;
406 unsigned int horizontalDpi( 0u );
407 unsigned int verticalDpi( 0u );
408 mImpl->mFontClient.GetDpi( horizontalDpi, verticalDpi );
410 // Adjust the metrics if the fixed-size font should be down-scaled
411 int maxEmojiSize( pointSize/POINTS_PER_INCH * verticalDpi );
412 DALI_LOG_INFO( gLogFilter, Debug::General, "Controller::SetDefaultPointSize %p setting MaxEmojiSize %d\n", this, maxEmojiSize );
413 mImpl->mMetrics->SetMaxEmojiSize( maxEmojiSize );
415 // Clear the font-specific data
418 mImpl->mOperationsPending = ALL_OPERATIONS;
419 mImpl->mRecalculateNaturalSize = true;
421 mImpl->RequestRelayout();
424 float Controller::GetDefaultPointSize() const
426 if( mImpl->mFontDefaults )
428 return mImpl->mFontDefaults->mDefaultPointSize;
434 void Controller::UpdateAfterFontChange( std::string& newDefaultFont )
436 DALI_LOG_INFO( gLogFilter, Debug::Concise, "Controller::UpdateAfterFontChange");
438 if ( !mImpl->mUserDefinedFontFamily ) // If user defined font then should not update when system font changes
440 DALI_LOG_INFO( gLogFilter, Debug::Concise, "Controller::UpdateAfterFontChange newDefaultFont(%s)\n", newDefaultFont.c_str() );
442 mImpl->mFontDefaults->mFontDescription.family = newDefaultFont;
443 mImpl->UpdateModel( ALL_OPERATIONS );
444 mImpl->QueueModifyEvent( ModifyEvent::TEXT_REPLACED );
445 mImpl->mRecalculateNaturalSize = true;
446 mImpl->RequestRelayout();
450 void Controller::SetTextColor( const Vector4& textColor )
452 mImpl->mTextColor = textColor;
454 if( !mImpl->IsShowingPlaceholderText() )
456 mImpl->mVisualModel->SetTextColor( textColor );
458 mImpl->RequestRelayout();
462 const Vector4& Controller::GetTextColor() const
464 return mImpl->mTextColor;
467 bool Controller::RemoveText( int cursorOffset, int numberOfChars )
469 bool removed( false );
471 DALI_LOG_INFO( gLogFilter, Debug::General, "Controller::RemoveText %p mText.Count() %d cursor %d cursorOffset %d numberOfChars %d\n",
472 this, mImpl->mLogicalModel->mText.Count(), mImpl->mEventData->mPrimaryCursorPosition, cursorOffset, numberOfChars );
474 if( !mImpl->IsShowingPlaceholderText() )
476 // Delete at current cursor position
477 Vector<Character>& currentText = mImpl->mLogicalModel->mText;
478 CharacterIndex& oldCursorIndex = mImpl->mEventData->mPrimaryCursorPosition;
480 CharacterIndex cursorIndex = oldCursorIndex;
482 // Validate the cursor position & number of characters
483 if( static_cast< CharacterIndex >( std::abs( cursorOffset ) ) <= cursorIndex )
485 cursorIndex = oldCursorIndex + cursorOffset;
488 if( ( cursorIndex + numberOfChars ) > currentText.Count() )
490 numberOfChars = currentText.Count() - cursorIndex;
493 if( ( cursorIndex + numberOfChars ) <= currentText.Count() )
495 // Update the input style and remove the text's style before removing the text.
496 if( mImpl->mEventData )
498 // Set first the default input style.
499 mImpl->RetrieveDefaultInputStyle( mImpl->mEventData->mInputStyle );
501 // Update the input style.
502 mImpl->mLogicalModel->RetrieveStyle( cursorIndex, mImpl->mEventData->mInputStyle );
504 // Remove the text's style before removing the text.
505 mImpl->mLogicalModel->UpdateTextStyleRuns( cursorIndex, -numberOfChars );
508 // Remove the characters.
509 Vector<Character>::Iterator first = currentText.Begin() + cursorIndex;
510 Vector<Character>::Iterator last = first + numberOfChars;
512 currentText.Erase( first, last );
514 // Cursor position retreat
515 oldCursorIndex = cursorIndex;
517 DALI_LOG_INFO( gLogFilter, Debug::General, "Controller::RemoveText %p removed %d\n", this, numberOfChars );
525 void Controller::SetPlaceholderTextColor( const Vector4& textColor )
527 if( mImpl->mEventData )
529 mImpl->mEventData->mPlaceholderTextColor = textColor;
532 if( mImpl->IsShowingPlaceholderText() )
534 mImpl->mVisualModel->SetTextColor( textColor );
535 mImpl->RequestRelayout();
539 const Vector4& Controller::GetPlaceholderTextColor() const
541 if( mImpl->mEventData )
543 return mImpl->mEventData->mPlaceholderTextColor;
549 void Controller::SetShadowOffset( const Vector2& shadowOffset )
551 mImpl->mVisualModel->SetShadowOffset( shadowOffset );
553 mImpl->RequestRelayout();
556 const Vector2& Controller::GetShadowOffset() const
558 return mImpl->mVisualModel->GetShadowOffset();
561 void Controller::SetShadowColor( const Vector4& shadowColor )
563 mImpl->mVisualModel->SetShadowColor( shadowColor );
565 mImpl->RequestRelayout();
568 const Vector4& Controller::GetShadowColor() const
570 return mImpl->mVisualModel->GetShadowColor();
573 void Controller::SetUnderlineColor( const Vector4& color )
575 mImpl->mVisualModel->SetUnderlineColor( color );
577 mImpl->RequestRelayout();
580 const Vector4& Controller::GetUnderlineColor() const
582 return mImpl->mVisualModel->GetUnderlineColor();
585 void Controller::SetUnderlineEnabled( bool enabled )
587 mImpl->mVisualModel->SetUnderlineEnabled( enabled );
589 mImpl->RequestRelayout();
592 bool Controller::IsUnderlineEnabled() const
594 return mImpl->mVisualModel->IsUnderlineEnabled();
597 void Controller::SetUnderlineHeight( float height )
599 mImpl->mVisualModel->SetUnderlineHeight( height );
601 mImpl->RequestRelayout();
604 float Controller::GetUnderlineHeight() const
606 return mImpl->mVisualModel->GetUnderlineHeight();
609 void Controller::SetInputColor( const Vector4& color )
611 if( mImpl->mEventData )
613 mImpl->mEventData->mInputStyle.textColor = color;
615 if( EventData::SELECTING == mImpl->mEventData->mState )
617 const bool handlesCrossed = mImpl->mEventData->mLeftSelectionPosition > mImpl->mEventData->mRightSelectionPosition;
619 // Get start and end position of selection
620 const CharacterIndex startOfSelectedText = handlesCrossed ? mImpl->mEventData->mRightSelectionPosition : mImpl->mEventData->mLeftSelectionPosition;
621 const Length lengthOfSelectedText = ( handlesCrossed ? mImpl->mEventData->mLeftSelectionPosition : mImpl->mEventData->mRightSelectionPosition ) - startOfSelectedText;
623 // Add the color run.
624 const VectorBase::SizeType numberOfRuns = mImpl->mLogicalModel->mColorRuns.Count();
625 mImpl->mLogicalModel->mColorRuns.Resize( numberOfRuns + 1u );
627 ColorRun& colorRun = *( mImpl->mLogicalModel->mColorRuns.Begin() + numberOfRuns );
628 colorRun.color = color;
629 colorRun.characterRun.characterIndex = startOfSelectedText;
630 colorRun.characterRun.numberOfCharacters = lengthOfSelectedText;
632 // Request to relayout.
633 mImpl->mOperationsPending = static_cast<OperationsMask>( mImpl->mOperationsPending | COLOR );
634 mImpl->RequestRelayout();
639 const Vector4& Controller::GetInputColor() const
641 if( mImpl->mEventData )
643 return mImpl->mEventData->mInputStyle.textColor;
646 // Return the default text's color if there is no EventData.
647 return mImpl->mTextColor;
651 void Controller::SetEnableCursorBlink( bool enable )
653 DALI_ASSERT_DEBUG( NULL != mImpl->mEventData && "TextInput disabled" );
655 if( mImpl->mEventData )
657 mImpl->mEventData->mCursorBlinkEnabled = enable;
660 mImpl->mEventData->mDecorator )
662 mImpl->mEventData->mDecorator->StopCursorBlink();
667 bool Controller::GetEnableCursorBlink() const
669 if( mImpl->mEventData )
671 return mImpl->mEventData->mCursorBlinkEnabled;
677 const Vector2& Controller::GetScrollPosition() const
679 if( mImpl->mEventData )
681 return mImpl->mEventData->mScrollPosition;
684 return Vector2::ZERO;
687 const Vector2& Controller::GetAlignmentOffset() const
689 return mImpl->mAlignmentOffset;
692 Vector3 Controller::GetNaturalSize()
694 DALI_LOG_INFO( gLogFilter, Debug::Verbose, "-->Controller::GetNaturalSize\n" );
697 // Make sure the model is up-to-date before layouting
698 ProcessModifyEvents();
700 if( mImpl->mRecalculateNaturalSize )
702 // Operations that can be done only once until the text changes.
703 const OperationsMask onlyOnceOperations = static_cast<OperationsMask>( CONVERT_TO_UTF32 |
711 // Make sure the model is up-to-date before layouting
712 mImpl->UpdateModel( onlyOnceOperations );
714 // Operations that need to be done if the size changes.
715 const OperationsMask sizeOperations = static_cast<OperationsMask>( LAYOUT |
719 DoRelayout( Size( MAX_FLOAT, MAX_FLOAT ),
720 static_cast<OperationsMask>( onlyOnceOperations |
722 naturalSize.GetVectorXY() );
724 // Do not do again the only once operations.
725 mImpl->mOperationsPending = static_cast<OperationsMask>( mImpl->mOperationsPending & ~onlyOnceOperations );
727 // Do the size related operations again.
728 mImpl->mOperationsPending = static_cast<OperationsMask>( mImpl->mOperationsPending | sizeOperations );
730 // Stores the natural size to avoid recalculate it again
731 // unless the text/style changes.
732 mImpl->mVisualModel->SetNaturalSize( naturalSize.GetVectorXY() );
734 mImpl->mRecalculateNaturalSize = false;
736 DALI_LOG_INFO( gLogFilter, Debug::Verbose, "<--Controller::GetNaturalSize calculated %f,%f,%f\n", naturalSize.x, naturalSize.y, naturalSize.z );
740 naturalSize = mImpl->mVisualModel->GetNaturalSize();
742 DALI_LOG_INFO( gLogFilter, Debug::Verbose, "<--Controller::GetNaturalSize cached %f,%f,%f\n", naturalSize.x, naturalSize.y, naturalSize.z );
745 naturalSize.x = ConvertToEven( naturalSize.x );
746 naturalSize.y = ConvertToEven( naturalSize.y );
751 float Controller::GetHeightForWidth( float width )
753 DALI_LOG_INFO( gLogFilter, Debug::Verbose, "-->Controller::GetHeightForWidth %p width %f\n", this, width );
754 // Make sure the model is up-to-date before layouting
755 ProcessModifyEvents();
758 if( fabsf( width - mImpl->mVisualModel->mControlSize.width ) > Math::MACHINE_EPSILON_1000 )
760 // Operations that can be done only once until the text changes.
761 const OperationsMask onlyOnceOperations = static_cast<OperationsMask>( CONVERT_TO_UTF32 |
769 // Make sure the model is up-to-date before layouting
770 mImpl->UpdateModel( onlyOnceOperations );
772 // Operations that need to be done if the size changes.
773 const OperationsMask sizeOperations = static_cast<OperationsMask>( LAYOUT |
777 DoRelayout( Size( width, MAX_FLOAT ),
778 static_cast<OperationsMask>( onlyOnceOperations |
782 // Do not do again the only once operations.
783 mImpl->mOperationsPending = static_cast<OperationsMask>( mImpl->mOperationsPending & ~onlyOnceOperations );
785 // Do the size related operations again.
786 mImpl->mOperationsPending = static_cast<OperationsMask>( mImpl->mOperationsPending | sizeOperations );
787 DALI_LOG_INFO( gLogFilter, Debug::Verbose, "<--Controller::GetHeightForWidth calculated %f\n", layoutSize.height );
791 layoutSize = mImpl->mVisualModel->GetActualSize();
792 DALI_LOG_INFO( gLogFilter, Debug::Verbose, "<--Controller::GetHeightForWidth cached %f\n", layoutSize.height );
795 return layoutSize.height;
798 bool Controller::Relayout( const Size& size )
800 DALI_LOG_INFO( gLogFilter, Debug::Verbose, "-->Controller::Relayout %p size %f,%f\n", this, size.width, size.height );
802 if( ( size.width < Math::MACHINE_EPSILON_1000 ) || ( size.height < Math::MACHINE_EPSILON_1000 ) )
804 bool glyphsRemoved( false );
805 if( 0u != mImpl->mVisualModel->mGlyphPositions.Count() )
807 mImpl->mVisualModel->mGlyphPositions.Clear();
808 glyphsRemoved = true;
810 // Not worth to relayout if width or height is equal to zero.
811 DALI_LOG_INFO( gLogFilter, Debug::Verbose, "<--Controller::Relayout (skipped)\n" );
812 return glyphsRemoved;
815 const bool newSize = ( size != mImpl->mVisualModel->mControlSize );
819 DALI_LOG_INFO( gLogFilter, Debug::Verbose, "new size (previous size %f,%f)\n", mImpl->mVisualModel->mControlSize.width, mImpl->mVisualModel->mControlSize.height );
821 // Layout operations that need to be done if the size changes.
822 mImpl->mOperationsPending = static_cast<OperationsMask>( mImpl->mOperationsPending |
828 mImpl->mVisualModel->mControlSize = size;
831 // Whether there are modify events.
832 const bool isModifyEventsEmpty = 0u == mImpl->mModifyEvents.Count();
834 // Make sure the model is up-to-date before layouting.
835 ProcessModifyEvents();
836 mImpl->UpdateModel( mImpl->mOperationsPending );
838 // Style operations that need to be done if the text is modified.
839 if( !isModifyEventsEmpty )
841 mImpl->mOperationsPending = static_cast<OperationsMask>( mImpl->mOperationsPending |
845 // Apply the style runs if text is modified.
846 bool updated = mImpl->UpdateModelStyle( mImpl->mOperationsPending );
850 updated = DoRelayout( mImpl->mVisualModel->mControlSize,
851 mImpl->mOperationsPending,
852 layoutSize ) || updated;
854 // Do not re-do any operation until something changes.
855 mImpl->mOperationsPending = NO_OPERATION;
857 // Keep the current offset and alignment as it will be used to update the decorator's positions (if the size changes).
859 if( newSize && mImpl->mEventData )
861 offset = mImpl->mAlignmentOffset + mImpl->mEventData->mScrollPosition;
864 // After doing the text layout, the alignment offset to place the actor in the desired position can be calculated.
865 CalculateTextAlignment( size );
867 if( mImpl->mEventData )
871 // If there is a new size, the scroll position needs to be clamped.
872 mImpl->ClampHorizontalScroll( layoutSize );
874 // Update the decorator's positions is needed if there is a new size.
875 mImpl->mEventData->mDecorator->UpdatePositions( mImpl->mAlignmentOffset + mImpl->mEventData->mScrollPosition - offset );
878 // Move the cursor, grab handle etc.
879 updated = mImpl->ProcessInputEvents() || updated;
882 DALI_LOG_INFO( gLogFilter, Debug::Verbose, "<--Controller::Relayout\n" );
886 void Controller::ProcessModifyEvents()
888 Vector<ModifyEvent>& events = mImpl->mModifyEvents;
890 if( 0u == events.Count() )
896 for( Vector<ModifyEvent>::ConstIterator it = events.Begin(),
897 endIt = events.End();
901 const ModifyEvent& event = *it;
903 if( ModifyEvent::TEXT_REPLACED == event.type )
905 // A (single) replace event should come first, otherwise we wasted time processing NOOP events
906 DALI_ASSERT_DEBUG( it == events.Begin() && "Unexpected TEXT_REPLACED event" );
910 else if( ModifyEvent::TEXT_INSERTED == event.type )
914 else if( ModifyEvent::TEXT_DELETED == event.type )
916 // Placeholder-text cannot be deleted
917 if( !mImpl->IsShowingPlaceholderText() )
924 if( mImpl->mEventData )
926 // When the text is being modified, delay cursor blinking
927 mImpl->mEventData->mDecorator->DelayCursorBlink();
930 // Discard temporary text
934 void Controller::ResetText()
937 mImpl->mLogicalModel->mText.Clear();
940 // We have cleared everything including the placeholder-text
941 mImpl->PlaceholderCleared();
943 // The natural size needs to be re-calculated.
944 mImpl->mRecalculateNaturalSize = true;
946 // Apply modifications to the model
947 mImpl->mOperationsPending = ALL_OPERATIONS;
950 void Controller::ResetCursorPosition( CharacterIndex cursorIndex )
952 // Reset the cursor position
953 if( NULL != mImpl->mEventData )
955 mImpl->mEventData->mPrimaryCursorPosition = cursorIndex;
957 // Update the cursor if it's in editing mode.
958 if ( EventData::IsEditingState( mImpl->mEventData->mState ) )
960 mImpl->mEventData->mUpdateCursorPosition = true;
965 void Controller::ResetScrollPosition()
967 if( NULL != mImpl->mEventData )
969 // Reset the scroll position.
970 mImpl->mEventData->mScrollPosition = Vector2::ZERO;
971 mImpl->mEventData->mScrollAfterUpdatePosition = true;
975 void Controller::TextReplacedEvent()
980 // The natural size needs to be re-calculated.
981 mImpl->mRecalculateNaturalSize = true;
983 // Apply modifications to the model
984 mImpl->mOperationsPending = ALL_OPERATIONS;
985 mImpl->UpdateModel( ALL_OPERATIONS );
986 mImpl->mOperationsPending = static_cast<OperationsMask>( LAYOUT |
992 void Controller::TextInsertedEvent()
994 DALI_ASSERT_DEBUG( NULL != mImpl->mEventData && "Unexpected TextInsertedEvent" );
996 // TODO - Optimize this
999 // The natural size needs to be re-calculated.
1000 mImpl->mRecalculateNaturalSize = true;
1002 // Apply modifications to the model; TODO - Optimize this
1003 mImpl->mOperationsPending = ALL_OPERATIONS;
1004 mImpl->UpdateModel( ALL_OPERATIONS );
1005 mImpl->mOperationsPending = static_cast<OperationsMask>( LAYOUT |
1007 UPDATE_ACTUAL_SIZE |
1010 // Queue a cursor reposition event; this must wait until after DoRelayout()
1011 if ( EventData::IsEditingState( mImpl->mEventData->mState ) )
1013 mImpl->mEventData->mUpdateCursorPosition = true;
1014 mImpl->mEventData->mScrollAfterUpdatePosition = true;
1018 void Controller::TextDeletedEvent()
1020 DALI_ASSERT_DEBUG( NULL != mImpl->mEventData && "Unexpected TextDeletedEvent" );
1022 // TODO - Optimize this
1025 // The natural size needs to be re-calculated.
1026 mImpl->mRecalculateNaturalSize = true;
1028 // Apply modifications to the model; TODO - Optimize this
1029 mImpl->mOperationsPending = ALL_OPERATIONS;
1030 mImpl->UpdateModel( ALL_OPERATIONS );
1031 mImpl->mOperationsPending = static_cast<OperationsMask>( LAYOUT |
1033 UPDATE_ACTUAL_SIZE |
1036 // Queue a cursor reposition event; this must wait until after DoRelayout()
1037 mImpl->mEventData->mUpdateCursorPosition = true;
1038 if( 0u != mImpl->mLogicalModel->mText.Count() )
1040 mImpl->mEventData->mScrollAfterDelete = true;
1044 bool Controller::DoRelayout( const Size& size,
1045 OperationsMask operationsRequired,
1048 DALI_LOG_INFO( gLogFilter, Debug::Verbose, "-->Controller::DoRelayout %p size %f,%f\n", this, size.width, size.height );
1049 bool viewUpdated( false );
1051 // Calculate the operations to be done.
1052 const OperationsMask operations = static_cast<OperationsMask>( mImpl->mOperationsPending & operationsRequired );
1054 if( LAYOUT & operations )
1056 // Some vectors with data needed to layout and reorder may be void
1057 // after the first time the text has been laid out.
1058 // Fill the vectors again.
1060 const Length numberOfGlyphs = mImpl->mVisualModel->mGlyphs.Count();
1062 if( 0u == numberOfGlyphs )
1064 // Nothing else to do if there is no glyphs.
1065 DALI_LOG_INFO( gLogFilter, Debug::Verbose, "<--Controller::DoRelayout no glyphs, view updated true\n" );
1069 const Vector<LineBreakInfo>& lineBreakInfo = mImpl->mLogicalModel->mLineBreakInfo;
1070 const Vector<WordBreakInfo>& wordBreakInfo = mImpl->mLogicalModel->mWordBreakInfo;
1071 const Vector<CharacterDirection>& characterDirection = mImpl->mLogicalModel->mCharacterDirections;
1072 const Vector<GlyphInfo>& glyphs = mImpl->mVisualModel->mGlyphs;
1073 const Vector<CharacterIndex>& glyphsToCharactersMap = mImpl->mVisualModel->mGlyphsToCharacters;
1074 const Vector<Length>& charactersPerGlyph = mImpl->mVisualModel->mCharactersPerGlyph;
1075 const Character* const textBuffer = mImpl->mLogicalModel->mText.Begin();
1077 // Set the layout parameters.
1078 LayoutParameters layoutParameters( size,
1080 lineBreakInfo.Begin(),
1081 wordBreakInfo.Begin(),
1082 ( 0u != characterDirection.Count() ) ? characterDirection.Begin() : NULL,
1085 glyphsToCharactersMap.Begin(),
1086 charactersPerGlyph.Begin() );
1088 // The laid-out lines.
1089 // It's not possible to know in how many lines the text is going to be laid-out,
1090 // but it can be resized at least with the number of 'paragraphs' to avoid
1091 // some re-allocations.
1092 Vector<LineRun>& lines = mImpl->mVisualModel->mLines;
1094 // Delete any previous laid out lines before setting the new ones.
1097 // The capacity of the bidirectional paragraph info is the number of paragraphs.
1098 lines.Reserve( mImpl->mLogicalModel->mBidirectionalParagraphInfo.Capacity() );
1100 // Resize the vector of positions to have the same size than the vector of glyphs.
1101 Vector<Vector2>& glyphPositions = mImpl->mVisualModel->mGlyphPositions;
1102 glyphPositions.Resize( numberOfGlyphs );
1104 // Whether the last character is a new paragraph character.
1105 layoutParameters.isLastNewParagraph = TextAbstraction::IsNewParagraph( *( textBuffer + ( mImpl->mLogicalModel->mText.Count() - 1u ) ) );
1107 // Update the visual model.
1108 viewUpdated = mImpl->mLayoutEngine.LayoutText( layoutParameters,
1115 // Reorder the lines
1116 if( REORDER & operations )
1118 Vector<BidirectionalParagraphInfoRun>& bidirectionalInfo = mImpl->mLogicalModel->mBidirectionalParagraphInfo;
1120 // Check first if there are paragraphs with bidirectional info.
1121 if( 0u != bidirectionalInfo.Count() )
1124 const Length numberOfLines = mImpl->mVisualModel->mLines.Count();
1126 // Reorder the lines.
1127 Vector<BidirectionalLineInfoRun> lineBidirectionalInfoRuns;
1128 lineBidirectionalInfoRuns.Reserve( numberOfLines ); // Reserve because is not known yet how many lines have right to left characters.
1129 ReorderLines( bidirectionalInfo,
1131 lineBidirectionalInfoRuns );
1133 // Set the bidirectional info into the model.
1134 const Length numberOfBidirectionalInfoRuns = lineBidirectionalInfoRuns.Count();
1135 mImpl->mLogicalModel->SetVisualToLogicalMap( lineBidirectionalInfoRuns.Begin(),
1136 numberOfBidirectionalInfoRuns );
1138 // Set the bidirectional info per line into the layout parameters.
1139 layoutParameters.lineBidirectionalInfoRunsBuffer = lineBidirectionalInfoRuns.Begin();
1140 layoutParameters.numberOfBidirectionalInfoRuns = numberOfBidirectionalInfoRuns;
1142 // Get the character to glyph conversion table and set into the layout.
1143 layoutParameters.charactersToGlyphsBuffer = mImpl->mVisualModel->mCharactersToGlyph.Begin();
1145 // Get the glyphs per character table and set into the layout.
1146 layoutParameters.glyphsPerCharacterBuffer = mImpl->mVisualModel->mGlyphsPerCharacter.Begin();
1148 // Re-layout the text. Reorder those lines with right to left characters.
1149 mImpl->mLayoutEngine.ReLayoutRightToLeftLines( layoutParameters,
1152 // Free the allocated memory used to store the conversion table in the bidirectional line info run.
1153 for( Vector<BidirectionalLineInfoRun>::Iterator it = lineBidirectionalInfoRuns.Begin(),
1154 endIt = lineBidirectionalInfoRuns.End();
1158 BidirectionalLineInfoRun& bidiLineInfo = *it;
1160 free( bidiLineInfo.visualToLogicalMap );
1165 // Sets the actual size.
1166 if( UPDATE_ACTUAL_SIZE & operations )
1168 mImpl->mVisualModel->SetActualSize( layoutSize );
1174 layoutSize = mImpl->mVisualModel->GetActualSize();
1177 if( ALIGN & operations )
1179 // The laid-out lines.
1180 Vector<LineRun>& lines = mImpl->mVisualModel->mLines;
1182 mImpl->mLayoutEngine.Align( layoutSize,
1188 DALI_LOG_INFO( gLogFilter, Debug::Verbose, "<--Controller::DoRelayout, view updated %s\n", ( viewUpdated ? "true" : "false" ) );
1192 void Controller::SetMultiLineEnabled( bool enable )
1194 const LayoutEngine::Layout layout = enable ? LayoutEngine::MULTI_LINE_BOX : LayoutEngine::SINGLE_LINE_BOX;
1196 if( layout != mImpl->mLayoutEngine.GetLayout() )
1198 // Set the layout type.
1199 mImpl->mLayoutEngine.SetLayout( layout );
1201 // Set the flags to redo the layout operations
1202 const OperationsMask layoutOperations = static_cast<OperationsMask>( LAYOUT |
1203 UPDATE_ACTUAL_SIZE |
1207 mImpl->mOperationsPending = static_cast<OperationsMask>( mImpl->mOperationsPending | layoutOperations );
1209 mImpl->RequestRelayout();
1213 bool Controller::IsMultiLineEnabled() const
1215 return LayoutEngine::MULTI_LINE_BOX == mImpl->mLayoutEngine.GetLayout();
1218 void Controller::SetHorizontalAlignment( LayoutEngine::HorizontalAlignment alignment )
1220 if( alignment != mImpl->mLayoutEngine.GetHorizontalAlignment() )
1222 // Set the alignment.
1223 mImpl->mLayoutEngine.SetHorizontalAlignment( alignment );
1225 // Set the flag to redo the alignment operation.
1226 mImpl->mOperationsPending = static_cast<OperationsMask>( mImpl->mOperationsPending | ALIGN );
1228 mImpl->RequestRelayout();
1232 LayoutEngine::HorizontalAlignment Controller::GetHorizontalAlignment() const
1234 return mImpl->mLayoutEngine.GetHorizontalAlignment();
1237 void Controller::SetVerticalAlignment( LayoutEngine::VerticalAlignment alignment )
1239 if( alignment != mImpl->mLayoutEngine.GetVerticalAlignment() )
1241 // Set the alignment.
1242 mImpl->mLayoutEngine.SetVerticalAlignment( alignment );
1244 mImpl->mOperationsPending = static_cast<OperationsMask>( mImpl->mOperationsPending | ALIGN );
1246 mImpl->RequestRelayout();
1250 LayoutEngine::VerticalAlignment Controller::GetVerticalAlignment() const
1252 return mImpl->mLayoutEngine.GetVerticalAlignment();
1255 void Controller::CalculateTextAlignment( const Size& size )
1257 // Get the direction of the first character.
1258 const CharacterDirection firstParagraphDirection = mImpl->mLogicalModel->GetCharacterDirection( 0u );
1260 Size actualSize = mImpl->mVisualModel->GetActualSize();
1261 if( fabsf( actualSize.height ) < Math::MACHINE_EPSILON_1000 )
1263 // Get the line height of the default font.
1264 actualSize.height = mImpl->GetDefaultFontLineHeight();
1267 // If the first paragraph is right to left swap ALIGN_BEGIN and ALIGN_END;
1268 LayoutEngine::HorizontalAlignment horizontalAlignment = mImpl->mLayoutEngine.GetHorizontalAlignment();
1269 if( firstParagraphDirection &&
1270 ( LayoutEngine::HORIZONTAL_ALIGN_CENTER != horizontalAlignment ) )
1272 if( LayoutEngine::HORIZONTAL_ALIGN_BEGIN == horizontalAlignment )
1274 horizontalAlignment = LayoutEngine::HORIZONTAL_ALIGN_END;
1278 horizontalAlignment = LayoutEngine::HORIZONTAL_ALIGN_BEGIN;
1282 switch( horizontalAlignment )
1284 case LayoutEngine::HORIZONTAL_ALIGN_BEGIN:
1286 mImpl->mAlignmentOffset.x = 0.f;
1289 case LayoutEngine::HORIZONTAL_ALIGN_CENTER:
1291 mImpl->mAlignmentOffset.x = floorf( 0.5f * ( size.width - actualSize.width ) ); // try to avoid pixel alignment.
1294 case LayoutEngine::HORIZONTAL_ALIGN_END:
1296 mImpl->mAlignmentOffset.x = size.width - actualSize.width;
1301 const LayoutEngine::VerticalAlignment verticalAlignment = mImpl->mLayoutEngine.GetVerticalAlignment();
1302 switch( verticalAlignment )
1304 case LayoutEngine::VERTICAL_ALIGN_TOP:
1306 mImpl->mAlignmentOffset.y = 0.f;
1309 case LayoutEngine::VERTICAL_ALIGN_CENTER:
1311 mImpl->mAlignmentOffset.y = floorf( 0.5f * ( size.height - actualSize.height ) ); // try to avoid pixel alignment.
1314 case LayoutEngine::VERTICAL_ALIGN_BOTTOM:
1316 mImpl->mAlignmentOffset.y = size.height - actualSize.height;
1322 LayoutEngine& Controller::GetLayoutEngine()
1324 return mImpl->mLayoutEngine;
1327 View& Controller::GetView()
1329 return mImpl->mView;
1332 void Controller::KeyboardFocusGainEvent()
1334 DALI_ASSERT_DEBUG( mImpl->mEventData && "Unexpected KeyboardFocusGainEvent" );
1336 if( mImpl->mEventData )
1338 if( ( EventData::INACTIVE == mImpl->mEventData->mState ) ||
1339 ( EventData::INTERRUPTED == mImpl->mEventData->mState ) )
1341 mImpl->ChangeState( EventData::EDITING );
1342 mImpl->mEventData->mUpdateCursorPosition = true; //If editing started without tap event, cursor update must be triggered.
1345 if( mImpl->IsShowingPlaceholderText() )
1347 // Show alternative placeholder-text when editing
1348 ShowPlaceholderText();
1351 mImpl->RequestRelayout();
1355 void Controller::KeyboardFocusLostEvent()
1357 DALI_ASSERT_DEBUG( mImpl->mEventData && "Unexpected KeyboardFocusLostEvent" );
1359 if( mImpl->mEventData )
1361 if ( EventData::INTERRUPTED != mImpl->mEventData->mState )
1363 mImpl->ChangeState( EventData::INACTIVE );
1365 if( !mImpl->IsShowingRealText() )
1367 // Revert to regular placeholder-text when not editing
1368 ShowPlaceholderText();
1372 mImpl->RequestRelayout();
1375 bool Controller::KeyEvent( const Dali::KeyEvent& keyEvent )
1377 DALI_ASSERT_DEBUG( mImpl->mEventData && "Unexpected KeyEvent" );
1379 bool textChanged( false );
1381 if( mImpl->mEventData &&
1382 keyEvent.state == KeyEvent::Down )
1384 int keyCode = keyEvent.keyCode;
1385 const std::string& keyString = keyEvent.keyPressed;
1387 // Pre-process to separate modifying events from non-modifying input events.
1388 if( Dali::DALI_KEY_ESCAPE == keyCode )
1390 // Escape key is a special case which causes focus loss
1391 KeyboardFocusLostEvent();
1393 else if( Dali::DALI_KEY_CURSOR_LEFT == keyCode ||
1394 Dali::DALI_KEY_CURSOR_RIGHT == keyCode ||
1395 Dali::DALI_KEY_CURSOR_UP == keyCode ||
1396 Dali::DALI_KEY_CURSOR_DOWN == keyCode )
1398 Event event( Event::CURSOR_KEY_EVENT );
1399 event.p1.mInt = keyCode;
1400 mImpl->mEventData->mEventQueue.push_back( event );
1402 else if( Dali::DALI_KEY_BACKSPACE == keyCode )
1404 textChanged = BackspaceKeyEvent();
1406 else if ( IsKey( keyEvent, Dali::DALI_KEY_POWER ) )
1408 mImpl->ChangeState( EventData::INTERRUPTED ); // State is not INACTIVE as expect to return to edit mode.
1409 // Avoids calling the InsertText() method which can delete selected text
1411 else if ( IsKey( keyEvent, Dali::DALI_KEY_MENU ) ||
1412 IsKey( keyEvent, Dali::DALI_KEY_HOME ) )
1414 mImpl->ChangeState( EventData::INACTIVE );
1415 // Menu/Home key behaviour does not allow edit mode to resume like Power key
1416 // Avoids calling the InsertText() method which can delete selected text
1418 else if( Dali::DALI_KEY_SHIFT_LEFT == keyCode )
1420 // DALI_KEY_SHIFT_LEFT is the key code for the Left Shift. It's sent (by the imf?) when the predictive text is enabled
1421 // and a character is typed after the type of a upper case latin character.
1427 DALI_LOG_INFO( gLogFilter, Debug::Verbose, "Controller::KeyEvent %p keyString %s\n", this, keyString.c_str() );
1429 // IMF manager is no longer handling key-events
1430 mImpl->ClearPreEditFlag();
1432 InsertText( keyString, COMMIT );
1436 if ( ( mImpl->mEventData->mState != EventData::INTERRUPTED ) &&
1437 ( mImpl->mEventData->mState != EventData::INACTIVE ) )
1439 mImpl->ChangeState( EventData::EDITING );
1442 mImpl->RequestRelayout();
1447 // Do this last since it provides callbacks into application code
1448 mImpl->mControlInterface.TextChanged();
1454 void Controller::InsertText( const std::string& text, Controller::InsertType type )
1456 bool removedPrevious( false );
1457 bool maxLengthReached( false );
1459 DALI_ASSERT_DEBUG( NULL != mImpl->mEventData && "Unexpected InsertText" )
1460 DALI_LOG_INFO( gLogFilter, Debug::Verbose, "Controller::InsertText %p %s (%s) mPrimaryCursorPosition %d mPreEditFlag %d mPreEditStartPosition %d mPreEditLength %d\n",
1461 this, text.c_str(), (COMMIT == type ? "COMMIT" : "PRE_EDIT"),
1462 mImpl->mEventData->mPrimaryCursorPosition, mImpl->mEventData->mPreEditFlag, mImpl->mEventData->mPreEditStartPosition, mImpl->mEventData->mPreEditLength );
1464 // TODO: At the moment the underline runs are only for pre-edit.
1465 mImpl->mVisualModel->mUnderlineRuns.Clear();
1467 Vector<Character> utf32Characters;
1468 Length characterCount( 0u );
1470 // Remove the previous IMF pre-edit (predicitive text)
1471 if( mImpl->mEventData &&
1472 mImpl->mEventData->mPreEditFlag &&
1473 0 != mImpl->mEventData->mPreEditLength )
1475 CharacterIndex offset = mImpl->mEventData->mPrimaryCursorPosition - mImpl->mEventData->mPreEditStartPosition;
1477 removedPrevious = RemoveText( -static_cast<int>(offset), mImpl->mEventData->mPreEditLength );
1479 mImpl->mEventData->mPrimaryCursorPosition = mImpl->mEventData->mPreEditStartPosition;
1480 mImpl->mEventData->mPreEditLength = 0;
1484 // Remove the previous Selection
1485 removedPrevious = RemoveSelectedText();
1490 // Convert text into UTF-32
1491 utf32Characters.Resize( text.size() );
1493 // This is a bit horrible but std::string returns a (signed) char*
1494 const uint8_t* utf8 = reinterpret_cast<const uint8_t*>( text.c_str() );
1496 // Transform a text array encoded in utf8 into an array encoded in utf32.
1497 // It returns the actual number of characters.
1498 characterCount = Utf8ToUtf32( utf8, text.size(), utf32Characters.Begin() );
1499 utf32Characters.Resize( characterCount );
1501 DALI_ASSERT_DEBUG( text.size() >= utf32Characters.Count() && "Invalid UTF32 conversion length" );
1502 DALI_LOG_INFO( gLogFilter, Debug::Verbose, "UTF8 size %d, UTF32 size %d\n", text.size(), utf32Characters.Count() );
1505 if( 0u != utf32Characters.Count() ) // Check if Utf8ToUtf32 conversion succeeded
1507 // The placeholder text is no longer needed
1508 if( mImpl->IsShowingPlaceholderText() )
1513 mImpl->ChangeState( EventData::EDITING );
1515 // Handle the IMF (predicitive text) state changes
1516 if( mImpl->mEventData )
1518 if( COMMIT == type )
1520 // IMF manager is no longer handling key-events
1521 mImpl->ClearPreEditFlag();
1525 if( !mImpl->mEventData->mPreEditFlag )
1527 DALI_LOG_INFO( gLogFilter, Debug::Verbose, "Entered PreEdit state" );
1529 // Record the start of the pre-edit text
1530 mImpl->mEventData->mPreEditStartPosition = mImpl->mEventData->mPrimaryCursorPosition;
1533 mImpl->mEventData->mPreEditLength = utf32Characters.Count();
1534 mImpl->mEventData->mPreEditFlag = true;
1536 DALI_LOG_INFO( gLogFilter, Debug::Verbose, "mPreEditStartPosition %d mPreEditLength %d\n", mImpl->mEventData->mPreEditStartPosition, mImpl->mEventData->mPreEditLength );
1540 const Length numberOfCharactersInModel = mImpl->mLogicalModel->mText.Count();
1542 // Restrict new text to fit within Maximum characters setting
1543 Length maxSizeOfNewText = std::min ( ( mImpl->mMaximumNumberOfCharacters - numberOfCharactersInModel ), characterCount );
1544 maxLengthReached = ( characterCount > maxSizeOfNewText );
1546 // The cursor position.
1547 CharacterIndex& cursorIndex = mImpl->mEventData->mPrimaryCursorPosition;
1549 // Update the text's style.
1550 if( mImpl->mEventData )
1552 // Updates the text style runs.
1553 mImpl->mLogicalModel->UpdateTextStyleRuns( cursorIndex, maxSizeOfNewText );
1555 // Get the character index from the cursor index.
1556 const CharacterIndex styleIndex = ( cursorIndex > 0u ) ? cursorIndex - 1u : 0u;
1558 // Retrieve the text's style for the given index.
1560 mImpl->mLogicalModel->RetrieveStyle( styleIndex, style );
1562 // Whether to add a new text color run.
1563 const bool addColorRun = style.textColor != mImpl->mEventData->mInputStyle.textColor;
1568 const VectorBase::SizeType numberOfRuns = mImpl->mLogicalModel->mColorRuns.Count();
1569 mImpl->mLogicalModel->mColorRuns.Resize( numberOfRuns + 1u );
1571 ColorRun& colorRun = *( mImpl->mLogicalModel->mColorRuns.Begin() + numberOfRuns );
1572 colorRun.color = mImpl->mEventData->mInputStyle.textColor;
1573 colorRun.characterRun.characterIndex = cursorIndex;
1574 colorRun.characterRun.numberOfCharacters = maxSizeOfNewText;
1578 // Insert at current cursor position.
1579 Vector<Character>& modifyText = mImpl->mLogicalModel->mText;
1581 if( cursorIndex < numberOfCharactersInModel )
1583 modifyText.Insert( modifyText.Begin() + cursorIndex, utf32Characters.Begin(), utf32Characters.Begin() + maxSizeOfNewText );
1587 modifyText.Insert( modifyText.End(), utf32Characters.Begin(), utf32Characters.Begin() + maxSizeOfNewText );
1590 cursorIndex += maxSizeOfNewText;
1592 DALI_LOG_INFO( gLogFilter, Debug::Verbose, "Inserted %d characters, new size %d new cursor %d\n", maxSizeOfNewText, mImpl->mLogicalModel->mText.Count(), mImpl->mEventData->mPrimaryCursorPosition );
1595 if( 0u == mImpl->mLogicalModel->mText.Count() &&
1596 mImpl->IsPlaceholderAvailable() )
1598 // Show place-holder if empty after removing the pre-edit text
1599 ShowPlaceholderText();
1600 mImpl->mEventData->mUpdateCursorPosition = true;
1601 mImpl->ClearPreEditFlag();
1603 else if( removedPrevious ||
1604 0 != utf32Characters.Count() )
1606 // Queue an inserted event
1607 mImpl->QueueModifyEvent( ModifyEvent::TEXT_INSERTED );
1610 if( maxLengthReached )
1612 DALI_LOG_INFO( gLogFilter, Debug::Verbose, "MaxLengthReached (%d)\n", mImpl->mLogicalModel->mText.Count() );
1614 mImpl->ResetImfManager();
1616 // Do this last since it provides callbacks into application code
1617 mImpl->mControlInterface.MaxLengthReached();
1621 bool Controller::RemoveSelectedText()
1623 bool textRemoved( false );
1625 if( EventData::SELECTING == mImpl->mEventData->mState )
1627 std::string removedString;
1628 mImpl->RetrieveSelection( removedString, true );
1630 if( !removedString.empty() )
1633 mImpl->ChangeState( EventData::EDITING );
1640 void Controller::TapEvent( unsigned int tapCount, float x, float y )
1642 DALI_ASSERT_DEBUG( mImpl->mEventData && "Unexpected TapEvent" );
1644 if( NULL != mImpl->mEventData )
1646 DALI_LOG_INFO( gLogFilter, Debug::Concise, "TapEvent state:%d \n", mImpl->mEventData->mState );
1648 if( 1u == tapCount )
1650 // This is to avoid unnecessary relayouts when tapping an empty text-field
1651 bool relayoutNeeded( false );
1653 if ( EventData::EDITING_WITH_PASTE_POPUP == mImpl->mEventData->mState || EventData::EDITING_WITH_PASTE_POPUP == mImpl->mEventData->mState )
1655 mImpl->ChangeState( EventData::EDITING_WITH_GRAB_HANDLE); // If Popup shown hide it here so can be shown again if required.
1658 if( mImpl->IsShowingRealText() && ( EventData::INACTIVE != mImpl->mEventData->mState ) )
1660 // Already in an active state so show a popup
1661 if ( !mImpl->IsClipboardEmpty() )
1663 // Shows Paste popup but could show full popup with Selection options. ( EDITING_WITH_POPUP )
1664 mImpl->ChangeState( EventData::EDITING_WITH_PASTE_POPUP );
1668 mImpl->ChangeState( EventData::EDITING_WITH_GRAB_HANDLE );
1670 relayoutNeeded = true;
1674 if( mImpl->IsShowingPlaceholderText() && !mImpl->IsFocusedPlaceholderAvailable() )
1676 // Hide placeholder text
1680 if ( EventData::INACTIVE == mImpl->mEventData->mState )
1682 mImpl->ChangeState( EventData::EDITING );
1684 else if ( !mImpl->IsClipboardEmpty() )
1686 mImpl->ChangeState( EventData::EDITING_WITH_POPUP );
1688 relayoutNeeded = true;
1691 // Handles & cursors must be repositioned after Relayout() i.e. after the Model has been updated
1692 if( relayoutNeeded )
1694 Event event( Event::TAP_EVENT );
1695 event.p1.mUint = tapCount;
1696 event.p2.mFloat = x;
1697 event.p3.mFloat = y;
1698 mImpl->mEventData->mEventQueue.push_back( event );
1700 mImpl->RequestRelayout();
1703 else if( 2u == tapCount )
1705 if( mImpl->mEventData->mSelectionEnabled &&
1706 mImpl->IsShowingRealText() )
1708 SelectEvent( x, y, false );
1713 // Reset keyboard as tap event has occurred.
1714 mImpl->ResetImfManager();
1717 void Controller::PanEvent( Gesture::State state, const Vector2& displacement )
1718 // Show cursor and grabhandle on first tap, this matches the behaviour of tapping when already editing
1720 DALI_ASSERT_DEBUG( mImpl->mEventData && "Unexpected PanEvent" );
1722 if( mImpl->mEventData )
1724 Event event( Event::PAN_EVENT );
1725 event.p1.mInt = state;
1726 event.p2.mFloat = displacement.x;
1727 event.p3.mFloat = displacement.y;
1728 mImpl->mEventData->mEventQueue.push_back( event );
1730 mImpl->RequestRelayout();
1734 void Controller::LongPressEvent( Gesture::State state, float x, float y )
1736 DALI_ASSERT_DEBUG( mImpl->mEventData && "Unexpected LongPressEvent" );
1738 if( state == Gesture::Started &&
1741 if( ! mImpl->IsShowingRealText() )
1743 Event event( Event::LONG_PRESS_EVENT );
1744 event.p1.mInt = state;
1745 mImpl->mEventData->mEventQueue.push_back( event );
1746 mImpl->RequestRelayout();
1750 // The 1st long-press on inactive text-field is treated as tap
1751 if( EventData::INACTIVE == mImpl->mEventData->mState )
1753 mImpl->ChangeState( EventData::EDITING );
1755 Event event( Event::TAP_EVENT );
1757 event.p2.mFloat = x;
1758 event.p3.mFloat = y;
1759 mImpl->mEventData->mEventQueue.push_back( event );
1761 mImpl->RequestRelayout();
1765 // Reset the imf manger to commit the pre-edit before selecting the text.
1766 mImpl->ResetImfManager();
1768 SelectEvent( x, y, false );
1774 void Controller::SelectEvent( float x, float y, bool selectAll )
1776 DALI_LOG_INFO( gLogFilter, Debug::Verbose, "Controller::SelectEvent\n" );
1778 if( mImpl->mEventData )
1780 mImpl->ChangeState( EventData::SELECTING );
1784 Event event( Event::SELECT_ALL );
1785 mImpl->mEventData->mEventQueue.push_back( event );
1789 Event event( Event::SELECT );
1790 event.p2.mFloat = x;
1791 event.p3.mFloat = y;
1792 mImpl->mEventData->mEventQueue.push_back( event );
1795 mImpl->RequestRelayout();
1799 void Controller::GetTargetSize( Vector2& targetSize )
1801 targetSize = mImpl->mVisualModel->mControlSize;
1804 void Controller::AddDecoration( Actor& actor, bool needsClipping )
1806 mImpl->mControlInterface.AddDecoration( actor, needsClipping );
1809 void Controller::DecorationEvent( HandleType handleType, HandleState state, float x, float y )
1811 DALI_ASSERT_DEBUG( mImpl->mEventData && "Unexpected DecorationEvent" );
1813 if( mImpl->mEventData )
1815 switch( handleType )
1819 Event event( Event::GRAB_HANDLE_EVENT );
1820 event.p1.mUint = state;
1821 event.p2.mFloat = x;
1822 event.p3.mFloat = y;
1824 mImpl->mEventData->mEventQueue.push_back( event );
1827 case LEFT_SELECTION_HANDLE:
1829 Event event( Event::LEFT_SELECTION_HANDLE_EVENT );
1830 event.p1.mUint = state;
1831 event.p2.mFloat = x;
1832 event.p3.mFloat = y;
1834 mImpl->mEventData->mEventQueue.push_back( event );
1837 case RIGHT_SELECTION_HANDLE:
1839 Event event( Event::RIGHT_SELECTION_HANDLE_EVENT );
1840 event.p1.mUint = state;
1841 event.p2.mFloat = x;
1842 event.p3.mFloat = y;
1844 mImpl->mEventData->mEventQueue.push_back( event );
1847 case LEFT_SELECTION_HANDLE_MARKER:
1848 case RIGHT_SELECTION_HANDLE_MARKER:
1850 // Markers do not move the handles.
1853 case HANDLE_TYPE_COUNT:
1855 DALI_ASSERT_DEBUG( !"Controller::HandleEvent. Unexpected handle type" );
1859 mImpl->RequestRelayout();
1863 void Controller::PasteText( const std::string& stringToPaste )
1865 InsertText( stringToPaste, Text::Controller::COMMIT );
1866 mImpl->ChangeState( EventData::EDITING );
1867 mImpl->RequestRelayout();
1869 // Do this last since it provides callbacks into application code
1870 mImpl->mControlInterface.TextChanged();
1873 void Controller::PasteClipboardItemEvent()
1875 // Retrieve the clipboard contents first
1876 ClipboardEventNotifier notifier( ClipboardEventNotifier::Get() );
1877 std::string stringToPaste( notifier.GetContent() );
1879 // Commit the current pre-edit text; the contents of the clipboard should be appended
1880 mImpl->ResetImfManager();
1883 PasteText( stringToPaste );
1886 void Controller::TextPopupButtonTouched( Dali::Toolkit::TextSelectionPopup::Buttons button )
1888 if( NULL == mImpl->mEventData )
1895 case Toolkit::TextSelectionPopup::CUT:
1897 mImpl->SendSelectionToClipboard( true ); // Synchronous call to modify text
1898 mImpl->mOperationsPending = ALL_OPERATIONS;
1900 // This is to reset the virtual keyboard to Upper-case
1901 if( 0u == mImpl->mLogicalModel->mText.Count() )
1906 if( 0u != mImpl->mLogicalModel->mText.Count() ||
1907 !mImpl->IsPlaceholderAvailable() )
1909 mImpl->QueueModifyEvent( ModifyEvent::TEXT_DELETED );
1913 ShowPlaceholderText();
1914 mImpl->mEventData->mUpdateCursorPosition = true;
1916 mImpl->RequestRelayout();
1917 mImpl->mControlInterface.TextChanged();
1920 case Toolkit::TextSelectionPopup::COPY:
1922 mImpl->SendSelectionToClipboard( false ); // Text not modified
1923 mImpl->RequestRelayout(); // Handles, Selection Highlight, Popup
1926 case Toolkit::TextSelectionPopup::PASTE:
1928 std::string stringToPaste("");
1929 mImpl->GetTextFromClipboard( 0, stringToPaste ); // Paste latest item from system clipboard
1930 PasteText( stringToPaste );
1933 case Toolkit::TextSelectionPopup::SELECT:
1935 const Vector2& currentCursorPosition = mImpl->mEventData->mDecorator->GetPosition( PRIMARY_CURSOR );
1937 if( mImpl->mEventData->mSelectionEnabled )
1939 // Creates a SELECT event.
1940 SelectEvent( currentCursorPosition.x, currentCursorPosition.y, false );
1944 case Toolkit::TextSelectionPopup::SELECT_ALL:
1946 // Creates a SELECT_ALL event
1947 SelectEvent( 0.f, 0.f, true );
1950 case Toolkit::TextSelectionPopup::CLIPBOARD:
1952 mImpl->ShowClipboard();
1955 case Toolkit::TextSelectionPopup::NONE:
1963 ImfManager::ImfCallbackData Controller::OnImfEvent( ImfManager& imfManager, const ImfManager::ImfEventData& imfEvent )
1965 bool update = false;
1966 bool requestRelayout = false;
1969 unsigned int cursorPosition( 0 );
1971 switch ( imfEvent.eventName )
1973 case ImfManager::COMMIT:
1975 InsertText( imfEvent.predictiveString, Text::Controller::COMMIT );
1977 requestRelayout = true;
1980 case ImfManager::PREEDIT:
1982 InsertText( imfEvent.predictiveString, Text::Controller::PRE_EDIT );
1984 requestRelayout = true;
1987 case ImfManager::DELETESURROUNDING:
1989 update = RemoveText( imfEvent.cursorOffset, imfEvent.numberOfChars );
1993 if( 0u != mImpl->mLogicalModel->mText.Count() ||
1994 !mImpl->IsPlaceholderAvailable() )
1996 mImpl->QueueModifyEvent( ModifyEvent::TEXT_DELETED );
2000 ShowPlaceholderText();
2001 mImpl->mEventData->mUpdateCursorPosition = true;
2004 requestRelayout = true;
2007 case ImfManager::GETSURROUNDING:
2010 cursorPosition = GetLogicalCursorPosition();
2012 imfManager.SetSurroundingText( text );
2013 imfManager.SetCursorPosition( cursorPosition );
2016 case ImfManager::VOID:
2023 if( ImfManager::GETSURROUNDING != imfEvent.eventName )
2026 cursorPosition = GetLogicalCursorPosition();
2029 if( requestRelayout )
2031 mImpl->mOperationsPending = ALL_OPERATIONS;
2032 mImpl->RequestRelayout();
2034 // Do this last since it provides callbacks into application code
2035 mImpl->mControlInterface.TextChanged();
2038 ImfManager::ImfCallbackData callbackData( update, cursorPosition, text, false );
2040 return callbackData;
2043 Controller::~Controller()
2048 bool Controller::BackspaceKeyEvent()
2050 DALI_LOG_INFO( gLogFilter, Debug::Verbose, "Controller::KeyEvent %p DALI_KEY_BACKSPACE\n", this );
2052 // IMF manager is no longer handling key-events
2053 mImpl->ClearPreEditFlag();
2055 bool removed( false );
2057 if( EventData::SELECTING == mImpl->mEventData->mState )
2059 removed = RemoveSelectedText();
2061 else if( mImpl->mEventData->mPrimaryCursorPosition > 0 )
2063 // Remove the character before the current cursor position
2064 removed = RemoveText( -1, 1 );
2069 DALI_LOG_INFO( gLogFilter, Debug::Verbose, "Controller::KeyEvent %p DALI_KEY_BACKSPACE RemovedText\n", this );
2070 // Notifiy the IMF manager after text changed
2071 // Automatic Upper-case and restarting prediction on an existing word require this.
2074 if( 0u != mImpl->mLogicalModel->mText.Count() ||
2075 !mImpl->IsPlaceholderAvailable() )
2077 mImpl->QueueModifyEvent( ModifyEvent::TEXT_DELETED );
2081 ShowPlaceholderText();
2082 mImpl->mEventData->mUpdateCursorPosition = true;
2089 void Controller::NotifyImfManager()
2091 if( mImpl->mEventData )
2093 if( mImpl->mEventData->mImfManager )
2095 // Notifying IMF of a cursor change triggers a surrounding text request so updating it now.
2098 mImpl->mEventData->mImfManager.SetSurroundingText( text );
2100 mImpl->mEventData->mImfManager.SetCursorPosition( GetLogicalCursorPosition() );
2101 mImpl->mEventData->mImfManager.NotifyCursorPosition();
2106 void Controller::ShowPlaceholderText()
2108 if( mImpl->IsPlaceholderAvailable() )
2110 DALI_ASSERT_DEBUG( mImpl->mEventData && "No placeholder text available" );
2112 mImpl->mEventData->mIsShowingPlaceholderText = true;
2114 // Disable handles when showing place-holder text
2115 mImpl->mEventData->mDecorator->SetHandleActive( GRAB_HANDLE, false );
2116 mImpl->mEventData->mDecorator->SetHandleActive( LEFT_SELECTION_HANDLE, false );
2117 mImpl->mEventData->mDecorator->SetHandleActive( RIGHT_SELECTION_HANDLE, false );
2119 const char* text( NULL );
2122 // TODO - Switch placeholder text styles when changing state
2123 if( EventData::INACTIVE != mImpl->mEventData->mState &&
2124 0u != mImpl->mEventData->mPlaceholderTextActive.c_str() )
2126 text = mImpl->mEventData->mPlaceholderTextActive.c_str();
2127 size = mImpl->mEventData->mPlaceholderTextActive.size();
2131 text = mImpl->mEventData->mPlaceholderTextInactive.c_str();
2132 size = mImpl->mEventData->mPlaceholderTextInactive.size();
2135 // Reset model for showing placeholder.
2136 mImpl->mLogicalModel->mText.Clear();
2138 mImpl->mVisualModel->SetTextColor( mImpl->mEventData->mPlaceholderTextColor );
2140 // Convert text into UTF-32
2141 Vector<Character>& utf32Characters = mImpl->mLogicalModel->mText;
2142 utf32Characters.Resize( size );
2144 // This is a bit horrible but std::string returns a (signed) char*
2145 const uint8_t* utf8 = reinterpret_cast<const uint8_t*>( text );
2147 // Transform a text array encoded in utf8 into an array encoded in utf32.
2148 // It returns the actual number of characters.
2149 Length characterCount = Utf8ToUtf32( utf8, size, utf32Characters.Begin() );
2150 utf32Characters.Resize( characterCount );
2152 // Reset the cursor position
2153 mImpl->mEventData->mPrimaryCursorPosition = 0;
2155 // The natural size needs to be re-calculated.
2156 mImpl->mRecalculateNaturalSize = true;
2158 // Apply modifications to the model
2159 mImpl->mOperationsPending = ALL_OPERATIONS;
2161 // Update the rest of the model during size negotiation
2162 mImpl->QueueModifyEvent( ModifyEvent::TEXT_REPLACED );
2166 void Controller::ClearModelData()
2168 // n.b. This does not Clear the mText from mLogicalModel
2169 mImpl->mLogicalModel->mScriptRuns.Clear();
2170 mImpl->mLogicalModel->mFontRuns.Clear();
2171 mImpl->mLogicalModel->mLineBreakInfo.Clear();
2172 mImpl->mLogicalModel->mWordBreakInfo.Clear();
2173 mImpl->mLogicalModel->mBidirectionalParagraphInfo.Clear();
2174 mImpl->mLogicalModel->mCharacterDirections.Clear();
2175 mImpl->mLogicalModel->mBidirectionalLineInfo.Clear();
2176 mImpl->mLogicalModel->mLogicalToVisualMap.Clear();
2177 mImpl->mLogicalModel->mVisualToLogicalMap.Clear();
2178 mImpl->mVisualModel->mGlyphs.Clear();
2179 mImpl->mVisualModel->mGlyphsToCharacters.Clear();
2180 mImpl->mVisualModel->mCharactersToGlyph.Clear();
2181 mImpl->mVisualModel->mCharactersPerGlyph.Clear();
2182 mImpl->mVisualModel->mGlyphsPerCharacter.Clear();
2183 mImpl->mVisualModel->mGlyphPositions.Clear();
2184 mImpl->mVisualModel->mLines.Clear();
2185 mImpl->mVisualModel->mColorRuns.Clear();
2186 mImpl->mVisualModel->ClearCaches();
2189 void Controller::ClearFontData()
2191 mImpl->mFontDefaults->mFontId = 0u; // Remove old font ID
2192 mImpl->mLogicalModel->mFontRuns.Clear();
2193 mImpl->mVisualModel->mGlyphs.Clear();
2194 mImpl->mVisualModel->mGlyphsToCharacters.Clear();
2195 mImpl->mVisualModel->mCharactersToGlyph.Clear();
2196 mImpl->mVisualModel->mCharactersPerGlyph.Clear();
2197 mImpl->mVisualModel->mGlyphsPerCharacter.Clear();
2198 mImpl->mVisualModel->mGlyphPositions.Clear();
2199 mImpl->mVisualModel->mLines.Clear();
2200 mImpl->mVisualModel->ClearCaches();
2203 void Controller::ClearStyleData()
2205 mImpl->mLogicalModel->mColorRuns.Clear();
2208 Controller::Controller( ControlInterface& controlInterface )
2211 mImpl = new Controller::Impl( controlInterface );
2216 } // namespace Toolkit