X-Git-Url: http://review.tizen.org/git/?p=platform%2Fcore%2Fuifw%2Fdali-toolkit.git;a=blobdiff_plain;f=dali-toolkit%2Finternal%2Ftext%2Ftext-controller.cpp;h=fc372af0467c55d1ef78fce49b0f6067a879126d;hp=4f866785837cd75b227a4dfb8592d4a2665de2b4;hb=2039784e7811f5f68ffdfb13c6aa1bc39f2ab950;hpb=a6f34ab2df1f2418c037366030a4dcfbcda29847 diff --git a/dali-toolkit/internal/text/text-controller.cpp b/dali-toolkit/internal/text/text-controller.cpp index 4f86678..592bc12 100644 --- a/dali-toolkit/internal/text/text-controller.cpp +++ b/dali-toolkit/internal/text/text-controller.cpp @@ -20,45 +20,34 @@ // EXTERNAL INCLUDES #include -#include #include -#include +#include +#include // INTERNAL INCLUDES #include #include -#include #include -#include -#include -#include -#include -#include -#include -#include -#include - -using std::vector; +#include namespace { +#if defined(DEBUG_ENABLED) + Debug::Filter* gLogFilter = Debug::Filter::New(Debug::NoLogging, true, "LOG_TEXT_CONTROLS"); +#endif + const float MAX_FLOAT = std::numeric_limits::max(); +const unsigned int POINTS_PER_INCH = 72; -enum ModifyType -{ - REPLACE_TEXT, ///< Replace the entire text - INSERT_TEXT, ///< Insert characters at the current cursor position - DELETE_TEXT ///< Delete a character at the current cursor position -}; +const std::string EMPTY_STRING(""); +const unsigned int ZERO = 0u; -struct ModifyEvent +float ConvertToEven( float value ) { - ModifyType type; - std::string text; -}; - -const std::string EMPTY_STRING(""); + int intValue(static_cast( value )); + return static_cast(intValue % 2 == 0) ? intValue : (intValue + 1); +} } // namespace @@ -71,2068 +60,2002 @@ namespace Toolkit namespace Text { -struct Controller::FontDefaults +ControllerPtr Controller::New( ControlInterface& controlInterface ) +{ + return ControllerPtr( new Controller( controlInterface ) ); +} + +void Controller::EnableTextInput( DecoratorPtr decorator ) { - FontDefaults() - : mDefaultPointSize(0.0f), - mFontId(0u) + if( !mImpl->mEventData ) { + mImpl->mEventData = new EventData( decorator ); } +} - FontId GetFontId( TextAbstraction::FontClient& fontClient ) - { - if( !mFontId ) - { - Dali::TextAbstraction::PointSize26Dot6 pointSize = mDefaultPointSize*64; - mFontId = fontClient.GetFontId( mDefaultFontFamily, mDefaultFontStyle, pointSize ); - } +void Controller::SetText( const std::string& text ) +{ + DALI_LOG_INFO( gLogFilter, Debug::Verbose, "Controller::SetText\n" ); - return mFontId; - } + // Reset keyboard as text changed + mImpl->ResetImfManager(); - std::string mDefaultFontFamily; - std::string mDefaultFontStyle; - float mDefaultPointSize; - FontId mFontId; -}; + // Remove the previously set text + ResetText(); -struct Controller::TextInput -{ - // Used to queue input events until DoRelayout() - enum EventType - { - KEYBOARD_FOCUS_GAIN_EVENT, - KEYBOARD_FOCUS_LOST_EVENT, - CURSOR_KEY_EVENT, - TAP_EVENT, - PAN_EVENT, - GRAB_HANDLE_EVENT - }; - - union Param - { - int mInt; - unsigned int mUint; - float mFloat; - }; + CharacterIndex lastCursorIndex = 0u; - struct Event + if( mImpl->mEventData ) { - Event( EventType eventType ) - : type( eventType ) + // If popup shown then hide it by switching to Editing state + if( ( EventData::SELECTING == mImpl->mEventData->mState ) || + ( EventData::EDITING_WITH_POPUP == mImpl->mEventData->mState ) || + ( EventData::EDITING_WITH_GRAB_HANDLE == mImpl->mEventData->mState ) || + ( EventData::EDITING_WITH_PASTE_POPUP == mImpl->mEventData->mState ) ) { - p1.mInt = 0; - p2.mInt = 0; + mImpl->ChangeState( EventData::EDITING ); } + } - EventType type; - Param p1; - Param p2; - Param p3; - }; + if( !text.empty() ) + { + // Convert text into UTF-32 + Vector& utf32Characters = mImpl->mLogicalModel->mText; + utf32Characters.Resize( text.size() ); + + // This is a bit horrible but std::string returns a (signed) char* + const uint8_t* utf8 = reinterpret_cast( text.c_str() ); + + // Transform a text array encoded in utf8 into an array encoded in utf32. + // It returns the actual number of characters. + Length characterCount = Utf8ToUtf32( utf8, text.size(), utf32Characters.Begin() ); + utf32Characters.Resize( characterCount ); + + DALI_ASSERT_DEBUG( text.size() >= characterCount && "Invalid UTF32 conversion length" ); + DALI_LOG_INFO( gLogFilter, Debug::Verbose, "Controller::SetText %p UTF8 size %d, UTF32 size %d\n", this, text.size(), mImpl->mLogicalModel->mText.Count() ); - struct CursorInfo + // To reset the cursor position + lastCursorIndex = characterCount; + + // Update the rest of the model during size negotiation + mImpl->QueueModifyEvent( ModifyEvent::TEXT_REPLACED ); + + // The natural size needs to be re-calculated. + mImpl->mRecalculateNaturalSize = true; + + // Apply modifications to the model + mImpl->mOperationsPending = ALL_OPERATIONS; + } + else { - CursorInfo() - : primaryPosition(), - secondaryPosition(), - lineHeight( 0.f ), - primaryCursorHeight( 0.f ), - secondaryCursorHeight( 0.f ), - isSecondaryCursor( false ) - {} + ShowPlaceholderText(); + } - ~CursorInfo() - {} + // Resets the cursor position. + ResetCursorPosition( lastCursorIndex ); - Vector2 primaryPosition; ///< The primary cursor's position. - Vector2 secondaryPosition; ///< The secondary cursor's position. - float lineHeight; ///< The height of the line where the cursor is placed. - float primaryCursorHeight; ///< The primary cursor's height. - float secondaryCursorHeight; ///< The secondary cursor's height. - bool isSecondaryCursor; ///< Whether the secondary cursor is valid. - }; + // Scrolls the text to make the cursor visible. + ResetScrollPosition(); - /** - * @brief Some characters can be shaped in more than one glyph. - * This struct is used to retrieve metrics from these group of glyphs. - */ - struct GlyphMetrics + mImpl->RequestRelayout(); + + if( mImpl->mEventData ) { - GlyphMetrics() - : fontHeight( 0.f ), - advance( 0.f ), - ascender( 0.f ), - xBearing( 0.f ) - {} + // Cancel previously queued events + mImpl->mEventData->mEventQueue.clear(); + } - ~GlyphMetrics() - {} + // Notify IMF as text changed + NotifyImfManager(); - float fontHeight; ///< The font's height of that glyphs. - float advance; ///< The sum of all the advances of all the glyphs. - float ascender; ///< The font's ascender. - float xBearing; ///< The x bearing of the first glyph. - }; - - enum State - { - INACTIVE, - SELECTING, - EDITING, - EDITING_WITH_POPUP - }; - - TextInput( LogicalModelPtr logicalModel, - VisualModelPtr visualModel, - DecoratorPtr decorator, - FontDefaults* fontDefaults, - TextAbstraction::FontClient& fontClient ) - : mLogicalModel( logicalModel ), - mVisualModel( visualModel ), - mDecorator( decorator ), - mFontDefaults( fontDefaults ), - mFontClient( fontClient ), - mState( INACTIVE ), - mPrimaryCursorPosition( 0u ), - mSecondaryCursorPosition( 0u ), - mDecoratorUpdated( false ), - mCursorBlinkEnabled( true ), - mGrabHandleEnabled( true ), - mGrabHandlePopupEnabled( true ), - mSelectionEnabled( true ), - mHorizontalScrollingEnabled( true ), - mVerticalScrollingEnabled( false ), - mUpdateCursorPosition( false ) - {} - - /** - * @brief Helper to move the cursor, grab handle etc. - */ - bool ProcessInputEvents( const Vector2& controlSize, - const Vector2& alignmentOffset ) - { - mDecoratorUpdated = false; - - if( mDecorator ) - { - for( vector::iterator iter = mEventQueue.begin(); iter != mEventQueue.end(); ++iter ) - { - switch( iter->type ) - { - case KEYBOARD_FOCUS_GAIN_EVENT: - { - OnKeyboardFocus( true ); - break; - } - case KEYBOARD_FOCUS_LOST_EVENT: - { - OnKeyboardFocus( false ); - break; - } - case CURSOR_KEY_EVENT: - { - OnCursorKeyEvent( *iter ); - break; - } - case TAP_EVENT: - { - OnTapEvent( *iter, alignmentOffset ); - break; - } - case PAN_EVENT: - { - OnPanEvent( *iter, controlSize, alignmentOffset ); - break; - } - case GRAB_HANDLE_EVENT: - { - OnGrabHandleEvent( *iter ); - break; - } - } - } - } + // Do this last since it provides callbacks into application code + mImpl->mControlInterface.TextChanged(); +} + +void Controller::GetText( std::string& text ) const +{ + if( ! mImpl->IsShowingPlaceholderText() ) + { + Vector& utf32Characters = mImpl->mLogicalModel->mText; - // The cursor must also be repositioned after inserts into the model - if( mUpdateCursorPosition ) + if( 0u != utf32Characters.Count() ) { - UpdateCursorPosition(); - mUpdateCursorPosition = false; + Utf32ToUtf8( &utf32Characters[0], utf32Characters.Count(), text ); } + } + else + { + DALI_LOG_INFO( gLogFilter, Debug::Verbose, "Controller::GetText %p empty (but showing placeholder)\n", this ); + } +} - mEventQueue.clear(); - - return mDecoratorUpdated; +unsigned int Controller::GetLogicalCursorPosition() const +{ + if( mImpl->mEventData ) + { + return mImpl->mEventData->mPrimaryCursorPosition; } - void OnKeyboardFocus( bool hasFocus ) + return 0u; +} + +void Controller::SetPlaceholderText( PlaceholderType type, const std::string& text ) +{ + if( mImpl->mEventData ) { - if( !hasFocus ) + if( PLACEHOLDER_TYPE_INACTIVE == type ) { - ChangeState( INACTIVE ); + mImpl->mEventData->mPlaceholderTextInactive = text; } else { - ChangeState( EDITING ); + mImpl->mEventData->mPlaceholderTextActive = text; } - } - - void OnCursorKeyEvent( const Event& event ) - { - int keyCode = event.p1.mInt; - if( Dali::DALI_KEY_CURSOR_LEFT == keyCode ) - { - if( mPrimaryCursorPosition > 0u ) - { - mPrimaryCursorPosition = CalculateNewCursorIndex( mPrimaryCursorPosition - 1u ); - } - } - else if( Dali::DALI_KEY_CURSOR_RIGHT == keyCode ) + // Update placeholder if there is no text + if( mImpl->IsShowingPlaceholderText() || + 0u == mImpl->mLogicalModel->mText.Count() ) { - if( mLogicalModel->GetNumberOfCharacters() > mPrimaryCursorPosition ) - { - mPrimaryCursorPosition = CalculateNewCursorIndex( mPrimaryCursorPosition ); - } + ShowPlaceholderText(); } - else if( Dali::DALI_KEY_CURSOR_UP == keyCode ) + } +} + +void Controller::GetPlaceholderText( PlaceholderType type, std::string& text ) const +{ + if( mImpl->mEventData ) + { + if( PLACEHOLDER_TYPE_INACTIVE == type ) { - // TODO + text = mImpl->mEventData->mPlaceholderTextInactive; } - else if( Dali::DALI_KEY_CURSOR_DOWN == keyCode ) + else { - // TODO + text = mImpl->mEventData->mPlaceholderTextActive; } - - UpdateCursorPosition(); } +} - void HandleCursorKey( int keyCode ) +void Controller::SetMaximumNumberOfCharacters( int maxCharacters ) +{ + if ( maxCharacters >= 0 ) { - // TODO + mImpl->mMaximumNumberOfCharacters = maxCharacters; } +} - void OnTapEvent( const Event& event, - const Vector2& alignmentOffset ) - { - unsigned int tapCount = event.p1.mUint; +int Controller::GetMaximumNumberOfCharacters() +{ + return mImpl->mMaximumNumberOfCharacters; +} - if( 1u == tapCount ) - { - ChangeState( EDITING ); +void Controller::SetDefaultFontFamily( const std::string& defaultFontFamily ) +{ + if( !mImpl->mFontDefaults ) + { + mImpl->mFontDefaults = new FontDefaults(); + } - float xPosition = event.p2.mFloat - alignmentOffset.x; - float yPosition = event.p3.mFloat - alignmentOffset.y; + mImpl->mFontDefaults->mFontDescription.family = defaultFontFamily; + DALI_LOG_INFO( gLogFilter, Debug::General, "Controller::SetDefaultFontFamily %s\n", defaultFontFamily.c_str()); + mImpl->mUserDefinedFontFamily = true; - mPrimaryCursorPosition = GetClosestCursorIndex( xPosition, - yPosition ); + // Clear the font-specific data + ClearFontData(); - UpdateCursorPosition(); - } - else if( mSelectionEnabled && - 2u == tapCount ) - { - ChangeState( SELECTING ); + mImpl->mOperationsPending = ALL_OPERATIONS; + mImpl->mRecalculateNaturalSize = true; - RepositionSelectionHandles( event.p2.mFloat, event.p3.mFloat ); - } - } + mImpl->RequestRelayout(); +} - void OnPanEvent( const Event& event, - const Vector2& controlSize, - const Vector2& alignmentOffset ) +const std::string& Controller::GetDefaultFontFamily() const +{ + if( mImpl->mFontDefaults ) { - int state = event.p1.mInt; - - if( Gesture::Started == state || - Gesture::Continuing == state ) - { - const Vector2& actualSize = mVisualModel->GetActualSize(); + return mImpl->mFontDefaults->mFontDescription.family; + } - if( mHorizontalScrollingEnabled ) - { - const float displacementX = event.p2.mFloat; - mScrollPosition.x += displacementX; + return EMPTY_STRING; +} - // Clamp between -space & 0 (and the text alignment). - const float contentWidth = actualSize.width; - if( contentWidth > controlSize.width ) - { - const float space = ( contentWidth - controlSize.width ) + alignmentOffset.x; - mScrollPosition.x = ( mScrollPosition.x < -space ) ? -space : mScrollPosition.x; - mScrollPosition.x = ( mScrollPosition.x > -alignmentOffset.x ) ? -alignmentOffset.x : mScrollPosition.x; +void Controller::SetDefaultFontStyle( const std::string& style ) +{ + if( !mImpl->mFontDefaults ) + { + mImpl->mFontDefaults = new FontDefaults(); + } - mDecoratorUpdated = true; - } - else - { - mScrollPosition.x = 0.f; - } - } + mImpl->mFontDefaults->mFontStyle = style; +} - if( mVerticalScrollingEnabled ) - { - const float displacementY = event.p3.mFloat; - mScrollPosition.y += displacementY; +const std::string& Controller::GetDefaultFontStyle() const +{ + if( mImpl->mFontDefaults ) + { + return mImpl->mFontDefaults->mFontStyle; + } - // Clamp between -space & 0 (and the text alignment). - if( actualSize.height > controlSize.height ) - { - const float space = ( actualSize.height - controlSize.height ) + alignmentOffset.y; - mScrollPosition.y = ( mScrollPosition.y < -space ) ? -space : mScrollPosition.y; - mScrollPosition.y = ( mScrollPosition.y > -alignmentOffset.y ) ? -alignmentOffset.y : mScrollPosition.y; + return EMPTY_STRING; +} - mDecoratorUpdated = true; - } - else - { - mScrollPosition.y = 0.f; - } - } - } +void Controller::SetDefaultFontWidth( FontWidth width ) +{ + if( !mImpl->mFontDefaults ) + { + mImpl->mFontDefaults = new FontDefaults(); } - void OnGrabHandleEvent( const Event& event ) - { - unsigned int state = event.p1.mUint; + mImpl->mFontDefaults->mFontDescription.width = width; - if( GRAB_HANDLE_PRESSED == state ) - { - float xPosition = event.p2.mFloat + mScrollPosition.x; - float yPosition = event.p3.mFloat + mScrollPosition.y; + // Clear the font-specific data + ClearFontData(); - mPrimaryCursorPosition = GetClosestCursorIndex( xPosition, - yPosition ); + mImpl->mOperationsPending = ALL_OPERATIONS; + mImpl->mRecalculateNaturalSize = true; - UpdateCursorPosition(); + mImpl->RequestRelayout(); +} - //mDecorator->HidePopup(); - ChangeState ( EDITING ); - } - else if ( mGrabHandlePopupEnabled && - GRAB_HANDLE_RELEASED == state ) - { - //mDecorator->ShowPopup(); - ChangeState ( EDITING_WITH_POPUP ); - mDecoratorUpdated = true; - } +FontWidth Controller::GetDefaultFontWidth() const +{ + if( mImpl->mFontDefaults ) + { + return mImpl->mFontDefaults->mFontDescription.width; } - void RepositionSelectionHandles( float visualX, float visualY ) + return TextAbstraction::FontWidth::NORMAL; +} + +void Controller::SetDefaultFontWeight( FontWeight weight ) +{ + if( !mImpl->mFontDefaults ) { - // TODO - Find which word was selected + mImpl->mFontDefaults = new FontDefaults(); + } - const Vector& glyphs = mVisualModel->mGlyphs; - const Vector::SizeType glyphCount = glyphs.Count(); + mImpl->mFontDefaults->mFontDescription.weight = weight; - const Vector& positions = mVisualModel->mGlyphPositions; - const Vector::SizeType positionCount = positions.Count(); + // Clear the font-specific data + ClearFontData(); - // Guard against glyphs which did not fit inside the layout - const Vector::SizeType count = (positionCount < glyphCount) ? positionCount : glyphCount; + mImpl->mOperationsPending = ALL_OPERATIONS; + mImpl->mRecalculateNaturalSize = true; - if( count ) - { - float primaryX = positions[0].x; - float secondaryX = positions[count-1].x + glyphs[count-1].width; + mImpl->RequestRelayout(); +} - // TODO - multi-line selection - const Vector& lines = mVisualModel->mLines; - float height = lines.Count() ? lines[0].ascender + -lines[0].descender : 0.0f; +FontWeight Controller::GetDefaultFontWeight() const +{ + if( mImpl->mFontDefaults ) + { + return mImpl->mFontDefaults->mFontDescription.weight; + } - mDecorator->SetPosition( PRIMARY_SELECTION_HANDLE, primaryX, 0.0f, height ); - mDecorator->SetPosition( SECONDARY_SELECTION_HANDLE, secondaryX, 0.0f, height ); + return TextAbstraction::FontWeight::NORMAL; +} - mDecorator->ClearHighlights(); - mDecorator->AddHighlight( primaryX, 0.0f, secondaryX, height ); - } +void Controller::SetDefaultFontSlant( FontSlant slant ) +{ + if( !mImpl->mFontDefaults ) + { + mImpl->mFontDefaults = new FontDefaults(); } - void ChangeState( State newState ) - { - if( mState != newState ) - { - mState = newState; + mImpl->mFontDefaults->mFontDescription.slant = slant; - if( INACTIVE == mState ) - { - mDecorator->SetActiveCursor( ACTIVE_CURSOR_NONE ); - mDecorator->StopCursorBlink(); - mDecorator->SetGrabHandleActive( false ); - mDecorator->SetSelectionActive( false ); - mDecorator->SetPopupActive( false ); - mDecoratorUpdated = true; - } - else if ( SELECTING == mState ) - { - mDecorator->SetActiveCursor( ACTIVE_CURSOR_NONE ); - mDecorator->StopCursorBlink(); - mDecorator->SetGrabHandleActive( false ); - mDecorator->SetSelectionActive( true ); - mDecoratorUpdated = true; - } - else if( EDITING == mState ) - { - mDecorator->SetActiveCursor( ACTIVE_CURSOR_PRIMARY ); - if( mCursorBlinkEnabled ) - { - mDecorator->StartCursorBlink(); - } - if( mGrabHandleEnabled ) - { - mDecorator->SetGrabHandleActive( true ); - } - if( mGrabHandlePopupEnabled ) - { - mDecorator->SetPopupActive( false ); - } - mDecorator->SetSelectionActive( false ); - mDecoratorUpdated = true; - } - else if( EDITING_WITH_POPUP == mState ) - { - mDecorator->SetActiveCursor( ACTIVE_CURSOR_PRIMARY ); - if( mCursorBlinkEnabled ) - { - mDecorator->StartCursorBlink(); - } - if( mGrabHandleEnabled ) - { - mDecorator->SetGrabHandleActive( true ); - } - if( mGrabHandlePopupEnabled ) - { - mDecorator->SetPopupActive( true ); - } - mDecorator->SetSelectionActive( false ); - mDecoratorUpdated = true; - } - } - } + // Clear the font-specific data + ClearFontData(); - LineIndex GetClosestLine( float y ) const - { - float totalHeight = 0.f; - LineIndex lineIndex = 0u; + mImpl->mOperationsPending = ALL_OPERATIONS; + mImpl->mRecalculateNaturalSize = true; - const Vector& lines = mVisualModel->mLines; - for( LineIndex endLine = lines.Count(); - lineIndex < endLine; - ++lineIndex ) - { - const LineRun& lineRun = lines[lineIndex]; - totalHeight += lineRun.ascender + -lineRun.descender; - if( y < totalHeight ) - { - return lineIndex; - } - } + mImpl->RequestRelayout(); +} - return lineIndex-1; +FontSlant Controller::GetDefaultFontSlant() const +{ + if( mImpl->mFontDefaults ) + { + return mImpl->mFontDefaults->mFontDescription.slant; } - /** - * @brief Retrieves the cursor's logical position for a given touch point x,y - * - * @param[in] visualX The touch point x. - * @param[in] visualY The touch point y. - * - * @return The logical cursor position (in characters). 0 is just before the first character, a value equal to the number of characters is just after the last character. - */ - CharacterIndex GetClosestCursorIndex( float visualX, - float visualY ) const + return TextAbstraction::FontSlant::NORMAL; +} + +void Controller::SetDefaultPointSize( float pointSize ) +{ + if( !mImpl->mFontDefaults ) { - CharacterIndex logicalIndex = 0u; + mImpl->mFontDefaults = new FontDefaults(); + } - const Length numberOfGlyphs = mVisualModel->mGlyphs.Count(); - const Length numberOfLines = mVisualModel->mLines.Count(); - if( 0 == numberOfGlyphs || - 0 == numberOfLines ) - { - return logicalIndex; - } + mImpl->mFontDefaults->mDefaultPointSize = pointSize; - // Transform to visual model coords - visualX -= mScrollPosition.x; - visualY -= mScrollPosition.y; + unsigned int horizontalDpi( 0u ); + unsigned int verticalDpi( 0u ); + mImpl->mFontClient.GetDpi( horizontalDpi, verticalDpi ); - // Find which line is closest - const LineIndex lineIndex = GetClosestLine( visualY ); - const LineRun& line = mVisualModel->mLines[lineIndex]; + // Adjust the metrics if the fixed-size font should be down-scaled + int maxEmojiSize( pointSize/POINTS_PER_INCH * verticalDpi ); + DALI_LOG_INFO( gLogFilter, Debug::General, "Controller::SetDefaultPointSize %p setting MaxEmojiSize %d\n", this, maxEmojiSize ); + mImpl->mMetrics->SetMaxEmojiSize( maxEmojiSize ); - // Get the positions of the glyphs. - const Vector& positions = mVisualModel->mGlyphPositions; - const Vector2* const positionsBuffer = positions.Begin(); + // Clear the font-specific data + ClearFontData(); - // Get the visual to logical conversion tables. - const CharacterIndex* const visualToLogicalBuffer = ( 0u != mLogicalModel->mVisualToLogicalMap.Count() ) ? mLogicalModel->mVisualToLogicalMap.Begin() : NULL; - const CharacterIndex* const visualToLogicalCursorBuffer = mLogicalModel->mVisualToLogicalCursorMap.Begin(); + mImpl->mOperationsPending = ALL_OPERATIONS; + mImpl->mRecalculateNaturalSize = true; - // Get the character to glyph conversion table. - const GlyphIndex* const charactersToGlyphBuffer = mVisualModel->mCharactersToGlyph.Begin(); + mImpl->RequestRelayout(); +} - // Get the glyphs per character table. - const Length* const glyphsPerCharacterBuffer = mVisualModel->mGlyphsPerCharacter.Begin(); +float Controller::GetDefaultPointSize() const +{ + if( mImpl->mFontDefaults ) + { + return mImpl->mFontDefaults->mDefaultPointSize; + } - // If the vector is void, there is no right to left characters. - const bool hasRightToLeftCharacters = NULL != visualToLogicalBuffer; + return 0.0f; +} - const CharacterIndex startCharacter = line.characterRun.characterIndex; - const CharacterIndex endCharacter = line.characterRun.characterIndex + line.characterRun.numberOfCharacters; - DALI_ASSERT_DEBUG( endCharacter <= mLogicalModel->mText.Count() && "Invalid line info" ); +void Controller::UpdateAfterFontChange( std::string& newDefaultFont ) +{ + DALI_LOG_INFO( gLogFilter, Debug::Concise, "Controller::UpdateAfterFontChange"); - // Whether there is a hit on a glyph. - bool matched = false; + if ( !mImpl->mUserDefinedFontFamily ) // If user defined font then should not update when system font changes + { + DALI_LOG_INFO( gLogFilter, Debug::Concise, "Controller::UpdateAfterFontChange newDefaultFont(%s)\n", newDefaultFont.c_str() ); + ClearFontData(); + mImpl->mFontDefaults->mFontDescription.family = newDefaultFont; + mImpl->UpdateModel( ALL_OPERATIONS ); + mImpl->QueueModifyEvent( ModifyEvent::TEXT_REPLACED ); + mImpl->mRecalculateNaturalSize = true; + mImpl->RequestRelayout(); + } +} - // Traverses glyphs in visual order. To do that use the visual to logical conversion table. - CharacterIndex visualIndex = startCharacter; - for( ; !matched && ( visualIndex < endCharacter ); ++visualIndex ) - { - // The character in logical order. - const CharacterIndex characterLogicalOrderIndex = hasRightToLeftCharacters ? *( visualToLogicalBuffer + visualIndex ) : visualIndex; +void Controller::SetTextColor( const Vector4& textColor ) +{ + mImpl->mTextColor = textColor; - // The first glyph for that character in logical order. - const GlyphIndex glyphLogicalOrderIndex = *( charactersToGlyphBuffer + characterLogicalOrderIndex ); + if( !mImpl->IsShowingPlaceholderText() ) + { + mImpl->mVisualModel->SetTextColor( textColor ); - // The number of glyphs for that character - const Length numberOfGlyphs = *( glyphsPerCharacterBuffer + characterLogicalOrderIndex ); + mImpl->RequestRelayout(); + } +} - // Get the metrics for the group of glyphs. - GlyphMetrics glyphMetrics; - GetGlyphsMetrics( glyphLogicalOrderIndex, - numberOfGlyphs, - glyphMetrics ); +const Vector4& Controller::GetTextColor() const +{ + return mImpl->mTextColor; +} - const Vector2& position = *( positionsBuffer + glyphLogicalOrderIndex ); +bool Controller::RemoveText( int cursorOffset, int numberOfChars ) +{ + bool removed( false ); - const float glyphX = -glyphMetrics.xBearing + position.x + 0.5f * glyphMetrics.advance; + DALI_LOG_INFO( gLogFilter, Debug::General, "Controller::RemoveText %p mText.Count() %d cursor %d cursorOffset %d numberOfChars %d\n", + this, mImpl->mLogicalModel->mText.Count(), mImpl->mEventData->mPrimaryCursorPosition, cursorOffset, numberOfChars ); - if( visualX < glyphX ) - { - matched = true; - break; - } - } + if( !mImpl->IsShowingPlaceholderText() ) + { + // Delete at current cursor position + Vector& currentText = mImpl->mLogicalModel->mText; + CharacterIndex& oldCursorIndex = mImpl->mEventData->mPrimaryCursorPosition; - // Return the logical position of the cursor in characters. + CharacterIndex cursorIndex = oldCursorIndex; - if( !matched ) + // Validate the cursor position & number of characters + if( static_cast< CharacterIndex >( std::abs( cursorOffset ) ) <= cursorIndex ) { - visualIndex = endCharacter; + cursorIndex = oldCursorIndex + cursorOffset; } - return hasRightToLeftCharacters ? *( visualToLogicalCursorBuffer + visualIndex ) : visualIndex; - } + if( ( cursorIndex + numberOfChars ) > currentText.Count() ) + { + numberOfChars = currentText.Count() - cursorIndex; + } - /** - * @brief Calculates the cursor's position for a given character index in the logical order. - * - * It retrieves as well the line's height and the cursor's height and - * if there is a valid alternative cursor, its position and height. - * - * @param[in] logical The logical cursor position (in characters). 0 is just before the first character, a value equal to the number of characters is just after the last character. - * @param[out] cursorInfo The line's height, the cursor's height, the cursor's position and whether there is an alternative cursor. - */ - void GetCursorPosition( CharacterIndex logical, - CursorInfo& cursorInfo ) const - { - // TODO: Check for multiline with \n, etc... + if( ( cursorIndex + numberOfChars ) <= currentText.Count() ) + { + Vector::Iterator first = currentText.Begin() + cursorIndex; + Vector::Iterator last = first + numberOfChars; - // Check if the logical position is the first or the last one of the text. - const bool isFirstPosition = 0u == logical; - const bool isLastPosition = mLogicalModel->GetNumberOfCharacters() == logical; + currentText.Erase( first, last ); - if( isFirstPosition && isLastPosition ) - { - // There is zero characters. Get the default font. + // Cursor position retreat + oldCursorIndex = cursorIndex; - FontId defaultFontId = 0u; - if( NULL == mFontDefaults ) - { - defaultFontId = mFontClient.GetFontId( EMPTY_STRING, - EMPTY_STRING ); - } - else - { - defaultFontId = mFontDefaults->GetFontId( mFontClient ); - } + DALI_LOG_INFO( gLogFilter, Debug::General, "Controller::RemoveText %p removed %d\n", this, numberOfChars ); + removed = true; + } + } - Text::FontMetrics fontMetrics; - mFontClient.GetFontMetrics( defaultFontId, fontMetrics ); + return removed; +} - cursorInfo.lineHeight = fontMetrics.ascender - fontMetrics.descender; - cursorInfo.primaryCursorHeight = cursorInfo.lineHeight; +void Controller::SetPlaceholderTextColor( const Vector4& textColor ) +{ + if( mImpl->mEventData ) + { + mImpl->mEventData->mPlaceholderTextColor = textColor; + } - cursorInfo.primaryPosition.x = 0.f; - cursorInfo.primaryPosition.y = 0.f; + if( mImpl->IsShowingPlaceholderText() ) + { + mImpl->mVisualModel->SetTextColor( textColor ); + mImpl->RequestRelayout(); + } +} - // Nothing else to do. - return; - } +const Vector4& Controller::GetPlaceholderTextColor() const +{ + if( mImpl->mEventData ) + { + return mImpl->mEventData->mPlaceholderTextColor; + } - // Get the previous logical index. - const CharacterIndex previousLogical = isFirstPosition ? 0u : logical - 1u; + return Color::BLACK; +} - // Decrease the logical index if it's the last one. - if( isLastPosition ) - { - --logical; - } +void Controller::SetShadowOffset( const Vector2& shadowOffset ) +{ + mImpl->mVisualModel->SetShadowOffset( shadowOffset ); - // Get the direction of the character and the previous one. - const CharacterDirection* const modelCharacterDirectionsBuffer = ( 0u != mLogicalModel->mCharacterDirections.Count() ) ? mLogicalModel->mCharacterDirections.Begin() : NULL; + mImpl->RequestRelayout(); +} - CharacterDirection isCurrentRightToLeft = false; - CharacterDirection isPreviousRightToLeft = false; - if( NULL != modelCharacterDirectionsBuffer ) // If modelCharacterDirectionsBuffer is NULL, it means the whole text is left to right. - { - isCurrentRightToLeft = *( modelCharacterDirectionsBuffer + logical ); - isPreviousRightToLeft = *( modelCharacterDirectionsBuffer + previousLogical ); - } +const Vector2& Controller::GetShadowOffset() const +{ + return mImpl->mVisualModel->GetShadowOffset(); +} - // Get the line where the character is laid-out. - const LineRun* modelLines = mVisualModel->mLines.Begin(); +void Controller::SetShadowColor( const Vector4& shadowColor ) +{ + mImpl->mVisualModel->SetShadowColor( shadowColor ); + + mImpl->RequestRelayout(); +} - const LineIndex lineIndex = mVisualModel->GetLineOfCharacter( logical ); - const LineRun& line = *( modelLines + lineIndex ); +const Vector4& Controller::GetShadowColor() const +{ + return mImpl->mVisualModel->GetShadowColor(); +} - // Get the paragraph's direction. - const CharacterDirection isRightToLeftParagraph = line.direction; +void Controller::SetUnderlineColor( const Vector4& color ) +{ + mImpl->mVisualModel->SetUnderlineColor( color ); - // Check whether there is an alternative position: + mImpl->RequestRelayout(); +} - cursorInfo.isSecondaryCursor = ( isCurrentRightToLeft != isPreviousRightToLeft ) || - ( isLastPosition && ( isRightToLeftParagraph != isCurrentRightToLeft ) ); +const Vector4& Controller::GetUnderlineColor() const +{ + return mImpl->mVisualModel->GetUnderlineColor(); +} - // Set the line height. - cursorInfo.lineHeight = line.ascender + -line.descender; +void Controller::SetUnderlineEnabled( bool enabled ) +{ + mImpl->mVisualModel->SetUnderlineEnabled( enabled ); - // Convert the cursor position into the glyph position. - CharacterIndex characterIndex = logical; - if( cursorInfo.isSecondaryCursor && - ( isRightToLeftParagraph != isCurrentRightToLeft ) ) - { - characterIndex = previousLogical; - } + mImpl->RequestRelayout(); +} - const GlyphIndex currentGlyphIndex = *( mVisualModel->mCharactersToGlyph.Begin() + characterIndex ); - const Length numberOfGlyphs = *( mVisualModel->mGlyphsPerCharacter.Begin() + characterIndex ); - const Length numberOfCharacters = *( mVisualModel->mCharactersPerGlyph.Begin() +currentGlyphIndex ); +bool Controller::IsUnderlineEnabled() const +{ + return mImpl->mVisualModel->IsUnderlineEnabled(); +} - // Get the metrics for the group of glyphs. - GlyphMetrics glyphMetrics; - GetGlyphsMetrics( currentGlyphIndex, - numberOfGlyphs, - glyphMetrics ); +void Controller::SetUnderlineHeight( float height ) +{ + mImpl->mVisualModel->SetUnderlineHeight( height ); - float interGlyphAdvance = 0.f; - if( !isLastPosition && - ( numberOfCharacters > 1u ) ) - { - const CharacterIndex firstIndex = *( mVisualModel->mGlyphsToCharacters.Begin() + currentGlyphIndex ); - interGlyphAdvance = static_cast( characterIndex - firstIndex ) * glyphMetrics.advance / static_cast( numberOfCharacters ); - } + mImpl->RequestRelayout(); +} - // Get the glyph position and x bearing. - const Vector2& currentPosition = *( mVisualModel->mGlyphPositions.Begin() + currentGlyphIndex ); +float Controller::GetUnderlineHeight() const +{ + return mImpl->mVisualModel->GetUnderlineHeight(); +} - // Set the cursor's height. - cursorInfo.primaryCursorHeight = glyphMetrics.fontHeight; +void Controller::SetEnableCursorBlink( bool enable ) +{ + DALI_ASSERT_DEBUG( NULL != mImpl->mEventData && "TextInput disabled" ); - // Set the position. - cursorInfo.primaryPosition.x = -glyphMetrics.xBearing + currentPosition.x + ( isCurrentRightToLeft ? glyphMetrics.advance : interGlyphAdvance ); - cursorInfo.primaryPosition.y = line.ascender - glyphMetrics.ascender; + if( mImpl->mEventData ) + { + mImpl->mEventData->mCursorBlinkEnabled = enable; - if( isLastPosition ) + if( !enable && + mImpl->mEventData->mDecorator ) { - // The position of the cursor after the last character needs special - // care depending on its direction and the direction of the paragraph. + mImpl->mEventData->mDecorator->StopCursorBlink(); + } + } +} - if( cursorInfo.isSecondaryCursor ) - { - // Need to find the first character after the last character with the paragraph's direction. - // i.e l0 l1 l2 r0 r1 should find r0. +bool Controller::GetEnableCursorBlink() const +{ + if( mImpl->mEventData ) + { + return mImpl->mEventData->mCursorBlinkEnabled; + } + + return false; +} - // TODO: check for more than one line! - characterIndex = isRightToLeftParagraph ? line.characterRun.characterIndex : line.characterRun.characterIndex + line.characterRun.numberOfCharacters - 1u; - characterIndex = mLogicalModel->GetLogicalCharacterIndex( characterIndex ); +const Vector2& Controller::GetScrollPosition() const +{ + if( mImpl->mEventData ) + { + return mImpl->mEventData->mScrollPosition; + } - const GlyphIndex glyphIndex = *( mVisualModel->mCharactersToGlyph.Begin() + characterIndex ); - const Length numberOfGlyphs = *( mVisualModel->mGlyphsPerCharacter.Begin() + characterIndex ); + return Vector2::ZERO; +} - const Vector2& position = *( mVisualModel->mGlyphPositions.Begin() + glyphIndex ); +const Vector2& Controller::GetAlignmentOffset() const +{ + return mImpl->mAlignmentOffset; +} - // Get the metrics for the group of glyphs. - GlyphMetrics glyphMetrics; - GetGlyphsMetrics( glyphIndex, - numberOfGlyphs, - glyphMetrics ); +Vector3 Controller::GetNaturalSize() +{ + DALI_LOG_INFO( gLogFilter, Debug::Verbose, "-->Controller::GetNaturalSize\n" ); + Vector3 naturalSize; - cursorInfo.primaryPosition.x = -glyphMetrics.xBearing + position.x + ( isRightToLeftParagraph ? 0.f : glyphMetrics.advance ); + // Make sure the model is up-to-date before layouting + ProcessModifyEvents(); - cursorInfo.primaryPosition.y = line.ascender - glyphMetrics.ascender; - } - else - { - if( !isCurrentRightToLeft ) - { - cursorInfo.primaryPosition.x += glyphMetrics.advance; - } - else - { - cursorInfo.primaryPosition.x -= glyphMetrics.advance; - } - } - } + if( mImpl->mRecalculateNaturalSize ) + { + // Operations that can be done only once until the text changes. + const OperationsMask onlyOnceOperations = static_cast( CONVERT_TO_UTF32 | + GET_SCRIPTS | + VALIDATE_FONTS | + GET_LINE_BREAKS | + GET_WORD_BREAKS | + BIDI_INFO | + SHAPE_TEXT | + GET_GLYPH_METRICS ); + // Make sure the model is up-to-date before layouting + mImpl->UpdateModel( onlyOnceOperations ); - // Set the alternative cursor position. - if( cursorInfo.isSecondaryCursor ) - { - // Convert the cursor position into the glyph position. - const CharacterIndex previousCharacterIndex = ( ( isRightToLeftParagraph != isCurrentRightToLeft ) ? logical : previousLogical ); - const GlyphIndex previousGlyphIndex = *( mVisualModel->mCharactersToGlyph.Begin() + previousCharacterIndex ); - const Length numberOfGlyphs = *( mVisualModel->mGlyphsPerCharacter.Begin() + previousCharacterIndex ); + // Operations that need to be done if the size changes. + const OperationsMask sizeOperations = static_cast( LAYOUT | + ALIGN | + REORDER ); - // Get the glyph position. - const Vector2& previousPosition = *( mVisualModel->mGlyphPositions.Begin() + previousGlyphIndex ); + DoRelayout( Size( MAX_FLOAT, MAX_FLOAT ), + static_cast( onlyOnceOperations | + sizeOperations ), + naturalSize.GetVectorXY() ); - // Get the metrics for the group of glyphs. - GlyphMetrics glyphMetrics; - GetGlyphsMetrics( previousGlyphIndex, - numberOfGlyphs, - glyphMetrics ); + // Do not do again the only once operations. + mImpl->mOperationsPending = static_cast( mImpl->mOperationsPending & ~onlyOnceOperations ); - // Set the cursor position and height. - cursorInfo.secondaryPosition.x = -glyphMetrics.xBearing + previousPosition.x + ( ( ( isLastPosition && !isCurrentRightToLeft ) || - ( !isLastPosition && isCurrentRightToLeft ) ) ? glyphMetrics.advance : 0.f ); + // Do the size related operations again. + mImpl->mOperationsPending = static_cast( mImpl->mOperationsPending | sizeOperations ); - cursorInfo.secondaryCursorHeight = 0.5f * glyphMetrics.fontHeight; + // Stores the natural size to avoid recalculate it again + // unless the text/style changes. + mImpl->mVisualModel->SetNaturalSize( naturalSize.GetVectorXY() ); - cursorInfo.secondaryPosition.y = cursorInfo.lineHeight - cursorInfo.secondaryCursorHeight - line.descender - ( glyphMetrics.fontHeight - glyphMetrics.ascender ); + mImpl->mRecalculateNaturalSize = false; - // Update the primary cursor height as well. - cursorInfo.primaryCursorHeight *= 0.5f; - } + DALI_LOG_INFO( gLogFilter, Debug::Verbose, "<--Controller::GetNaturalSize calculated %f,%f,%f\n", naturalSize.x, naturalSize.y, naturalSize.z ); } - - /** - * @brief Get some glyph's metrics of a group of glyphs formed as a result of shaping one character. - * - * @param[in] glyphIndex The index to the first glyph. - * @param[in] numberOfGlyphs The number of glyphs. - * @param[out] glyphMetrics Some glyph metrics (font height, advance, ascender and x bearing). - */ - void GetGlyphsMetrics( GlyphIndex glyphIndex, - Length numberOfGlyphs, - GlyphMetrics& glyphMetrics ) const + else { - const GlyphInfo* glyphsBuffer = mVisualModel->mGlyphs.Begin(); - - const GlyphInfo& firstGlyph = *( glyphsBuffer + glyphIndex ); + naturalSize = mImpl->mVisualModel->GetNaturalSize(); - Text::FontMetrics fontMetrics; - mFontClient.GetFontMetrics( firstGlyph.fontId, fontMetrics ); + DALI_LOG_INFO( gLogFilter, Debug::Verbose, "<--Controller::GetNaturalSize cached %f,%f,%f\n", naturalSize.x, naturalSize.y, naturalSize.z ); + } - glyphMetrics.fontHeight = fontMetrics.height; - glyphMetrics.advance = firstGlyph.advance; - glyphMetrics.ascender = fontMetrics.ascender; - glyphMetrics.xBearing = firstGlyph.xBearing; + naturalSize.x = ConvertToEven( naturalSize.x ); + naturalSize.y = ConvertToEven( naturalSize.y ); - for( unsigned int i = 1u; i < numberOfGlyphs; ++i ) - { - const GlyphInfo& glyphInfo = *( glyphsBuffer + glyphIndex + i ); + return naturalSize; +} - glyphMetrics.advance += glyphInfo.advance; - } - } +float Controller::GetHeightForWidth( float width ) +{ + DALI_LOG_INFO( gLogFilter, Debug::Verbose, "-->Controller::GetHeightForWidth %p width %f\n", this, width ); + // Make sure the model is up-to-date before layouting + ProcessModifyEvents(); - /** - * @brief Calculates the new cursor index. - * - * It takes into account that in some scripts multiple characters can form a glyph and all of them - * need to be jumped with one key event. - * - * @param[in] index The initial new index. - * - * @return The new cursor index. - */ - CharacterIndex CalculateNewCursorIndex( CharacterIndex index ) const + Size layoutSize; + if( fabsf( width - mImpl->mVisualModel->mControlSize.width ) > Math::MACHINE_EPSILON_1000 ) { - CharacterIndex cursorIndex = mPrimaryCursorPosition; - - const Script script = mLogicalModel->GetScript( index ); - const GlyphIndex* charactersToGlyphBuffer = mVisualModel->mCharactersToGlyph.Begin(); - const Length* charactersPerGlyphBuffer = mVisualModel->mCharactersPerGlyph.Begin(); + // Operations that can be done only once until the text changes. + const OperationsMask onlyOnceOperations = static_cast( CONVERT_TO_UTF32 | + GET_SCRIPTS | + VALIDATE_FONTS | + GET_LINE_BREAKS | + GET_WORD_BREAKS | + BIDI_INFO | + SHAPE_TEXT | + GET_GLYPH_METRICS ); + // Make sure the model is up-to-date before layouting + mImpl->UpdateModel( onlyOnceOperations ); - Length numberOfCharacters = 0u; - if( TextAbstraction::LATIN == script ) - { - // Prevents to jump the whole Latin ligatures like fi, ff, ... - numberOfCharacters = 1u; - } - else - { - GlyphIndex glyphIndex = *( charactersToGlyphBuffer + index ); - numberOfCharacters = *( charactersPerGlyphBuffer + glyphIndex ); + // Operations that need to be done if the size changes. + const OperationsMask sizeOperations = static_cast( LAYOUT | + ALIGN | + REORDER ); - while( 0u == numberOfCharacters ) - { - numberOfCharacters = *( charactersPerGlyphBuffer + glyphIndex ); - ++glyphIndex; - } - } + DoRelayout( Size( width, MAX_FLOAT ), + static_cast( onlyOnceOperations | + sizeOperations ), + layoutSize ); - if( index < mPrimaryCursorPosition ) - { - cursorIndex -= numberOfCharacters; - } - else - { - cursorIndex += numberOfCharacters; - } + // Do not do again the only once operations. + mImpl->mOperationsPending = static_cast( mImpl->mOperationsPending & ~onlyOnceOperations ); - return cursorIndex; + // Do the size related operations again. + mImpl->mOperationsPending = static_cast( mImpl->mOperationsPending | sizeOperations ); + DALI_LOG_INFO( gLogFilter, Debug::Verbose, "<--Controller::GetHeightForWidth calculated %f\n", layoutSize.height ); } - - void UpdateCursorPosition() + else { - CursorInfo cursorInfo; + layoutSize = mImpl->mVisualModel->GetActualSize(); + DALI_LOG_INFO( gLogFilter, Debug::Verbose, "<--Controller::GetHeightForWidth cached %f\n", layoutSize.height ); + } - GetCursorPosition( mPrimaryCursorPosition, - cursorInfo ); + return layoutSize.height; +} - mDecorator->SetPosition( PRIMARY_CURSOR, - cursorInfo.primaryPosition.x, - cursorInfo.primaryPosition.y, - cursorInfo.primaryCursorHeight, - cursorInfo.lineHeight ); +bool Controller::Relayout( const Size& size ) +{ + DALI_LOG_INFO( gLogFilter, Debug::Verbose, "-->Controller::Relayout %p size %f,%f\n", this, size.width, size.height ); - if( cursorInfo.isSecondaryCursor ) + if( ( size.width < Math::MACHINE_EPSILON_1000 ) || ( size.height < Math::MACHINE_EPSILON_1000 ) ) + { + bool glyphsRemoved( false ); + if( 0u != mImpl->mVisualModel->mGlyphPositions.Count() ) { - mDecorator->SetActiveCursor( ACTIVE_CURSOR_BOTH ); - mDecorator->SetPosition( SECONDARY_CURSOR, - cursorInfo.secondaryPosition.x, - cursorInfo.secondaryPosition.y, - cursorInfo.secondaryCursorHeight, - cursorInfo.lineHeight ); + mImpl->mVisualModel->mGlyphPositions.Clear(); + glyphsRemoved = true; } - else - { - mDecorator->SetActiveCursor( ACTIVE_CURSOR_PRIMARY ); - } - - mUpdateCursorPosition = false; - mDecoratorUpdated = true; - } - - LogicalModelPtr mLogicalModel; - VisualModelPtr mVisualModel; - DecoratorPtr mDecorator; - FontDefaults* mFontDefaults; - TextAbstraction::FontClient& mFontClient; - std::string mPlaceholderText; - - /** - * This is used to delay handling events until after the model has been updated. - * The number of updates to the model is minimized to improve performance. - */ - vector mEventQueue; ///< The queue of touch events etc. - - State mState; ///< Selection mode, edit mode etc. - - CharacterIndex mPrimaryCursorPosition; ///< Index into logical model for primary cursor - CharacterIndex mSecondaryCursorPosition; ///< Index into logical model for secondary cursor - - /** - * 0,0 means that the top-left corner of the layout matches the top-left corner of the UI control. - * Typically this will have a negative value with scrolling occurs. - */ - Vector2 mScrollPosition; ///< The text is offset by this position when scrolling. - - bool mDecoratorUpdated : 1; ///< True if the decorator was updated during event processing - bool mCursorBlinkEnabled : 1; ///< True if cursor should blink when active - bool mGrabHandleEnabled : 1; ///< True if grab handle is enabled - bool mGrabHandlePopupEnabled : 1; ///< True if the grab handle popu-up should be shown - bool mSelectionEnabled : 1; ///< True if selection handles, highlight etc. are enabled - bool mHorizontalScrollingEnabled : 1; ///< True if horizontal scrolling is enabled - bool mVerticalScrollingEnabled : 1; ///< True if vertical scrolling is enabled - bool mUpdateCursorPosition : 1; ///< True if the visual position of the cursor must be recalculated -}; - -struct Controller::Impl -{ - Impl( ControlInterface& controlInterface ) - : mControlInterface( controlInterface ), - mLogicalModel(), - mVisualModel(), - mFontDefaults( NULL ), - mTextInput( NULL ), - mFontClient(), - mView(), - mLayoutEngine(), - mModifyEvents(), - mControlSize(), - mAlignmentOffset(), - mOperationsPending( NO_OPERATION ), - mRecalculateNaturalSize( true ) - { - mLogicalModel = LogicalModel::New(); - mVisualModel = VisualModel::New(); - - mFontClient = TextAbstraction::FontClient::Get(); - - mView.SetVisualModel( mVisualModel ); - - // Set the text properties to default - mVisualModel->SetTextColor( Color::WHITE ); - mVisualModel->SetShadowOffset( Vector2::ZERO ); - mVisualModel->SetShadowColor( Color::BLACK ); - mVisualModel->SetUnderlineEnabled( false ); - mVisualModel->SetUnderlineHeight( 0.0f ); - } - - ~Impl() - { - delete mTextInput; - } - - ControlInterface& mControlInterface; ///< Reference to the text controller. - LogicalModelPtr mLogicalModel; ///< Pointer to the logical model. - VisualModelPtr mVisualModel; ///< Pointer to the visual model. - FontDefaults* mFontDefaults; ///< Avoid allocating this when the user does not specify a font. - Controller::TextInput* mTextInput; ///< Avoid allocating everything for text input until EnableTextInput(). - TextAbstraction::FontClient mFontClient; ///< Handle to the font client. - View mView; ///< The view interface to the rendering back-end. - LayoutEngine mLayoutEngine; ///< The layout engine. - std::vector mModifyEvents; ///< Temporary stores the text set until the next relayout. - Size mControlSize; ///< The size of the control. - Vector2 mAlignmentOffset; ///< Vertical and horizontal offset of the whole text inside the control due to alignment. - OperationsMask mOperationsPending; ///< Operations pending to be done to layout the text. - bool mRecalculateNaturalSize:1; ///< Whether the natural size needs to be recalculated. -}; - -ControllerPtr Controller::New( ControlInterface& controlInterface ) -{ - return ControllerPtr( new Controller( controlInterface ) ); -} - -void Controller::SetText( const std::string& text ) -{ - // Cancel previously queued inserts etc. - mImpl->mModifyEvents.clear(); + // Not worth to relayout if width or height is equal to zero. + DALI_LOG_INFO( gLogFilter, Debug::Verbose, "<--Controller::Relayout (skipped)\n" ); + return glyphsRemoved; + } - // Keep until size negotiation - ModifyEvent event; - event.type = REPLACE_TEXT; - event.text = text; - mImpl->mModifyEvents.push_back( event ); + const bool newSize = ( size != mImpl->mVisualModel->mControlSize ); - if( mImpl->mTextInput ) + if( newSize ) { - // Cancel previously queued events - mImpl->mTextInput->mEventQueue.clear(); + DALI_LOG_INFO( gLogFilter, Debug::Verbose, "new size (previous size %f,%f)\n", mImpl->mVisualModel->mControlSize.width, mImpl->mVisualModel->mControlSize.height ); - // TODO - Hide selection decorations - } -} + // Operations that need to be done if the size changes. + mImpl->mOperationsPending = static_cast( mImpl->mOperationsPending | + LAYOUT | + ALIGN | + UPDATE_ACTUAL_SIZE | + REORDER ); -void Controller::GetText( std::string& text ) const -{ - if( !mImpl->mModifyEvents.empty() && - REPLACE_TEXT == mImpl->mModifyEvents[0].type ) - { - text = mImpl->mModifyEvents[0].text; - } - else - { - // TODO - Convert from UTF-32 + mImpl->mVisualModel->mControlSize = size; } -} -void Controller::SetPlaceholderText( const std::string& text ) -{ - if( !mImpl->mTextInput ) + // Make sure the model is up-to-date before layouting + ProcessModifyEvents(); + mImpl->UpdateModel( mImpl->mOperationsPending ); + + Size layoutSize; + bool updated = DoRelayout( mImpl->mVisualModel->mControlSize, + mImpl->mOperationsPending, + layoutSize ); + + // Do not re-do any operation until something changes. + mImpl->mOperationsPending = NO_OPERATION; + + // Keep the current offset and alignment as it will be used to update the decorator's positions (if the size changes). + Vector2 offset; + if( newSize && mImpl->mEventData ) { - mImpl->mTextInput->mPlaceholderText = text; + offset = mImpl->mAlignmentOffset + mImpl->mEventData->mScrollPosition; } -} -void Controller::GetPlaceholderText( std::string& text ) const -{ - if( !mImpl->mTextInput ) + // After doing the text layout, the alignment offset to place the actor in the desired position can be calculated. + CalculateTextAlignment( size ); + + if( mImpl->mEventData ) { - text = mImpl->mTextInput->mPlaceholderText; + if( newSize ) + { + // If there is a new size, the scroll position needs to be clamped. + mImpl->ClampHorizontalScroll( layoutSize ); + + // Update the decorator's positions is needed if there is a new size. + mImpl->mEventData->mDecorator->UpdatePositions( mImpl->mAlignmentOffset + mImpl->mEventData->mScrollPosition - offset ); + } + + // Move the cursor, grab handle etc. + updated = mImpl->ProcessInputEvents() || updated; } + + DALI_LOG_INFO( gLogFilter, Debug::Verbose, "<--Controller::Relayout\n" ); + return updated; } -void Controller::SetDefaultFontFamily( const std::string& defaultFontFamily ) +void Controller::ProcessModifyEvents() { - if( !mImpl->mFontDefaults ) - { - mImpl->mFontDefaults = new Controller::FontDefaults(); - } - - mImpl->mFontDefaults->mDefaultFontFamily = defaultFontFamily; - mImpl->mFontDefaults->mFontId = 0u; // Remove old font ID - mImpl->mOperationsPending = ALL_OPERATIONS; - mImpl->mRecalculateNaturalSize = true; - - // Clear the font-specific data - mImpl->mLogicalModel->mFontRuns.Clear(); - mImpl->mVisualModel->mGlyphs.Clear(); - mImpl->mVisualModel->mGlyphsToCharacters.Clear(); - mImpl->mVisualModel->mCharactersToGlyph.Clear(); - mImpl->mVisualModel->mCharactersPerGlyph.Clear(); - mImpl->mVisualModel->mGlyphsPerCharacter.Clear(); - mImpl->mVisualModel->mGlyphPositions.Clear(); - mImpl->mVisualModel->mLines.Clear(); - mImpl->mVisualModel->ClearCaches(); - - RequestRelayout(); -} + std::vector& events = mImpl->mModifyEvents; -const std::string& Controller::GetDefaultFontFamily() const -{ - if( mImpl->mFontDefaults ) + for( unsigned int i=0; imFontDefaults->mDefaultFontFamily; - } - - return EMPTY_STRING; -} + if( ModifyEvent::TEXT_REPLACED == events[i].type ) + { + // A (single) replace event should come first, otherwise we wasted time processing NOOP events + DALI_ASSERT_DEBUG( 0 == i && "Unexpected TEXT_REPLACED event" ); -void Controller::SetDefaultFontStyle( const std::string& defaultFontStyle ) -{ - if( !mImpl->mFontDefaults ) - { - mImpl->mFontDefaults = new Controller::FontDefaults(); + TextReplacedEvent(); + } + else if( ModifyEvent::TEXT_INSERTED == events[i].type ) + { + TextInsertedEvent(); + } + else if( ModifyEvent::TEXT_DELETED == events[i].type ) + { + // Placeholder-text cannot be deleted + if( !mImpl->IsShowingPlaceholderText() ) + { + TextDeletedEvent(); + } + } } - mImpl->mFontDefaults->mDefaultFontStyle = defaultFontStyle; - mImpl->mFontDefaults->mFontId = 0u; // Remove old font ID - mImpl->mOperationsPending = ALL_OPERATIONS; - mImpl->mRecalculateNaturalSize = true; - - // Clear the font-specific data - mImpl->mLogicalModel->mFontRuns.Clear(); - mImpl->mVisualModel->mGlyphs.Clear(); - mImpl->mVisualModel->mGlyphsToCharacters.Clear(); - mImpl->mVisualModel->mCharactersToGlyph.Clear(); - mImpl->mVisualModel->mCharactersPerGlyph.Clear(); - mImpl->mVisualModel->mGlyphsPerCharacter.Clear(); - mImpl->mVisualModel->mGlyphPositions.Clear(); - mImpl->mVisualModel->mLines.Clear(); - mImpl->mVisualModel->ClearCaches(); - - RequestRelayout(); -} - -const std::string& Controller::GetDefaultFontStyle() const -{ - if( mImpl->mFontDefaults ) + if( mImpl->mEventData && + 0 != events.size() ) { - return mImpl->mFontDefaults->mDefaultFontStyle; + // When the text is being modified, delay cursor blinking + mImpl->mEventData->mDecorator->DelayCursorBlink(); } - return EMPTY_STRING; + // Discard temporary text + events.clear(); } -void Controller::SetDefaultPointSize( float pointSize ) +void Controller::ResetText() { - if( !mImpl->mFontDefaults ) - { - mImpl->mFontDefaults = new Controller::FontDefaults(); - } + // Reset buffers. + mImpl->mLogicalModel->mText.Clear(); + ClearModelData(); - mImpl->mFontDefaults->mDefaultPointSize = pointSize; - mImpl->mFontDefaults->mFontId = 0u; // Remove old font ID - mImpl->mOperationsPending = ALL_OPERATIONS; - mImpl->mRecalculateNaturalSize = true; + // We have cleared everything including the placeholder-text + mImpl->PlaceholderCleared(); - // Clear the font-specific data - mImpl->mLogicalModel->mFontRuns.Clear(); - mImpl->mVisualModel->mGlyphs.Clear(); - mImpl->mVisualModel->mGlyphsToCharacters.Clear(); - mImpl->mVisualModel->mCharactersToGlyph.Clear(); - mImpl->mVisualModel->mCharactersPerGlyph.Clear(); - mImpl->mVisualModel->mGlyphsPerCharacter.Clear(); - mImpl->mVisualModel->mGlyphPositions.Clear(); - mImpl->mVisualModel->mLines.Clear(); - mImpl->mVisualModel->ClearCaches(); + // The natural size needs to be re-calculated. + mImpl->mRecalculateNaturalSize = true; - RequestRelayout(); + // Apply modifications to the model + mImpl->mOperationsPending = ALL_OPERATIONS; } -float Controller::GetDefaultPointSize() const +void Controller::ResetCursorPosition( CharacterIndex cursorIndex ) { - if( mImpl->mFontDefaults ) + // Reset the cursor position + if( NULL != mImpl->mEventData ) { - return mImpl->mFontDefaults->mDefaultPointSize; - } + mImpl->mEventData->mPrimaryCursorPosition = cursorIndex; - return 0.0f; + // Update the cursor if it's in editing mode. + if ( EventData::IsEditingState( mImpl->mEventData->mState ) ) + { + mImpl->mEventData->mUpdateCursorPosition = true; + } + } } -void Controller::GetDefaultFonts( Vector& fonts, Length numberOfCharacters ) const +void Controller::ResetScrollPosition() { - if( mImpl->mFontDefaults ) + if( NULL != mImpl->mEventData ) { - FontRun fontRun; - fontRun.characterRun.characterIndex = 0; - fontRun.characterRun.numberOfCharacters = numberOfCharacters; - fontRun.fontId = mImpl->mFontDefaults->GetFontId( mImpl->mFontClient ); - fontRun.isDefault = true; - - fonts.PushBack( fontRun ); + // Reset the scroll position. + mImpl->mEventData->mScrollPosition = Vector2::ZERO; + mImpl->mEventData->mScrollAfterUpdatePosition = true; } } -const Vector4& Controller::GetTextColor() const +void Controller::TextReplacedEvent() { - return mImpl->mVisualModel->GetTextColor(); -} + // Reset buffers. + ClearModelData(); -const Vector2& Controller::GetShadowOffset() const -{ - return mImpl->mVisualModel->GetShadowOffset(); -} + // The natural size needs to be re-calculated. + mImpl->mRecalculateNaturalSize = true; -const Vector4& Controller::GetShadowColor() const -{ - return mImpl->mVisualModel->GetShadowColor(); + // Apply modifications to the model + mImpl->mOperationsPending = ALL_OPERATIONS; + mImpl->UpdateModel( ALL_OPERATIONS ); + mImpl->mOperationsPending = static_cast( LAYOUT | + ALIGN | + UPDATE_ACTUAL_SIZE | + REORDER ); } -const Vector4& Controller::GetUnderlineColor() const +void Controller::TextInsertedEvent() { - return mImpl->mVisualModel->GetUnderlineColor(); -} + DALI_ASSERT_DEBUG( NULL != mImpl->mEventData && "Unexpected TextInsertedEvent" ); -bool Controller::IsUnderlineEnabled() const -{ - return mImpl->mVisualModel->IsUnderlineEnabled(); -} + // TODO - Optimize this + ClearModelData(); -float Controller::GetUnderlineHeight() const -{ - return mImpl->mVisualModel->GetUnderlineHeight(); -} + // The natural size needs to be re-calculated. + mImpl->mRecalculateNaturalSize = true; -void Controller::SetTextColor( const Vector4& textColor ) -{ - mImpl->mVisualModel->SetTextColor( textColor ); -} + // Apply modifications to the model; TODO - Optimize this + mImpl->mOperationsPending = ALL_OPERATIONS; + mImpl->UpdateModel( ALL_OPERATIONS ); + mImpl->mOperationsPending = static_cast( LAYOUT | + ALIGN | + UPDATE_ACTUAL_SIZE | + REORDER ); -void Controller::SetShadowOffset( const Vector2& shadowOffset ) -{ - mImpl->mVisualModel->SetShadowOffset( shadowOffset ); + // Queue a cursor reposition event; this must wait until after DoRelayout() + if ( EventData::IsEditingState( mImpl->mEventData->mState ) ) + { + mImpl->mEventData->mUpdateCursorPosition = true; + mImpl->mEventData->mScrollAfterUpdatePosition = true; + } } -void Controller::SetShadowColor( const Vector4& shadowColor ) +void Controller::TextDeletedEvent() { - mImpl->mVisualModel->SetShadowColor( shadowColor ); -} + DALI_ASSERT_DEBUG( NULL != mImpl->mEventData && "Unexpected TextDeletedEvent" ); -void Controller::SetUnderlineColor( const Vector4& color ) -{ - mImpl->mVisualModel->SetUnderlineColor( color ); -} + // TODO - Optimize this + ClearModelData(); -void Controller::SetUnderlineEnabled( bool enabled ) -{ - mImpl->mVisualModel->SetUnderlineEnabled( enabled ); -} + // The natural size needs to be re-calculated. + mImpl->mRecalculateNaturalSize = true; -void Controller::SetUnderlineHeight( float height ) -{ - mImpl->mVisualModel->SetUnderlineHeight( height ); -} + // Apply modifications to the model; TODO - Optimize this + mImpl->mOperationsPending = ALL_OPERATIONS; + mImpl->UpdateModel( ALL_OPERATIONS ); + mImpl->mOperationsPending = static_cast( LAYOUT | + ALIGN | + UPDATE_ACTUAL_SIZE | + REORDER ); -void Controller::EnableTextInput( DecoratorPtr decorator ) -{ - if( !mImpl->mTextInput ) + // Queue a cursor reposition event; this must wait until after DoRelayout() + mImpl->mEventData->mUpdateCursorPosition = true; + if( 0u != mImpl->mLogicalModel->mText.Count() ) { - mImpl->mTextInput = new TextInput( mImpl->mLogicalModel, - mImpl->mVisualModel, - decorator, - mImpl->mFontDefaults, - mImpl->mFontClient ); + mImpl->mEventData->mScrollAfterDelete = true; } } -void Controller::SetEnableCursorBlink( bool enable ) +bool Controller::DoRelayout( const Size& size, + OperationsMask operationsRequired, + Size& layoutSize ) { - DALI_ASSERT_DEBUG( NULL != mImpl->mTextInput && "TextInput disabled" ); + DALI_LOG_INFO( gLogFilter, Debug::Verbose, "-->Controller::DoRelayout %p size %f,%f\n", this, size.width, size.height ); + bool viewUpdated( false ); - if( mImpl->mTextInput ) + // Calculate the operations to be done. + const OperationsMask operations = static_cast( mImpl->mOperationsPending & operationsRequired ); + + if( LAYOUT & operations ) { - mImpl->mTextInput->mCursorBlinkEnabled = enable; + // Some vectors with data needed to layout and reorder may be void + // after the first time the text has been laid out. + // Fill the vectors again. - if( !enable && - mImpl->mTextInput->mDecorator ) + const Length numberOfGlyphs = mImpl->mVisualModel->mGlyphs.Count(); + + if( 0u == numberOfGlyphs ) { - mImpl->mTextInput->mDecorator->StopCursorBlink(); + // Nothing else to do if there is no glyphs. + DALI_LOG_INFO( gLogFilter, Debug::Verbose, "<--Controller::DoRelayout no glyphs, view updated true\n" ); + return true; } - } -} -bool Controller::GetEnableCursorBlink() const -{ - if( mImpl->mTextInput ) - { - return mImpl->mTextInput->mCursorBlinkEnabled; - } + const Vector& lineBreakInfo = mImpl->mLogicalModel->mLineBreakInfo; + const Vector& wordBreakInfo = mImpl->mLogicalModel->mWordBreakInfo; + const Vector& characterDirection = mImpl->mLogicalModel->mCharacterDirections; + const Vector& glyphs = mImpl->mVisualModel->mGlyphs; + const Vector& glyphsToCharactersMap = mImpl->mVisualModel->mGlyphsToCharacters; + const Vector& charactersPerGlyph = mImpl->mVisualModel->mCharactersPerGlyph; + const Character* const textBuffer = mImpl->mLogicalModel->mText.Begin(); - return false; -} + // Set the layout parameters. + LayoutParameters layoutParameters( size, + textBuffer, + lineBreakInfo.Begin(), + wordBreakInfo.Begin(), + ( 0u != characterDirection.Count() ) ? characterDirection.Begin() : NULL, + numberOfGlyphs, + glyphs.Begin(), + glyphsToCharactersMap.Begin(), + charactersPerGlyph.Begin() ); -const Vector2& Controller::GetScrollPosition() const -{ - if( mImpl->mTextInput ) - { - return mImpl->mTextInput->mScrollPosition; - } + // The laid-out lines. + // It's not possible to know in how many lines the text is going to be laid-out, + // but it can be resized at least with the number of 'paragraphs' to avoid + // some re-allocations. + Vector& lines = mImpl->mVisualModel->mLines; - return Vector2::ZERO; -} + // Delete any previous laid out lines before setting the new ones. + lines.Clear(); -const Vector2& Controller::GetAlignmentOffset() const -{ - return mImpl->mAlignmentOffset; -} + // The capacity of the bidirectional paragraph info is the number of paragraphs. + lines.Reserve( mImpl->mLogicalModel->mBidirectionalParagraphInfo.Capacity() ); -Vector3 Controller::GetNaturalSize() -{ - Vector3 naturalSize; + // Resize the vector of positions to have the same size than the vector of glyphs. + Vector& glyphPositions = mImpl->mVisualModel->mGlyphPositions; + glyphPositions.Resize( numberOfGlyphs ); - // Make sure the model is up-to-date before layouting - ProcessModifyEvents(); + // Whether the last character is a new paragraph character. + layoutParameters.isLastNewParagraph = TextAbstraction::IsNewParagraph( *( textBuffer + ( mImpl->mLogicalModel->mText.Count() - 1u ) ) ); - if( mImpl->mRecalculateNaturalSize ) - { - // Operations that can be done only once until the text changes. - const OperationsMask onlyOnceOperations = static_cast( CONVERT_TO_UTF32 | - GET_SCRIPTS | - VALIDATE_FONTS | - GET_LINE_BREAKS | - GET_WORD_BREAKS | - BIDI_INFO | - SHAPE_TEXT | - GET_GLYPH_METRICS ); - // Make sure the model is up-to-date before layouting - UpdateModel( onlyOnceOperations ); + // Update the visual model. + viewUpdated = mImpl->mLayoutEngine.LayoutText( layoutParameters, + glyphPositions, + lines, + layoutSize ); - // Operations that need to be done if the size changes. - const OperationsMask sizeOperations = static_cast( LAYOUT | - ALIGN | - REORDER ); + if( viewUpdated ) + { + // Reorder the lines + if( REORDER & operations ) + { + Vector& bidirectionalInfo = mImpl->mLogicalModel->mBidirectionalParagraphInfo; - DoRelayout( Size( MAX_FLOAT, MAX_FLOAT ), - static_cast( onlyOnceOperations | - sizeOperations ), - naturalSize.GetVectorXY() ); + // Check first if there are paragraphs with bidirectional info. + if( 0u != bidirectionalInfo.Count() ) + { + // Get the lines + const Length numberOfLines = mImpl->mVisualModel->mLines.Count(); - // Do not do again the only once operations. - mImpl->mOperationsPending = static_cast( mImpl->mOperationsPending & ~onlyOnceOperations ); + // Reorder the lines. + Vector lineBidirectionalInfoRuns; + lineBidirectionalInfoRuns.Reserve( numberOfLines ); // Reserve because is not known yet how many lines have right to left characters. + ReorderLines( bidirectionalInfo, + lines, + lineBidirectionalInfoRuns ); - // Do the size related operations again. - mImpl->mOperationsPending = static_cast( mImpl->mOperationsPending | sizeOperations ); + // Set the bidirectional info into the model. + const Length numberOfBidirectionalInfoRuns = lineBidirectionalInfoRuns.Count(); + mImpl->mLogicalModel->SetVisualToLogicalMap( lineBidirectionalInfoRuns.Begin(), + numberOfBidirectionalInfoRuns ); - // Stores the natural size to avoid recalculate it again - // unless the text/style changes. - mImpl->mVisualModel->SetNaturalSize( naturalSize.GetVectorXY() ); + // Set the bidirectional info per line into the layout parameters. + layoutParameters.lineBidirectionalInfoRunsBuffer = lineBidirectionalInfoRuns.Begin(); + layoutParameters.numberOfBidirectionalInfoRuns = numberOfBidirectionalInfoRuns; - mImpl->mRecalculateNaturalSize = false; + // Get the character to glyph conversion table and set into the layout. + layoutParameters.charactersToGlyphsBuffer = mImpl->mVisualModel->mCharactersToGlyph.Begin(); + + // Get the glyphs per character table and set into the layout. + layoutParameters.glyphsPerCharacterBuffer = mImpl->mVisualModel->mGlyphsPerCharacter.Begin(); + + // Re-layout the text. Reorder those lines with right to left characters. + mImpl->mLayoutEngine.ReLayoutRightToLeftLines( layoutParameters, + glyphPositions ); + + // Free the allocated memory used to store the conversion table in the bidirectional line info run. + for( Vector::Iterator it = lineBidirectionalInfoRuns.Begin(), + endIt = lineBidirectionalInfoRuns.End(); + it != endIt; + ++it ) + { + BidirectionalLineInfoRun& bidiLineInfo = *it; + + free( bidiLineInfo.visualToLogicalMap ); + } + } + } // REORDER + + // Sets the actual size. + if( UPDATE_ACTUAL_SIZE & operations ) + { + mImpl->mVisualModel->SetActualSize( layoutSize ); + } + } // view updated } else { - naturalSize = mImpl->mVisualModel->GetNaturalSize(); + layoutSize = mImpl->mVisualModel->GetActualSize(); } - return naturalSize; + if( ALIGN & operations ) + { + // The laid-out lines. + Vector& lines = mImpl->mVisualModel->mLines; + + mImpl->mLayoutEngine.Align( layoutSize, + lines ); + + viewUpdated = true; + } + + DALI_LOG_INFO( gLogFilter, Debug::Verbose, "<--Controller::DoRelayout, view updated %s\n", ( viewUpdated ? "true" : "false" ) ); + return viewUpdated; } -float Controller::GetHeightForWidth( float width ) +void Controller::SetMultiLineEnabled( bool enable ) { - // Make sure the model is up-to-date before layouting - ProcessModifyEvents(); + const LayoutEngine::Layout layout = enable ? LayoutEngine::MULTI_LINE_BOX : LayoutEngine::SINGLE_LINE_BOX; - Size layoutSize; - if( width != mImpl->mControlSize.width ) + if( layout != mImpl->mLayoutEngine.GetLayout() ) { - // Operations that can be done only once until the text changes. - const OperationsMask onlyOnceOperations = static_cast( CONVERT_TO_UTF32 | - GET_SCRIPTS | - VALIDATE_FONTS | - GET_LINE_BREAKS | - GET_WORD_BREAKS | - BIDI_INFO | - SHAPE_TEXT | - GET_GLYPH_METRICS ); - // Make sure the model is up-to-date before layouting - UpdateModel( onlyOnceOperations ); + // Set the layout type. + mImpl->mLayoutEngine.SetLayout( layout ); - // Operations that need to be done if the size changes. - const OperationsMask sizeOperations = static_cast( LAYOUT | - ALIGN | - REORDER ); - - DoRelayout( Size( width, MAX_FLOAT ), - static_cast( onlyOnceOperations | - sizeOperations ), - layoutSize ); + // Set the flags to redo the layout operations + const OperationsMask layoutOperations = static_cast( LAYOUT | + UPDATE_ACTUAL_SIZE | + ALIGN | + REORDER ); - // Do not do again the only once operations. - mImpl->mOperationsPending = static_cast( mImpl->mOperationsPending & ~onlyOnceOperations ); + mImpl->mOperationsPending = static_cast( mImpl->mOperationsPending | layoutOperations ); - // Do the size related operations again. - mImpl->mOperationsPending = static_cast( mImpl->mOperationsPending | sizeOperations ); - } - else - { - layoutSize = mImpl->mVisualModel->GetActualSize(); + mImpl->RequestRelayout(); } +} - return layoutSize.height; +bool Controller::IsMultiLineEnabled() const +{ + return LayoutEngine::MULTI_LINE_BOX == mImpl->mLayoutEngine.GetLayout(); } -bool Controller::Relayout( const Size& size ) +void Controller::SetHorizontalAlignment( LayoutEngine::HorizontalAlignment alignment ) { - if( ( size.width < Math::MACHINE_EPSILON_1000 ) || ( size.height < Math::MACHINE_EPSILON_1000 ) ) + if( alignment != mImpl->mLayoutEngine.GetHorizontalAlignment() ) { - bool glyphsRemoved( false ); - if( 0u != mImpl->mVisualModel->GetNumberOfGlyphPositions() ) - { - mImpl->mVisualModel->SetGlyphPositions( NULL, 0u ); - glyphsRemoved = true; - } - - // Not worth to relayout if width or height is equal to zero. - return glyphsRemoved; - } + // Set the alignment. + mImpl->mLayoutEngine.SetHorizontalAlignment( alignment ); - if( size != mImpl->mControlSize ) - { - // Operations that need to be done if the size changes. - mImpl->mOperationsPending = static_cast( mImpl->mOperationsPending | - LAYOUT | - ALIGN | - UPDATE_ACTUAL_SIZE | - REORDER ); + // Set the flag to redo the alignment operation. + mImpl->mOperationsPending = static_cast( mImpl->mOperationsPending | ALIGN ); - mImpl->mControlSize = size; + mImpl->RequestRelayout(); } +} - // Make sure the model is up-to-date before layouting - ProcessModifyEvents(); - UpdateModel( mImpl->mOperationsPending ); - - Size layoutSize; - bool updated = DoRelayout( mImpl->mControlSize, - mImpl->mOperationsPending, - layoutSize ); +LayoutEngine::HorizontalAlignment Controller::GetHorizontalAlignment() const +{ + return mImpl->mLayoutEngine.GetHorizontalAlignment(); +} - // Do not re-do any operation until something changes. - mImpl->mOperationsPending = NO_OPERATION; +void Controller::SetVerticalAlignment( LayoutEngine::VerticalAlignment alignment ) +{ + if( alignment != mImpl->mLayoutEngine.GetVerticalAlignment() ) + { + // Set the alignment. + mImpl->mLayoutEngine.SetVerticalAlignment( alignment ); - // After doing the text layout, the alignment offset to place the actor in the desired position can be calculated. - CalculateTextAlignment( size ); + mImpl->mOperationsPending = static_cast( mImpl->mOperationsPending | ALIGN ); - if( mImpl->mTextInput ) - { - // Move the cursor, grab handle etc. - updated = mImpl->mTextInput->ProcessInputEvents( mImpl->mControlSize, mImpl->mAlignmentOffset ) || updated; + mImpl->RequestRelayout(); } +} - return updated; +LayoutEngine::VerticalAlignment Controller::GetVerticalAlignment() const +{ + return mImpl->mLayoutEngine.GetVerticalAlignment(); } -void Controller::ProcessModifyEvents() +void Controller::CalculateTextAlignment( const Size& size ) { - std::vector& events = mImpl->mModifyEvents; + // Get the direction of the first character. + const CharacterDirection firstParagraphDirection = mImpl->mLogicalModel->GetCharacterDirection( 0u ); - for( unsigned int i=0; imVisualModel->GetActualSize(); + if( fabsf( actualSize.height ) < Math::MACHINE_EPSILON_1000 ) { - if( REPLACE_TEXT == events[0].type ) - { - // A (single) replace event should come first, otherwise we wasted time processing NOOP events - DALI_ASSERT_DEBUG( 0 == i && "Unexpected REPLACE event" ); + // Get the line height of the default font. + actualSize.height = mImpl->GetDefaultFontLineHeight(); + } - ReplaceTextEvent( events[0].text ); - } - else if( INSERT_TEXT == events[0].type ) + // If the first paragraph is right to left swap ALIGN_BEGIN and ALIGN_END; + LayoutEngine::HorizontalAlignment horizontalAlignment = mImpl->mLayoutEngine.GetHorizontalAlignment(); + if( firstParagraphDirection && + ( LayoutEngine::HORIZONTAL_ALIGN_CENTER != horizontalAlignment ) ) + { + if( LayoutEngine::HORIZONTAL_ALIGN_BEGIN == horizontalAlignment ) { - InsertTextEvent( events[0].text ); + horizontalAlignment = LayoutEngine::HORIZONTAL_ALIGN_END; } - else if( DELETE_TEXT == events[0].type ) + else { - DeleteTextEvent(); + horizontalAlignment = LayoutEngine::HORIZONTAL_ALIGN_BEGIN; } } - // Discard temporary text - events.clear(); -} - -void Controller::ReplaceTextEvent( const std::string& text ) -{ - // Reset buffers. - mImpl->mLogicalModel->mText.Clear(); - mImpl->mLogicalModel->mScriptRuns.Clear(); - mImpl->mLogicalModel->mFontRuns.Clear(); - mImpl->mLogicalModel->mLineBreakInfo.Clear(); - mImpl->mLogicalModel->mWordBreakInfo.Clear(); - mImpl->mLogicalModel->mBidirectionalParagraphInfo.Clear(); - mImpl->mLogicalModel->mCharacterDirections.Clear(); - mImpl->mLogicalModel->mBidirectionalLineInfo.Clear(); - mImpl->mLogicalModel->mLogicalToVisualMap.Clear(); - mImpl->mLogicalModel->mVisualToLogicalMap.Clear(); - mImpl->mVisualModel->mGlyphs.Clear(); - mImpl->mVisualModel->mGlyphsToCharacters.Clear(); - mImpl->mVisualModel->mCharactersToGlyph.Clear(); - mImpl->mVisualModel->mCharactersPerGlyph.Clear(); - mImpl->mVisualModel->mGlyphsPerCharacter.Clear(); - mImpl->mVisualModel->mGlyphPositions.Clear(); - mImpl->mVisualModel->mLines.Clear(); - mImpl->mVisualModel->ClearCaches(); - - // Convert text into UTF-32 - Vector& utf32Characters = mImpl->mLogicalModel->mText; - utf32Characters.Resize( text.size() ); - - // This is a bit horrible but std::string returns a (signed) char* - const uint8_t* utf8 = reinterpret_cast( text.c_str() ); - - // Transform a text array encoded in utf8 into an array encoded in utf32. - // It returns the actual number of characters. - Length characterCount = Utf8ToUtf32( utf8, text.size(), utf32Characters.Begin() ); - utf32Characters.Resize( characterCount ); - - // Reset the cursor position - if( mImpl->mTextInput ) + switch( horizontalAlignment ) { - mImpl->mTextInput->mPrimaryCursorPosition = characterCount; - // TODO - handle secondary cursor + case LayoutEngine::HORIZONTAL_ALIGN_BEGIN: + { + mImpl->mAlignmentOffset.x = 0.f; + break; + } + case LayoutEngine::HORIZONTAL_ALIGN_CENTER: + { + mImpl->mAlignmentOffset.x = floorf( 0.5f * ( size.width - actualSize.width ) ); // try to avoid pixel alignment. + break; + } + case LayoutEngine::HORIZONTAL_ALIGN_END: + { + mImpl->mAlignmentOffset.x = size.width - actualSize.width; + break; + } } - // The natural size needs to be re-calculated. - mImpl->mRecalculateNaturalSize = true; - - // Apply modifications to the model - mImpl->mOperationsPending = ALL_OPERATIONS; - UpdateModel( ALL_OPERATIONS ); - mImpl->mOperationsPending = static_cast( LAYOUT | - ALIGN | - UPDATE_ACTUAL_SIZE | - REORDER ); + const LayoutEngine::VerticalAlignment verticalAlignment = mImpl->mLayoutEngine.GetVerticalAlignment(); + switch( verticalAlignment ) + { + case LayoutEngine::VERTICAL_ALIGN_TOP: + { + mImpl->mAlignmentOffset.y = 0.f; + break; + } + case LayoutEngine::VERTICAL_ALIGN_CENTER: + { + mImpl->mAlignmentOffset.y = floorf( 0.5f * ( size.height - actualSize.height ) ); // try to avoid pixel alignment. + break; + } + case LayoutEngine::VERTICAL_ALIGN_BOTTOM: + { + mImpl->mAlignmentOffset.y = size.height - actualSize.height; + break; + } + } } -void Controller::InsertTextEvent( const std::string& text ) +LayoutEngine& Controller::GetLayoutEngine() { - DALI_ASSERT_DEBUG( NULL != mImpl->mTextInput && "Unexpected InsertTextEvent" ); - - // TODO - Optimize this - mImpl->mLogicalModel->mScriptRuns.Clear(); - mImpl->mLogicalModel->mFontRuns.Clear(); - mImpl->mLogicalModel->mLineBreakInfo.Clear(); - mImpl->mLogicalModel->mWordBreakInfo.Clear(); - mImpl->mLogicalModel->mBidirectionalParagraphInfo.Clear(); - mImpl->mLogicalModel->mCharacterDirections.Clear(); - mImpl->mLogicalModel->mBidirectionalLineInfo.Clear(); - mImpl->mLogicalModel->mLogicalToVisualMap.Clear(); - mImpl->mLogicalModel->mVisualToLogicalMap.Clear(); - mImpl->mVisualModel->mGlyphs.Clear(); - mImpl->mVisualModel->mGlyphsToCharacters.Clear(); - mImpl->mVisualModel->mCharactersToGlyph.Clear(); - mImpl->mVisualModel->mCharactersPerGlyph.Clear(); - mImpl->mVisualModel->mGlyphsPerCharacter.Clear(); - mImpl->mVisualModel->mGlyphPositions.Clear(); - mImpl->mVisualModel->mLines.Clear(); - mImpl->mVisualModel->ClearCaches(); + return mImpl->mLayoutEngine; +} - // Convert text into UTF-32 - Vector utf32Characters; - utf32Characters.Resize( text.size() ); +View& Controller::GetView() +{ + return mImpl->mView; +} - // This is a bit horrible but std::string returns a (signed) char* - const uint8_t* utf8 = reinterpret_cast( text.c_str() ); +void Controller::KeyboardFocusGainEvent() +{ + DALI_ASSERT_DEBUG( mImpl->mEventData && "Unexpected KeyboardFocusGainEvent" ); - // Transform a text array encoded in utf8 into an array encoded in utf32. - // It returns the actual number of characters. - Length characterCount = Utf8ToUtf32( utf8, text.size(), utf32Characters.Begin() ); - utf32Characters.Resize( characterCount ); + if( mImpl->mEventData ) + { + if( ( EventData::INACTIVE == mImpl->mEventData->mState ) || + ( EventData::INTERRUPTED == mImpl->mEventData->mState ) ) + { + mImpl->ChangeState( EventData::EDITING ); + mImpl->mEventData->mUpdateCursorPosition = true; //If editing started without tap event, cursor update must be triggered. + } - // Insert at current cursor position - Vector& modifyText = mImpl->mLogicalModel->mText; - CharacterIndex& cursorIndex = mImpl->mTextInput->mPrimaryCursorPosition; + if( mImpl->IsShowingPlaceholderText() ) + { + // Show alternative placeholder-text when editing + ShowPlaceholderText(); + } - if( cursorIndex < modifyText.Count() ) - { - modifyText.Insert( modifyText.Begin() + cursorIndex, utf32Characters.Begin(), utf32Characters.End() ); + mImpl->RequestRelayout(); } - else +} + +void Controller::KeyboardFocusLostEvent() +{ + DALI_ASSERT_DEBUG( mImpl->mEventData && "Unexpected KeyboardFocusLostEvent" ); + + if( mImpl->mEventData ) { - modifyText.Insert( modifyText.End(), utf32Characters.Begin(), utf32Characters.End() ); + if ( EventData::INTERRUPTED != mImpl->mEventData->mState ) + { + mImpl->ChangeState( EventData::INACTIVE ); + + if( !mImpl->IsShowingRealText() ) + { + // Revert to regular placeholder-text when not editing + ShowPlaceholderText(); + } + } } + mImpl->RequestRelayout(); +} - // Advance the cursor position - ++cursorIndex; +bool Controller::KeyEvent( const Dali::KeyEvent& keyEvent ) +{ + DALI_ASSERT_DEBUG( mImpl->mEventData && "Unexpected KeyEvent" ); - // The natural size needs to be re-calculated. - mImpl->mRecalculateNaturalSize = true; + bool textChanged( false ); - // Apply modifications to the model; TODO - Optimize this - mImpl->mOperationsPending = ALL_OPERATIONS; - UpdateModel( ALL_OPERATIONS ); - mImpl->mOperationsPending = static_cast( LAYOUT | - ALIGN | - UPDATE_ACTUAL_SIZE | - REORDER ); + if( mImpl->mEventData && + keyEvent.state == KeyEvent::Down ) + { + int keyCode = keyEvent.keyCode; + const std::string& keyString = keyEvent.keyPressed; - // Queue a cursor reposition event; this must wait until after DoRelayout() - mImpl->mTextInput->mUpdateCursorPosition = true; -} + // Pre-process to separate modifying events from non-modifying input events. + if( Dali::DALI_KEY_ESCAPE == keyCode ) + { + // Escape key is a special case which causes focus loss + KeyboardFocusLostEvent(); + } + else if( Dali::DALI_KEY_CURSOR_LEFT == keyCode || + Dali::DALI_KEY_CURSOR_RIGHT == keyCode || + Dali::DALI_KEY_CURSOR_UP == keyCode || + Dali::DALI_KEY_CURSOR_DOWN == keyCode ) + { + Event event( Event::CURSOR_KEY_EVENT ); + event.p1.mInt = keyCode; + mImpl->mEventData->mEventQueue.push_back( event ); + } + else if( Dali::DALI_KEY_BACKSPACE == keyCode ) + { + textChanged = BackspaceKeyEvent(); + } + else if ( IsKey( keyEvent, Dali::DALI_KEY_POWER ) ) + { + mImpl->ChangeState( EventData::INTERRUPTED ); // State is not INACTIVE as expect to return to edit mode. + // Avoids calling the InsertText() method which can delete selected text + } + else if ( IsKey( keyEvent, Dali::DALI_KEY_MENU ) || + IsKey( keyEvent, Dali::DALI_KEY_HOME ) ) + { + mImpl->ChangeState( EventData::INACTIVE ); + // Menu/Home key behaviour does not allow edit mode to resume like Power key + // Avoids calling the InsertText() method which can delete selected text + } + else if( Dali::DALI_KEY_SHIFT_LEFT == keyCode ) + { + // DALI_KEY_SHIFT_LEFT is the key code for the Left Shift. It's sent (by the imf?) when the predictive text is enabled + // and a character is typed after the type of a upper case latin character. -void Controller::DeleteTextEvent() -{ - DALI_ASSERT_DEBUG( NULL != mImpl->mTextInput && "Unexpected InsertTextEvent" ); + // Do nothing. + } + else + { + DALI_LOG_INFO( gLogFilter, Debug::Verbose, "Controller::KeyEvent %p keyString %s\n", this, keyString.c_str() ); - // TODO - Optimize this - mImpl->mLogicalModel->mScriptRuns.Clear(); - mImpl->mLogicalModel->mFontRuns.Clear(); - mImpl->mLogicalModel->mLineBreakInfo.Clear(); - mImpl->mLogicalModel->mWordBreakInfo.Clear(); - mImpl->mLogicalModel->mBidirectionalParagraphInfo.Clear(); - mImpl->mLogicalModel->mCharacterDirections.Clear(); - mImpl->mLogicalModel->mBidirectionalLineInfo.Clear(); - mImpl->mLogicalModel->mLogicalToVisualMap.Clear(); - mImpl->mLogicalModel->mVisualToLogicalMap.Clear(); - mImpl->mVisualModel->mGlyphs.Clear(); - mImpl->mVisualModel->mGlyphsToCharacters.Clear(); - mImpl->mVisualModel->mCharactersToGlyph.Clear(); - mImpl->mVisualModel->mCharactersPerGlyph.Clear(); - mImpl->mVisualModel->mGlyphsPerCharacter.Clear(); - mImpl->mVisualModel->mGlyphPositions.Clear(); - mImpl->mVisualModel->mLines.Clear(); - mImpl->mVisualModel->ClearCaches(); + // IMF manager is no longer handling key-events + mImpl->ClearPreEditFlag(); - // Delte at current cursor position - Vector& modifyText = mImpl->mLogicalModel->mText; - CharacterIndex& cursorIndex = mImpl->mTextInput->mPrimaryCursorPosition; + InsertText( keyString, COMMIT ); + textChanged = true; + } - if( cursorIndex > 0 && - cursorIndex-1 < modifyText.Count() ) - { - modifyText.Remove( modifyText.Begin() + cursorIndex - 1 ); + if ( ( mImpl->mEventData->mState != EventData::INTERRUPTED ) && + ( mImpl->mEventData->mState != EventData::INACTIVE ) ) + { + mImpl->ChangeState( EventData::EDITING ); + } - // Cursor position retreat - --cursorIndex; + mImpl->RequestRelayout(); } - // The natural size needs to be re-calculated. - mImpl->mRecalculateNaturalSize = true; - - // Apply modifications to the model; TODO - Optimize this - mImpl->mOperationsPending = ALL_OPERATIONS; - UpdateModel( ALL_OPERATIONS ); - mImpl->mOperationsPending = static_cast( LAYOUT | - ALIGN | - UPDATE_ACTUAL_SIZE | - REORDER ); + if( textChanged ) + { + // Do this last since it provides callbacks into application code + mImpl->mControlInterface.TextChanged(); + } - // Queue a cursor reposition event; this must wait until after DoRelayout() - mImpl->mTextInput->mUpdateCursorPosition = true; + return false; } -void Controller::UpdateModel( OperationsMask operationsRequired ) +void Controller::InsertText( const std::string& text, Controller::InsertType type ) { - // Calculate the operations to be done. - const OperationsMask operations = static_cast( mImpl->mOperationsPending & operationsRequired ); + bool removedPrevious( false ); + bool maxLengthReached( false ); - Vector& utf32Characters = mImpl->mLogicalModel->mText; + DALI_ASSERT_DEBUG( NULL != mImpl->mEventData && "Unexpected InsertText" ) + DALI_LOG_INFO( gLogFilter, Debug::Verbose, "Controller::InsertText %p %s (%s) mPrimaryCursorPosition %d mPreEditFlag %d mPreEditStartPosition %d mPreEditLength %d\n", + this, text.c_str(), (COMMIT == type ? "COMMIT" : "PRE_EDIT"), + mImpl->mEventData->mPrimaryCursorPosition, mImpl->mEventData->mPreEditFlag, mImpl->mEventData->mPreEditStartPosition, mImpl->mEventData->mPreEditLength ); - const Length numberOfCharacters = mImpl->mLogicalModel->GetNumberOfCharacters(); + // TODO: At the moment the underline runs are only for pre-edit. + mImpl->mVisualModel->mUnderlineRuns.Clear(); + + Vector utf32Characters; + Length characterCount( 0u ); - Vector& lineBreakInfo = mImpl->mLogicalModel->mLineBreakInfo; - if( GET_LINE_BREAKS & operations ) + // Remove the previous IMF pre-edit (predicitive text) + if( mImpl->mEventData && + mImpl->mEventData->mPreEditFlag && + 0 != mImpl->mEventData->mPreEditLength ) { - // Retrieves the line break info. The line break info is used to split the text in 'paragraphs' to - // calculate the bidirectional info for each 'paragraph'. - // It's also used to layout the text (where it should be a new line) or to shape the text (text in different lines - // is not shaped together). - lineBreakInfo.Resize( numberOfCharacters, TextAbstraction::LINE_NO_BREAK ); + CharacterIndex offset = mImpl->mEventData->mPrimaryCursorPosition - mImpl->mEventData->mPreEditStartPosition; - SetLineBreakInfo( utf32Characters, - lineBreakInfo ); + removedPrevious = RemoveText( -static_cast(offset), mImpl->mEventData->mPreEditLength ); + + mImpl->mEventData->mPrimaryCursorPosition = mImpl->mEventData->mPreEditStartPosition; + mImpl->mEventData->mPreEditLength = 0; + } + else + { + // Remove the previous Selection + removedPrevious = RemoveSelectedText(); } - Vector& wordBreakInfo = mImpl->mLogicalModel->mWordBreakInfo; - if( GET_WORD_BREAKS & operations ) + if( !text.empty() ) { - // Retrieves the word break info. The word break info is used to layout the text (where to wrap the text in lines). - wordBreakInfo.Resize( numberOfCharacters, TextAbstraction::WORD_NO_BREAK ); + // Convert text into UTF-32 + utf32Characters.Resize( text.size() ); - SetWordBreakInfo( utf32Characters, - wordBreakInfo ); - } + // This is a bit horrible but std::string returns a (signed) char* + const uint8_t* utf8 = reinterpret_cast( text.c_str() ); - const bool getScripts = GET_SCRIPTS & operations; - const bool validateFonts = VALIDATE_FONTS & operations; + // Transform a text array encoded in utf8 into an array encoded in utf32. + // It returns the actual number of characters. + characterCount = Utf8ToUtf32( utf8, text.size(), utf32Characters.Begin() ); + utf32Characters.Resize( characterCount ); - Vector& scripts = mImpl->mLogicalModel->mScriptRuns; - Vector& validFonts = mImpl->mLogicalModel->mFontRuns; + DALI_ASSERT_DEBUG( text.size() >= utf32Characters.Count() && "Invalid UTF32 conversion length" ); + DALI_LOG_INFO( gLogFilter, Debug::Verbose, "UTF8 size %d, UTF32 size %d\n", text.size(), utf32Characters.Count() ); + } - if( getScripts || validateFonts ) + if( 0u != utf32Characters.Count() ) // Check if Utf8ToUtf32 conversion succeeded { - // Validates the fonts assigned by the application or assigns default ones. - // It makes sure all the characters are going to be rendered by the correct font. - MultilanguageSupport multilanguageSupport = MultilanguageSupport::Get(); - - if( getScripts ) + // The placeholder text is no longer needed + if( mImpl->IsShowingPlaceholderText() ) { - // Retrieves the scripts used in the text. - multilanguageSupport.SetScripts( utf32Characters, - lineBreakInfo, - scripts ); + ResetText(); } - if( validateFonts ) + mImpl->ChangeState( EventData::EDITING ); + + // Handle the IMF (predicitive text) state changes + if( mImpl->mEventData ) { - if( 0u == validFonts.Count() ) + if( COMMIT == type ) { - // Copy the requested font defaults received via the property system. - // These may not be valid i.e. may not contain glyphs for the necessary scripts. - GetDefaultFonts( validFonts, numberOfCharacters ); + // IMF manager is no longer handling key-events + mImpl->ClearPreEditFlag(); } + else // PRE_EDIT + { + if( !mImpl->mEventData->mPreEditFlag ) + { + DALI_LOG_INFO( gLogFilter, Debug::Verbose, "Entered PreEdit state" ); - // Validates the fonts. If there is a character with no assigned font it sets a default one. - // After this call, fonts are validated. - multilanguageSupport.ValidateFonts( utf32Characters, - scripts, - validFonts ); - } - } - - Vector mirroredUtf32Characters; - bool textMirrored = false; - if( BIDI_INFO & operations ) - { - // Count the number of LINE_NO_BREAK to reserve some space for the vector of paragraph's - // bidirectional info. + // Record the start of the pre-edit text + mImpl->mEventData->mPreEditStartPosition = mImpl->mEventData->mPrimaryCursorPosition; + } - Length numberOfParagraphs = 0u; + mImpl->mEventData->mPreEditLength = utf32Characters.Count(); + mImpl->mEventData->mPreEditFlag = true; - const TextAbstraction::LineBreakInfo* lineBreakInfoBuffer = lineBreakInfo.Begin(); - for( Length index = 0u; index < numberOfCharacters; ++index ) - { - if( TextAbstraction::LINE_NO_BREAK == *( lineBreakInfoBuffer + index ) ) - { - ++numberOfParagraphs; + DALI_LOG_INFO( gLogFilter, Debug::Verbose, "mPreEditStartPosition %d mPreEditLength %d\n", mImpl->mEventData->mPreEditStartPosition, mImpl->mEventData->mPreEditLength ); } } - Vector& bidirectionalInfo = mImpl->mLogicalModel->mBidirectionalParagraphInfo; - bidirectionalInfo.Reserve( numberOfParagraphs ); - - // Calculates the bidirectional info for the whole paragraph if it contains right to left scripts. - SetBidirectionalInfo( utf32Characters, - scripts, - lineBreakInfo, - bidirectionalInfo ); + const Length numberOfCharactersInModel = mImpl->mLogicalModel->mText.Count(); - if( 0u != bidirectionalInfo.Count() ) - { - // This paragraph has right to left text. Some characters may need to be mirrored. - // TODO: consider if the mirrored string can be stored as well. + // Restrict new text to fit within Maximum characters setting + Length maxSizeOfNewText = std::min ( ( mImpl->mMaximumNumberOfCharacters - numberOfCharactersInModel ), characterCount ); + maxLengthReached = ( characterCount > maxSizeOfNewText ); - textMirrored = GetMirroredText( utf32Characters, mirroredUtf32Characters ); + // Insert at current cursor position + CharacterIndex& cursorIndex = mImpl->mEventData->mPrimaryCursorPosition; - // Only set the character directions if there is right to left characters. - Vector& directions = mImpl->mLogicalModel->mCharacterDirections; - directions.Resize( numberOfCharacters ); + Vector& modifyText = mImpl->mLogicalModel->mText; - GetCharactersDirection( bidirectionalInfo, - directions ); + if( cursorIndex < numberOfCharactersInModel ) + { + modifyText.Insert( modifyText.Begin() + cursorIndex, utf32Characters.Begin(), utf32Characters.Begin() + maxSizeOfNewText ); } else { - // There is no right to left characters. Clear the directions vector. - mImpl->mLogicalModel->mCharacterDirections.Clear(); + modifyText.Insert( modifyText.End(), utf32Characters.Begin(), utf32Characters.Begin() + maxSizeOfNewText ); } - } + cursorIndex += maxSizeOfNewText; + + DALI_LOG_INFO( gLogFilter, Debug::Verbose, "Inserted %d characters, new size %d new cursor %d\n", maxSizeOfNewText, mImpl->mLogicalModel->mText.Count(), mImpl->mEventData->mPrimaryCursorPosition ); + } + + if( 0u == mImpl->mLogicalModel->mText.Count() && + mImpl->IsPlaceholderAvailable() ) + { + // Show place-holder if empty after removing the pre-edit text + ShowPlaceholderText(); + mImpl->mEventData->mUpdateCursorPosition = true; + mImpl->ClearPreEditFlag(); + } + else if( removedPrevious || + 0 != utf32Characters.Count() ) + { + // Queue an inserted event + mImpl->QueueModifyEvent( ModifyEvent::TEXT_INSERTED ); + } - Vector& glyphs = mImpl->mVisualModel->mGlyphs; - Vector& glyphsToCharactersMap = mImpl->mVisualModel->mGlyphsToCharacters; - Vector& charactersPerGlyph = mImpl->mVisualModel->mCharactersPerGlyph; - if( SHAPE_TEXT & operations ) + if( maxLengthReached ) { - const Vector& textToShape = textMirrored ? mirroredUtf32Characters : utf32Characters; - // Shapes the text. - ShapeText( textToShape, - lineBreakInfo, - scripts, - validFonts, - glyphs, - glyphsToCharactersMap, - charactersPerGlyph ); + DALI_LOG_INFO( gLogFilter, Debug::Verbose, "MaxLengthReached (%d)\n", mImpl->mLogicalModel->mText.Count() ); + + mImpl->ResetImfManager(); - // Create the 'number of glyphs' per character and the glyph to character conversion tables. - mImpl->mVisualModel->CreateGlyphsPerCharacterTable( numberOfCharacters ); - mImpl->mVisualModel->CreateCharacterToGlyphTable( numberOfCharacters ); + // Do this last since it provides callbacks into application code + mImpl->mControlInterface.MaxLengthReached(); } +} - const Length numberOfGlyphs = glyphs.Count(); +bool Controller::RemoveSelectedText() +{ + bool textRemoved( false ); - if( GET_GLYPH_METRICS & operations ) + if( EventData::SELECTING == mImpl->mEventData->mState ) { - mImpl->mFontClient.GetGlyphMetrics( glyphs.Begin(), numberOfGlyphs ); + std::string removedString; + mImpl->RetrieveSelection( removedString, true ); + + if( !removedString.empty() ) + { + textRemoved = true; + mImpl->ChangeState( EventData::EDITING ); + } } + + return textRemoved; } -bool Controller::DoRelayout( const Size& size, - OperationsMask operationsRequired, - Size& layoutSize ) +void Controller::TapEvent( unsigned int tapCount, float x, float y ) { - bool viewUpdated( false ); - - // Calculate the operations to be done. - const OperationsMask operations = static_cast( mImpl->mOperationsPending & operationsRequired ); + DALI_ASSERT_DEBUG( mImpl->mEventData && "Unexpected TapEvent" ); - if( LAYOUT & operations ) + if( NULL != mImpl->mEventData ) { - // Some vectors with data needed to layout and reorder may be void - // after the first time the text has been laid out. - // Fill the vectors again. + DALI_LOG_INFO( gLogFilter, Debug::Concise, "TapEvent state:%d \n", mImpl->mEventData->mState ); + + if( 1u == tapCount ) + { + // This is to avoid unnecessary relayouts when tapping an empty text-field + bool relayoutNeeded( false ); - Length numberOfGlyphs = mImpl->mVisualModel->GetNumberOfGlyphs(); + if ( EventData::EDITING_WITH_PASTE_POPUP == mImpl->mEventData->mState || EventData::EDITING_WITH_PASTE_POPUP == mImpl->mEventData->mState ) + { + mImpl->ChangeState( EventData::EDITING_WITH_GRAB_HANDLE); // If Popup shown hide it here so can be shown again if required. + } - if( 0u == numberOfGlyphs ) + if( mImpl->IsShowingRealText() && ( EventData::INACTIVE != mImpl->mEventData->mState ) ) + { + // Already in an active state so show a popup + if ( !mImpl->IsClipboardEmpty() ) + { + // Shows Paste popup but could show full popup with Selection options. ( EDITING_WITH_POPUP ) + mImpl->ChangeState( EventData::EDITING_WITH_PASTE_POPUP ); + } + else + { + mImpl->ChangeState( EventData::EDITING_WITH_GRAB_HANDLE ); + } + relayoutNeeded = true; + } + else + { + if( mImpl->IsShowingPlaceholderText() && !mImpl->IsFocusedPlaceholderAvailable() ) + { + // Hide placeholder text + ResetText(); + } + + if ( EventData::INACTIVE == mImpl->mEventData->mState ) + { + mImpl->ChangeState( EventData::EDITING ); + } + else if ( !mImpl->IsClipboardEmpty() ) + { + mImpl->ChangeState( EventData::EDITING_WITH_POPUP ); + } + relayoutNeeded = true; + } + + // Handles & cursors must be repositioned after Relayout() i.e. after the Model has been updated + if( relayoutNeeded ) + { + Event event( Event::TAP_EVENT ); + event.p1.mUint = tapCount; + event.p2.mFloat = x; + event.p3.mFloat = y; + mImpl->mEventData->mEventQueue.push_back( event ); + + mImpl->RequestRelayout(); + } + } + else if( 2u == tapCount ) { - // Nothing else to do if there is no glyphs. - return true; + if( mImpl->mEventData->mSelectionEnabled && + mImpl->IsShowingRealText() ) + { + SelectEvent( x, y, false ); + } } + } - Vector& lineBreakInfo = mImpl->mLogicalModel->mLineBreakInfo; - Vector& wordBreakInfo = mImpl->mLogicalModel->mWordBreakInfo; - Vector& characterDirection = mImpl->mLogicalModel->mCharacterDirections; - Vector& glyphs = mImpl->mVisualModel->mGlyphs; - Vector& glyphsToCharactersMap = mImpl->mVisualModel->mGlyphsToCharacters; - Vector& charactersPerGlyph = mImpl->mVisualModel->mCharactersPerGlyph; + // Reset keyboard as tap event has occurred. + mImpl->ResetImfManager(); +} - // Set the layout parameters. - LayoutParameters layoutParameters( size, - mImpl->mLogicalModel->mText.Begin(), - lineBreakInfo.Begin(), - wordBreakInfo.Begin(), - ( 0u != characterDirection.Count() ) ? characterDirection.Begin() : NULL, - numberOfGlyphs, - glyphs.Begin(), - glyphsToCharactersMap.Begin(), - charactersPerGlyph.Begin() ); +void Controller::PanEvent( Gesture::State state, const Vector2& displacement ) + // Show cursor and grabhandle on first tap, this matches the behaviour of tapping when already editing +{ + DALI_ASSERT_DEBUG( mImpl->mEventData && "Unexpected PanEvent" ); - // The laid-out lines. - // It's not possible to know in how many lines the text is going to be laid-out, - // but it can be resized at least with the number of 'paragraphs' to avoid - // some re-allocations. - Vector& lines = mImpl->mVisualModel->mLines; + if( mImpl->mEventData ) + { + Event event( Event::PAN_EVENT ); + event.p1.mInt = state; + event.p2.mFloat = displacement.x; + event.p3.mFloat = displacement.y; + mImpl->mEventData->mEventQueue.push_back( event ); - // Delete any previous laid out lines before setting the new ones. - lines.Clear(); + mImpl->RequestRelayout(); + } +} - // The capacity of the bidirectional paragraph info is the number of paragraphs. - lines.Reserve( mImpl->mLogicalModel->mBidirectionalParagraphInfo.Capacity() ); +void Controller::LongPressEvent( Gesture::State state, float x, float y ) +{ + DALI_ASSERT_DEBUG( mImpl->mEventData && "Unexpected LongPressEvent" ); - // Resize the vector of positions to have the same size than the vector of glyphs. - Vector& glyphPositions = mImpl->mVisualModel->mGlyphPositions; - glyphPositions.Resize( numberOfGlyphs ); + if( state == Gesture::Started && + mImpl->mEventData ) + { + if( ! mImpl->IsShowingRealText() ) + { + Event event( Event::LONG_PRESS_EVENT ); + event.p1.mInt = state; + mImpl->mEventData->mEventQueue.push_back( event ); + mImpl->RequestRelayout(); + } + else + { + // The 1st long-press on inactive text-field is treated as tap + if( EventData::INACTIVE == mImpl->mEventData->mState ) + { + mImpl->ChangeState( EventData::EDITING ); - // Update the visual model. - viewUpdated = mImpl->mLayoutEngine.LayoutText( layoutParameters, - glyphPositions, - lines, - layoutSize ); + Event event( Event::TAP_EVENT ); + event.p1.mUint = 1; + event.p2.mFloat = x; + event.p3.mFloat = y; + mImpl->mEventData->mEventQueue.push_back( event ); - if( viewUpdated ) - { - // Reorder the lines - if( REORDER & operations ) + mImpl->RequestRelayout(); + } + else { - Vector& bidirectionalInfo = mImpl->mLogicalModel->mBidirectionalParagraphInfo; + // Reset the imf manger to commit the pre-edit before selecting the text. + mImpl->ResetImfManager(); - // Check first if there are paragraphs with bidirectional info. - if( 0u != bidirectionalInfo.Count() ) - { - // Get the lines - const Length numberOfLines = mImpl->mVisualModel->GetNumberOfLines(); + SelectEvent( x, y, false ); + } + } + } +} - // Reorder the lines. - Vector lineBidirectionalInfoRuns; - lineBidirectionalInfoRuns.Reserve( numberOfLines ); // Reserve because is not known yet how many lines have right to left characters. - ReorderLines( bidirectionalInfo, - lines, - lineBidirectionalInfoRuns ); +void Controller::SelectEvent( float x, float y, bool selectAll ) +{ + DALI_LOG_INFO( gLogFilter, Debug::Verbose, "Controller::SelectEvent\n" ); - // Set the bidirectional info into the model. - const Length numberOfBidirectionalInfoRuns = lineBidirectionalInfoRuns.Count(); - mImpl->mLogicalModel->SetVisualToLogicalMap( lineBidirectionalInfoRuns.Begin(), - numberOfBidirectionalInfoRuns ); + if( mImpl->mEventData ) + { + mImpl->ChangeState( EventData::SELECTING ); - // Set the bidirectional info per line into the layout parameters. - layoutParameters.lineBidirectionalInfoRunsBuffer = lineBidirectionalInfoRuns.Begin(); - layoutParameters.numberOfBidirectionalInfoRuns = numberOfBidirectionalInfoRuns; + if( selectAll ) + { + Event event( Event::SELECT_ALL ); + mImpl->mEventData->mEventQueue.push_back( event ); + } + else + { + Event event( Event::SELECT ); + event.p2.mFloat = x; + event.p3.mFloat = y; + mImpl->mEventData->mEventQueue.push_back( event ); + } - // Get the character to glyph conversion table and set into the layout. - layoutParameters.charactersToGlyphsBuffer = mImpl->mVisualModel->mCharactersToGlyph.Begin(); + mImpl->RequestRelayout(); + } +} - // Get the glyphs per character table and set into the layout. - layoutParameters.glyphsPerCharacterBuffer = mImpl->mVisualModel->mGlyphsPerCharacter.Begin(); +void Controller::GetTargetSize( Vector2& targetSize ) +{ + targetSize = mImpl->mVisualModel->mControlSize; +} - // Re-layout the text. Reorder those lines with right to left characters. - mImpl->mLayoutEngine.ReLayoutRightToLeftLines( layoutParameters, - glyphPositions ); +void Controller::AddDecoration( Actor& actor, bool needsClipping ) +{ + mImpl->mControlInterface.AddDecoration( actor, needsClipping ); +} - // Free the allocated memory used to store the conversion table in the bidirectional line info run. - for( Vector::Iterator it = lineBidirectionalInfoRuns.Begin(), - endIt = lineBidirectionalInfoRuns.End(); - it != endIt; - ++it ) - { - BidirectionalLineInfoRun& bidiLineInfo = *it; +void Controller::DecorationEvent( HandleType handleType, HandleState state, float x, float y ) +{ + DALI_ASSERT_DEBUG( mImpl->mEventData && "Unexpected DecorationEvent" ); - free( bidiLineInfo.visualToLogicalMap ); - } - } - } // REORDER + if( mImpl->mEventData ) + { + switch( handleType ) + { + case GRAB_HANDLE: + { + Event event( Event::GRAB_HANDLE_EVENT ); + event.p1.mUint = state; + event.p2.mFloat = x; + event.p3.mFloat = y; - if( ALIGN & operations ) + mImpl->mEventData->mEventQueue.push_back( event ); + break; + } + case LEFT_SELECTION_HANDLE: { - mImpl->mLayoutEngine.Align( layoutParameters, - layoutSize, - lines, - glyphPositions ); + Event event( Event::LEFT_SELECTION_HANDLE_EVENT ); + event.p1.mUint = state; + event.p2.mFloat = x; + event.p3.mFloat = y; + + mImpl->mEventData->mEventQueue.push_back( event ); + break; } + case RIGHT_SELECTION_HANDLE: + { + Event event( Event::RIGHT_SELECTION_HANDLE_EVENT ); + event.p1.mUint = state; + event.p2.mFloat = x; + event.p3.mFloat = y; - // Sets the actual size. - if( UPDATE_ACTUAL_SIZE & operations ) + mImpl->mEventData->mEventQueue.push_back( event ); + break; + } + case LEFT_SELECTION_HANDLE_MARKER: + case RIGHT_SELECTION_HANDLE_MARKER: { - mImpl->mVisualModel->SetActualSize( layoutSize ); + // Markers do not move the handles. + break; } - } // view updated - } - else - { - layoutSize = mImpl->mVisualModel->GetActualSize(); + case HANDLE_TYPE_COUNT: + { + DALI_ASSERT_DEBUG( !"Controller::HandleEvent. Unexpected handle type" ); + } + } + + mImpl->RequestRelayout(); } +} - return viewUpdated; +void Controller::PasteText( const std::string& stringToPaste ) +{ + InsertText( stringToPaste, Text::Controller::COMMIT ); + mImpl->ChangeState( EventData::EDITING ); + mImpl->RequestRelayout(); + + // Do this last since it provides callbacks into application code + mImpl->mControlInterface.TextChanged(); } -void Controller::CalculateTextAlignment( const Size& size ) +void Controller::PasteClipboardItemEvent() { - // Get the direction of the first character. - const CharacterDirection firstParagraphDirection = mImpl->mLogicalModel->GetCharacterDirection( 0u ); + // Retrieve the clipboard contents first + ClipboardEventNotifier notifier( ClipboardEventNotifier::Get() ); + std::string stringToPaste( notifier.GetContent() ); - const Size& actualSize = mImpl->mVisualModel->GetActualSize(); + // Commit the current pre-edit text; the contents of the clipboard should be appended + mImpl->ResetImfManager(); - // If the first paragraph is right to left swap ALIGN_BEGIN and ALIGN_END; - LayoutEngine::HorizontalAlignment horizontalAlignment = mImpl->mLayoutEngine.GetHorizontalAlignment(); - if( firstParagraphDirection && - ( LayoutEngine::HORIZONTAL_ALIGN_CENTER != horizontalAlignment ) ) + // Paste + PasteText( stringToPaste ); +} + +void Controller::TextPopupButtonTouched( Dali::Toolkit::TextSelectionPopup::Buttons button ) +{ + if( NULL == mImpl->mEventData ) { - if( LayoutEngine::HORIZONTAL_ALIGN_BEGIN == horizontalAlignment ) + return; + } + + switch( button ) + { + case Toolkit::TextSelectionPopup::CUT: { - horizontalAlignment = LayoutEngine::HORIZONTAL_ALIGN_END; + mImpl->SendSelectionToClipboard( true ); // Synchronous call to modify text + mImpl->mOperationsPending = ALL_OPERATIONS; + + // This is to reset the virtual keyboard to Upper-case + if( 0u == mImpl->mLogicalModel->mText.Count() ) + { + NotifyImfManager(); + } + + if( 0u != mImpl->mLogicalModel->mText.Count() || + !mImpl->IsPlaceholderAvailable() ) + { + mImpl->QueueModifyEvent( ModifyEvent::TEXT_DELETED ); + } + else + { + ShowPlaceholderText(); + mImpl->mEventData->mUpdateCursorPosition = true; + } + mImpl->RequestRelayout(); + mImpl->mControlInterface.TextChanged(); + break; } - else + case Toolkit::TextSelectionPopup::COPY: { - horizontalAlignment = LayoutEngine::HORIZONTAL_ALIGN_BEGIN; + mImpl->SendSelectionToClipboard( false ); // Text not modified + mImpl->RequestRelayout(); // Handles, Selection Highlight, Popup + break; } - } + case Toolkit::TextSelectionPopup::PASTE: + { + std::string stringToPaste(""); + mImpl->GetTextFromClipboard( 0, stringToPaste ); // Paste latest item from system clipboard + PasteText( stringToPaste ); + break; + } + case Toolkit::TextSelectionPopup::SELECT: + { + const Vector2& currentCursorPosition = mImpl->mEventData->mDecorator->GetPosition( PRIMARY_CURSOR ); - switch( horizontalAlignment ) - { - case LayoutEngine::HORIZONTAL_ALIGN_BEGIN: + if( mImpl->mEventData->mSelectionEnabled ) + { + // Creates a SELECT event. + SelectEvent( currentCursorPosition.x, currentCursorPosition.y, false ); + } + break; + } + case Toolkit::TextSelectionPopup::SELECT_ALL: { - mImpl->mAlignmentOffset.x = 0.f; + // Creates a SELECT_ALL event + SelectEvent( 0.f, 0.f, true ); break; } - case LayoutEngine::HORIZONTAL_ALIGN_CENTER: + case Toolkit::TextSelectionPopup::CLIPBOARD: { - const int intOffset = static_cast( 0.5f * ( size.width - actualSize.width ) ); // try to avoid pixel alignment. - mImpl->mAlignmentOffset.x = static_cast( intOffset ); + mImpl->ShowClipboard(); break; } - case LayoutEngine::HORIZONTAL_ALIGN_END: + case Toolkit::TextSelectionPopup::NONE: { - mImpl->mAlignmentOffset.x = size.width - actualSize.width; + // Nothing to do. break; } } +} - const LayoutEngine::VerticalAlignment verticalAlignment = mImpl->mLayoutEngine.GetVerticalAlignment(); - switch( verticalAlignment ) +ImfManager::ImfCallbackData Controller::OnImfEvent( ImfManager& imfManager, const ImfManager::ImfEventData& imfEvent ) +{ + bool update = false; + bool requestRelayout = false; + + std::string text; + unsigned int cursorPosition( 0 ); + + switch ( imfEvent.eventName ) { - case LayoutEngine::VERTICAL_ALIGN_TOP: + case ImfManager::COMMIT: { - mImpl->mAlignmentOffset.y = 0.f; + InsertText( imfEvent.predictiveString, Text::Controller::COMMIT ); + update=true; + requestRelayout = true; break; } - case LayoutEngine::VERTICAL_ALIGN_CENTER: + case ImfManager::PREEDIT: { - const int intOffset = static_cast( 0.5f * ( size.height - actualSize.height ) ); // try to avoid pixel alignment. - mImpl->mAlignmentOffset.y = static_cast( intOffset ); + InsertText( imfEvent.predictiveString, Text::Controller::PRE_EDIT ); + update = true; + requestRelayout = true; break; } - case LayoutEngine::VERTICAL_ALIGN_BOTTOM: + case ImfManager::DELETESURROUNDING: { - mImpl->mAlignmentOffset.y = size.height - actualSize.height; + update = RemoveText( imfEvent.cursorOffset, imfEvent.numberOfChars ); + + if( update ) + { + if( 0u != mImpl->mLogicalModel->mText.Count() || + !mImpl->IsPlaceholderAvailable() ) + { + mImpl->QueueModifyEvent( ModifyEvent::TEXT_DELETED ); + } + else + { + ShowPlaceholderText(); + mImpl->mEventData->mUpdateCursorPosition = true; + } + } + requestRelayout = true; break; } + case ImfManager::GETSURROUNDING: + { + GetText( text ); + cursorPosition = GetLogicalCursorPosition(); + + imfManager.SetSurroundingText( text ); + imfManager.SetCursorPosition( cursorPosition ); + break; + } + case ImfManager::VOID: + { + // do nothing + break; + } + } // end switch + + if( ImfManager::GETSURROUNDING != imfEvent.eventName ) + { + GetText( text ); + cursorPosition = GetLogicalCursorPosition(); } -} -View& Controller::GetView() -{ - return mImpl->mView; -} + if( requestRelayout ) + { + mImpl->mOperationsPending = ALL_OPERATIONS; + mImpl->RequestRelayout(); -LayoutEngine& Controller::GetLayoutEngine() -{ - return mImpl->mLayoutEngine; + // Do this last since it provides callbacks into application code + mImpl->mControlInterface.TextChanged(); + } + + ImfManager::ImfCallbackData callbackData( update, cursorPosition, text, false ); + + return callbackData; } -void Controller::RequestRelayout() +Controller::~Controller() { - mImpl->mControlInterface.RequestTextRelayout(); + delete mImpl; } -void Controller::KeyboardFocusGainEvent() +bool Controller::BackspaceKeyEvent() { - DALI_ASSERT_DEBUG( mImpl->mTextInput && "Unexpected KeyboardFocusGainEvent" ); + DALI_LOG_INFO( gLogFilter, Debug::Verbose, "Controller::KeyEvent %p DALI_KEY_BACKSPACE\n", this ); - if( mImpl->mTextInput ) + // IMF manager is no longer handling key-events + mImpl->ClearPreEditFlag(); + + bool removed( false ); + + if( EventData::SELECTING == mImpl->mEventData->mState ) + { + removed = RemoveSelectedText(); + } + else if( mImpl->mEventData->mPrimaryCursorPosition > 0 ) { - TextInput::Event event( TextInput::KEYBOARD_FOCUS_GAIN_EVENT ); - mImpl->mTextInput->mEventQueue.push_back( event ); + // Remove the character before the current cursor position + removed = RemoveText( -1, 1 ); + } + + if( removed ) + { + DALI_LOG_INFO( gLogFilter, Debug::Verbose, "Controller::KeyEvent %p DALI_KEY_BACKSPACE RemovedText\n", this ); + // Notifiy the IMF manager after text changed + // Automatic Upper-case and restarting prediction on an existing word require this. + NotifyImfManager(); - RequestRelayout(); + if( 0u != mImpl->mLogicalModel->mText.Count() || + !mImpl->IsPlaceholderAvailable() ) + { + mImpl->QueueModifyEvent( ModifyEvent::TEXT_DELETED ); + } + else + { + ShowPlaceholderText(); + mImpl->mEventData->mUpdateCursorPosition = true; + } } + + return removed; } -void Controller::KeyboardFocusLostEvent() +void Controller::NotifyImfManager() { - DALI_ASSERT_DEBUG( mImpl->mTextInput && "Unexpected KeyboardFocusLostEvent" ); - - if( mImpl->mTextInput ) + if( mImpl->mEventData ) { - TextInput::Event event( TextInput::KEYBOARD_FOCUS_LOST_EVENT ); - mImpl->mTextInput->mEventQueue.push_back( event ); + if( mImpl->mEventData->mImfManager ) + { + // Notifying IMF of a cursor change triggers a surrounding text request so updating it now. + std::string text; + GetText( text ); + mImpl->mEventData->mImfManager.SetSurroundingText( text ); - RequestRelayout(); + mImpl->mEventData->mImfManager.SetCursorPosition( GetLogicalCursorPosition() ); + mImpl->mEventData->mImfManager.NotifyCursorPosition(); + } } } -bool Controller::KeyEvent( const Dali::KeyEvent& keyEvent ) +void Controller::ShowPlaceholderText() { - DALI_ASSERT_DEBUG( mImpl->mTextInput && "Unexpected KeyEvent" ); - - if( mImpl->mTextInput && - keyEvent.state == KeyEvent::Down ) + if( mImpl->IsPlaceholderAvailable() ) { - int keyCode = keyEvent.keyCode; - const std::string& keyString = keyEvent.keyPressed; + DALI_ASSERT_DEBUG( mImpl->mEventData && "No placeholder text available" ); - // Pre-process to separate modifying events from non-modifying input events. - if( Dali::DALI_KEY_ESCAPE == keyCode ) - { - // Escape key is a special case which causes focus loss - KeyboardFocusLostEvent(); - } - else if( Dali::DALI_KEY_CURSOR_LEFT == keyCode || - Dali::DALI_KEY_CURSOR_RIGHT == keyCode || - Dali::DALI_KEY_CURSOR_UP == keyCode || - Dali::DALI_KEY_CURSOR_DOWN == keyCode ) - { - TextInput::Event event( TextInput::CURSOR_KEY_EVENT ); - event.p1.mInt = keyCode; - mImpl->mTextInput->mEventQueue.push_back( event ); - } - else if( Dali::DALI_KEY_BACKSPACE == keyCode ) + mImpl->mEventData->mIsShowingPlaceholderText = true; + + // Disable handles when showing place-holder text + mImpl->mEventData->mDecorator->SetHandleActive( GRAB_HANDLE, false ); + mImpl->mEventData->mDecorator->SetHandleActive( LEFT_SELECTION_HANDLE, false ); + mImpl->mEventData->mDecorator->SetHandleActive( RIGHT_SELECTION_HANDLE, false ); + + const char* text( NULL ); + size_t size( 0 ); + + // TODO - Switch placeholder text styles when changing state + if( EventData::INACTIVE != mImpl->mEventData->mState && + 0u != mImpl->mEventData->mPlaceholderTextActive.c_str() ) { - // Queue a delete event - ModifyEvent event; - event.type = DELETE_TEXT; - mImpl->mModifyEvents.push_back( event ); + text = mImpl->mEventData->mPlaceholderTextActive.c_str(); + size = mImpl->mEventData->mPlaceholderTextActive.size(); } - else if( !keyString.empty() ) + else { - // Queue an insert event - ModifyEvent event; - event.type = INSERT_TEXT; - event.text = keyString; - mImpl->mModifyEvents.push_back( event ); + text = mImpl->mEventData->mPlaceholderTextInactive.c_str(); + size = mImpl->mEventData->mPlaceholderTextInactive.size(); } - mImpl->mTextInput->ChangeState( TextInput::EDITING ); // todo Confirm this is the best place to change the state of + // Reset model for showing placeholder. + mImpl->mLogicalModel->mText.Clear(); + ClearModelData(); + mImpl->mVisualModel->SetTextColor( mImpl->mEventData->mPlaceholderTextColor ); - RequestRelayout(); - } - - return false; -} + // Convert text into UTF-32 + Vector& utf32Characters = mImpl->mLogicalModel->mText; + utf32Characters.Resize( size ); -void Controller::TapEvent( unsigned int tapCount, float x, float y ) -{ - DALI_ASSERT_DEBUG( mImpl->mTextInput && "Unexpected TapEvent" ); + // This is a bit horrible but std::string returns a (signed) char* + const uint8_t* utf8 = reinterpret_cast( text ); - if( mImpl->mTextInput ) - { - TextInput::Event event( TextInput::TAP_EVENT ); - event.p1.mUint = tapCount; - event.p2.mFloat = x; - event.p3.mFloat = y; - mImpl->mTextInput->mEventQueue.push_back( event ); + // Transform a text array encoded in utf8 into an array encoded in utf32. + // It returns the actual number of characters. + Length characterCount = Utf8ToUtf32( utf8, size, utf32Characters.Begin() ); + utf32Characters.Resize( characterCount ); - RequestRelayout(); - } -} + // Reset the cursor position + mImpl->mEventData->mPrimaryCursorPosition = 0; -void Controller::PanEvent( Gesture::State state, const Vector2& displacement ) -{ - DALI_ASSERT_DEBUG( mImpl->mTextInput && "Unexpected PanEvent" ); + // The natural size needs to be re-calculated. + mImpl->mRecalculateNaturalSize = true; - if( mImpl->mTextInput ) - { - TextInput::Event event( TextInput::PAN_EVENT ); - event.p1.mInt = state; - event.p2.mFloat = displacement.x; - event.p3.mFloat = displacement.y; - mImpl->mTextInput->mEventQueue.push_back( event ); + // Apply modifications to the model + mImpl->mOperationsPending = ALL_OPERATIONS; - RequestRelayout(); + // Update the rest of the model during size negotiation + mImpl->QueueModifyEvent( ModifyEvent::TEXT_REPLACED ); } } -void Controller::GrabHandleEvent( GrabHandleState state, float x, float y ) +void Controller::ClearModelData() { - DALI_ASSERT_DEBUG( mImpl->mTextInput && "Unexpected GrabHandleEvent" ); - - if( mImpl->mTextInput ) - { - TextInput::Event event( TextInput::GRAB_HANDLE_EVENT ); - event.p1.mUint = state; - event.p2.mFloat = x; - event.p3.mFloat = y; - mImpl->mTextInput->mEventQueue.push_back( event ); - - RequestRelayout(); - } + // n.b. This does not Clear the mText from mLogicalModel + mImpl->mLogicalModel->mScriptRuns.Clear(); + mImpl->mLogicalModel->mFontRuns.Clear(); + mImpl->mLogicalModel->mLineBreakInfo.Clear(); + mImpl->mLogicalModel->mWordBreakInfo.Clear(); + mImpl->mLogicalModel->mBidirectionalParagraphInfo.Clear(); + mImpl->mLogicalModel->mCharacterDirections.Clear(); + mImpl->mLogicalModel->mBidirectionalLineInfo.Clear(); + mImpl->mLogicalModel->mLogicalToVisualMap.Clear(); + mImpl->mLogicalModel->mVisualToLogicalMap.Clear(); + mImpl->mVisualModel->mGlyphs.Clear(); + mImpl->mVisualModel->mGlyphsToCharacters.Clear(); + mImpl->mVisualModel->mCharactersToGlyph.Clear(); + mImpl->mVisualModel->mCharactersPerGlyph.Clear(); + mImpl->mVisualModel->mGlyphsPerCharacter.Clear(); + mImpl->mVisualModel->mGlyphPositions.Clear(); + mImpl->mVisualModel->mLines.Clear(); + mImpl->mVisualModel->ClearCaches(); } -Controller::~Controller() +void Controller::ClearFontData() { - delete mImpl; + mImpl->mFontDefaults->mFontId = 0u; // Remove old font ID + mImpl->mLogicalModel->mFontRuns.Clear(); + mImpl->mVisualModel->mGlyphs.Clear(); + mImpl->mVisualModel->mGlyphsToCharacters.Clear(); + mImpl->mVisualModel->mCharactersToGlyph.Clear(); + mImpl->mVisualModel->mCharactersPerGlyph.Clear(); + mImpl->mVisualModel->mGlyphsPerCharacter.Clear(); + mImpl->mVisualModel->mGlyphPositions.Clear(); + mImpl->mVisualModel->mLines.Clear(); + mImpl->mVisualModel->ClearCaches(); } Controller::Controller( ControlInterface& controlInterface )