Move FontDefaults Declaration/Definition as it's needed by the TextInput.
[platform/core/uifw/dali-toolkit.git] / dali-toolkit / internal / text / text-controller.cpp
index 995354c..591dbaf 100644 (file)
 // CLASS HEADER
 #include <dali-toolkit/internal/text/text-controller.h>
 
+// EXTERNAL INCLUDES
+#include <limits>
+#include <vector>
+#include <dali/public-api/adaptor-framework/key.h>
+#include <dali/public-api/text-abstraction/font-client.h>
+
 // INTERNAL INCLUDES
+#include <dali-toolkit/internal/text/bidirectional-support.h>
 #include <dali-toolkit/internal/text/character-set-conversion.h>
 #include <dali-toolkit/internal/text/layouts/layout-engine.h>
 #include <dali-toolkit/internal/text/layouts/layout-parameters.h>
-#include <dali-toolkit/internal/text/logical-model.h>
+#include <dali-toolkit/internal/text/logical-model-impl.h>
 #include <dali-toolkit/internal/text/multi-language-support.h>
 #include <dali-toolkit/internal/text/script-run.h>
 #include <dali-toolkit/internal/text/segmentation.h>
 #include <dali-toolkit/internal/text/shaper.h>
+#include <dali-toolkit/internal/text/text-io.h>
 #include <dali-toolkit/internal/text/text-view.h>
-#include <dali-toolkit/internal/text/visual-model.h>
-
-// EXTERNAL INCLUDES
-#include <limits>
-#include <vector>
-#include <dali/public-api/text-abstraction/font-client.h>
+#include <dali-toolkit/internal/text/visual-model-impl.h>
 
 using std::vector;
 
+namespace
+{
+
+const float MAX_FLOAT = std::numeric_limits<float>::max();
+const std::string EMPTY_STRING;
+
+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
+};
+
+struct ModifyEvent
+{
+  ModifyType type;
+  std::string text;
+};
+
+} // namespace
+
 namespace Dali
 {
 
@@ -46,6 +70,31 @@ namespace Toolkit
 namespace Text
 {
 
+struct Controller::FontDefaults
+{
+  FontDefaults()
+  : mDefaultPointSize(0.0f),
+    mFontId(0u)
+  {
+  }
+
+  FontId GetFontId( TextAbstraction::FontClient& fontClient )
+  {
+    if( !mFontId )
+    {
+      Dali::TextAbstraction::PointSize26Dot6 pointSize = mDefaultPointSize*64;
+      mFontId = fontClient.GetFontId( mDefaultFontFamily, mDefaultFontStyle, pointSize );
+    }
+
+    return mFontId;
+  }
+
+  std::string mDefaultFontFamily;
+  std::string mDefaultFontStyle;
+  float mDefaultPointSize;
+  FontId mFontId;
+};
+
 struct Controller::TextInput
 {
   // Used to queue input events until DoRelayout()
@@ -53,7 +102,9 @@ struct Controller::TextInput
   {
     KEYBOARD_FOCUS_GAIN_EVENT,
     KEYBOARD_FOCUS_LOST_EVENT,
+    CURSOR_KEY_EVENT,
     TAP_EVENT,
+    PAN_EVENT,
     GRAB_HANDLE_EVENT
   };
 
@@ -83,7 +134,8 @@ struct Controller::TextInput
   {
     INACTIVE,
     SELECTING,
-    EDITING
+    EDITING,
+    EDITING_WITH_POPUP
   };
 
   TextInput( LogicalModelPtr logicalModel,
@@ -92,14 +144,25 @@ struct Controller::TextInput
   : mLogicalModel( logicalModel ),
     mVisualModel( visualModel ),
     mDecorator( decorator ),
-    mState( INACTIVE )
+    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 ProcessTouchEvents()
+  bool ProcessInputEvents( const Vector2& controlSize,
+                           const Vector2& alignmentOffset )
   {
     mDecoratorUpdated = false;
 
@@ -119,9 +182,19 @@ struct Controller::TextInput
             OnKeyboardFocus( false );
             break;
           }
+          case CURSOR_KEY_EVENT:
+          {
+            OnCursorKeyEvent( *iter );
+            break;
+          }
           case TAP_EVENT:
           {
-            OnTapEvent( *iter );
+            OnTapEvent( *iter, alignmentOffset );
+            break;
+          }
+          case PAN_EVENT:
+          {
+            OnPanEvent( *iter, controlSize, alignmentOffset );
             break;
           }
           case GRAB_HANDLE_EVENT:
@@ -133,6 +206,13 @@ struct Controller::TextInput
       }
     }
 
+    // The cursor must also be repositioned after inserts into the model
+    if( mUpdateCursorPosition )
+    {
+      UpdateCursorPosition();
+      mUpdateCursorPosition = false;
+    }
+
     mEventQueue.clear();
 
     return mDecoratorUpdated;
@@ -140,32 +220,121 @@ struct Controller::TextInput
 
   void OnKeyboardFocus( bool hasFocus )
   {
+    if( !hasFocus )
+    {
+      ChangeState( INACTIVE );
+    }
+    else
+    {
+      ChangeState( EDITING );
+    }
+  }
+
+  void OnCursorKeyEvent( const Event& event )
+  {
+    int keyCode = event.p1.mInt;
+
+    if( Dali::DALI_KEY_CURSOR_LEFT == keyCode )
+    {
+      // TODO
+    }
+    else if( Dali::DALI_KEY_CURSOR_RIGHT == keyCode )
+    {
+      // TODO
+    }
+    else if( Dali::DALI_KEY_CURSOR_UP == keyCode )
+    {
+      // TODO
+    }
+    else if(   Dali::DALI_KEY_CURSOR_DOWN == keyCode )
+    {
+      // TODO
+    }
+  }
+
+  void HandleCursorKey( int keyCode )
+  {
     // TODO
   }
 
-  void OnTapEvent( const Event& event )
+  void OnTapEvent( const Event& event,
+                   const Vector2& alignmentOffset  )
   {
-    if( 1u == event.p1.mUint )
+    unsigned int tapCount = event.p1.mUint;
+
+    if( 1u == tapCount )
     {
-      mState = TextInput::EDITING;
-      mDecorator->SetActiveCursor( ACTIVE_CURSOR_PRIMARY );
-      mDecorator->StartCursorBlink();
-      mDecorator->SetGrabHandleActive( true );
+      ChangeState( EDITING );
 
-      float xPosition = event.p2.mFloat;
-      float yPosition = event.p3.mFloat;
+      float xPosition = event.p2.mFloat - alignmentOffset.x;
+      float yPosition = event.p3.mFloat - alignmentOffset.y;
       float height(0.0f);
-      GetClosestCursorPosition( xPosition, yPosition, height );
-      mDecorator->SetPosition( PRIMARY_CURSOR, xPosition, yPosition, height );
+      GetClosestCursorPosition( mPrimaryCursorPosition, xPosition, yPosition, height );
+      mDecorator->SetPosition( PRIMARY_CURSOR, xPosition, yPosition, height, height ); // TODO: To be fixed in the next patch.
+      mUpdateCursorPosition = false;
 
       mDecoratorUpdated = true;
     }
-    else if( 2u == event.p1.mUint )
+    else if( mSelectionEnabled &&
+             2u == tapCount )
     {
-      mState = TextInput::SELECTING;
-      mDecorator->SetGrabHandleActive( false );
-      mDecorator->SetSelectionActive( true );
-      mDecoratorUpdated = true;
+      ChangeState( SELECTING );
+
+      RepositionSelectionHandles( event.p2.mFloat, event.p3.mFloat );
+    }
+  }
+
+  void OnPanEvent( const Event& event,
+                   const Vector2& controlSize,
+                   const Vector2& alignmentOffset )
+  {
+    int state = event.p1.mInt;
+
+    if( Gesture::Started    == state ||
+        Gesture::Continuing == state )
+    {
+      const Vector2& actualSize = mVisualModel->GetActualSize();
+
+      if( mHorizontalScrollingEnabled )
+      {
+        const float displacementX = event.p2.mFloat;
+        mScrollPosition.x += displacementX;
+
+        // 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;
+
+          mDecoratorUpdated = true;
+        }
+        else
+        {
+          mScrollPosition.x = 0.f;
+        }
+      }
+
+      if( mVerticalScrollingEnabled )
+      {
+        const float displacementY = event.p3.mFloat;
+        mScrollPosition.y += displacementY;
+
+        // 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;
+
+          mDecoratorUpdated = true;
+        }
+        else
+        {
+          mScrollPosition.y = 0.f;
+        }
+      }
     }
   }
 
@@ -179,62 +348,260 @@ struct Controller::TextInput
       float yPosition = event.p3.mFloat;
       float height(0.0f);
 
-      GetClosestCursorPosition( xPosition, yPosition, height );
+      GetClosestCursorPosition( mPrimaryCursorPosition, xPosition, yPosition, height );
+
+      mDecorator->SetPosition( PRIMARY_CURSOR, xPosition, yPosition, height, height ); // TODO: To be fixed in the next patch.
 
-      mDecorator->SetPosition( PRIMARY_CURSOR, xPosition, yPosition, height );
+      //mDecorator->HidePopup();
+      ChangeState ( EDITING );
+      mDecoratorUpdated = true;
+    }
+    else if ( mGrabHandlePopupEnabled &&
+              GRAB_HANDLE_RELEASED == state )
+    {
+      //mDecorator->ShowPopup();
+      ChangeState ( EDITING_WITH_POPUP );
       mDecoratorUpdated = true;
     }
   }
 
-  void GetClosestCursorPosition( float& x, float& y, float& height )
+  void RepositionSelectionHandles( float visualX, float visualY )
+  {
+    // TODO - Find which word was selected
+
+    const Vector<GlyphInfo>& glyphs = mVisualModel->mGlyphs;
+    const Vector<Vector2>::SizeType glyphCount = glyphs.Count();
+
+    const Vector<Vector2>& positions = mVisualModel->mGlyphPositions;
+    const Vector<Vector2>::SizeType positionCount = positions.Count();
+
+    // Guard against glyphs which did not fit inside the layout
+    const Vector<Vector2>::SizeType count = (positionCount < glyphCount) ? positionCount : glyphCount;
+
+    if( count )
+    {
+      float primaryX   = positions[0].x;
+      float secondaryX = positions[count-1].x + glyphs[count-1].width;
+
+      // TODO - multi-line selection
+      const Vector<LineRun>& lines = mVisualModel->mLines;
+      float height = lines.Count() ? lines[0].ascender + -lines[0].descender : 0.0f;
+
+      mDecorator->SetPosition( PRIMARY_SELECTION_HANDLE,   primaryX,   0.0f, height );
+      mDecorator->SetPosition( SECONDARY_SELECTION_HANDLE, secondaryX, 0.0f, height );
+
+      mDecorator->ClearHighlights();
+      mDecorator->AddHighlight( primaryX, 0.0f, secondaryX, height );
+    }
+  }
+
+  void ChangeState( State newState )
+  {
+    if( mState != newState )
+    {
+      mState = newState;
+
+      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;
+      }
+    }
+  }
+
+  LineIndex GetClosestLine( float y )
   {
-    // TODO - Look at LineRuns first
+    LineIndex lineIndex( 0u );
+
+    const Vector<LineRun>& lines = mVisualModel->mLines;
+    for( float totalHeight = 0; lineIndex < lines.Count(); ++lineIndex )
+    {
+      const LineRun& lineRun = lines[lineIndex];
+      totalHeight += lineRun.ascender + -lineRun.descender;
+      if( y < totalHeight )
+      {
+        return lineIndex;
+      }
+    }
 
-    Text::Length numberOfGlyphs = mVisualModel->GetNumberOfGlyphs();
-    if( 0 == numberOfGlyphs )
+    return lineIndex-1;
+  }
+
+  void GetClosestCursorPosition( CharacterIndex& logical, float& visualX, float& visualY, float& height )
+  {
+    Length numberOfGlyphs = mVisualModel->mGlyphs.Count();
+    Length numberOfLines  = mVisualModel->mLines.Count();
+    if( 0 == numberOfGlyphs ||
+        0 == numberOfLines )
     {
       return;
     }
 
-    Vector<GlyphInfo> glyphs;
-    glyphs.Resize( numberOfGlyphs );
-    mVisualModel->GetGlyphs( &glyphs[0], 0, numberOfGlyphs );
+    // Transform to visual model coords
+    visualX -= mScrollPosition.x;
+    visualY -= mScrollPosition.y;
+
+    // Find which line is closest
+    LineIndex lineIndex( GetClosestLine( visualY ) );
 
-    std::vector<Vector2> positions;
-    positions.resize( numberOfGlyphs );
-    mVisualModel->GetGlyphPositions( &positions[0], 0, numberOfGlyphs );
+    const Vector<GlyphInfo>& glyphs = mVisualModel->mGlyphs;
+    const GlyphInfo* const glyphsBuffer = glyphs.Begin();
+
+    const Vector<Vector2>& positions = mVisualModel->mGlyphPositions;
+    const Vector2* const positionsBuffer = positions.Begin();
 
     unsigned int closestGlyph = 0;
-    float closestDistance = std::numeric_limits<float>::max();
+    bool leftOfGlyph( false ); // which side of the glyph?
+    float closestDistance = MAX_FLOAT;
+
+    const LineRun& line = mVisualModel->mLines[lineIndex];
+    GlyphIndex startGlyph = line.glyphIndex;
+    GlyphIndex endGlyph   = line.glyphIndex + line.numberOfGlyphs;
+    DALI_ASSERT_DEBUG( endGlyph <= glyphs.Count() && "Invalid line info" );
 
-    for( unsigned int i=0; i<glyphs.Count(); ++i )
+    for( GlyphIndex i = startGlyph; i < endGlyph; ++i )
     {
-      float glyphX = positions[i].x + glyphs[i].width*0.5f;
-      float glyphY = positions[i].y + glyphs[i].height*0.5f;
+      const GlyphInfo& glyphInfo = *( glyphsBuffer + i );
+      const Vector2& position = *( positionsBuffer + i );
+      float glyphX = position.x + glyphInfo.width*0.5f;
+      float glyphY = position.y + glyphInfo.height*0.5f;
 
-      float distanceToGlyph = fabsf( glyphX - x ) + fabsf( glyphY - y );
+      float distanceToGlyph = fabsf( glyphX - visualX ) + fabsf( glyphY - visualY );
 
       if( distanceToGlyph < closestDistance )
       {
         closestDistance = distanceToGlyph;
         closestGlyph = i;
+        leftOfGlyph = ( visualX < glyphX );
+      }
+    }
+
+    // Calculate the logical position
+    logical = mVisualModel->GetCharacterIndex( closestGlyph );
+
+    // Returns the visual position of the glyph
+    visualX = positions[closestGlyph].x;
+    if( !leftOfGlyph )
+    {
+      visualX += glyphs[closestGlyph].width;
+
+      //if( LTR ) TODO
+        ++logical;
+    }
+    else// if ( RTL ) TODO
+    {
+      //++logical;
+    }
+    visualY = 0.0f;
+
+    height = line.ascender + -line.descender;
+  }
+
+  void UpdateCursorPosition()
+  {
+    if( 0 == mVisualModel->mGlyphs.Count() )
+    {
+      return;
+    }
+
+    // FIXME GetGlyphIndex() is behaving strangely
+#if 0
+    GlyphIndex cursorGlyph = mVisualModel->GetGlyphIndex( mPrimaryCursorPosition );
+#else
+    GlyphIndex cursorGlyph( 0u );
+    for( cursorGlyph = 0; cursorGlyph < mVisualModel->mGlyphs.Count(); ++cursorGlyph )
+    {
+      if( mPrimaryCursorPosition == mVisualModel->GetCharacterIndex( cursorGlyph ) )
+      {
+        break;
       }
     }
+#endif
+
+    float visualX( 0.0f );
+    float visualY( 0.0f );
+    float height( 0.0f );
+    const Vector<LineRun>& lineRuns = mVisualModel->mLines;
+
+    if( cursorGlyph > 0 )
+    {
+      --cursorGlyph;
+
+      visualX = mVisualModel->mGlyphPositions[ cursorGlyph ].x;
+      //if( LTR ) TODO
+        visualX += mVisualModel->mGlyphs[ cursorGlyph ].width;
 
-    // TODO - Consider RTL languages
-    x = positions[closestGlyph].x + glyphs[closestGlyph].width;
-    y = 0.0f;
+      // Find the line height
+      GlyphIndex lastGlyph( 0 );
+      for( LineIndex lineIndex = 0u; lineIndex < lineRuns.Count(); ++lineIndex )
+      {
+        lastGlyph = (lineRuns[lineIndex].glyphIndex + lineRuns[lineIndex].numberOfGlyphs);
+        if( cursorGlyph < lastGlyph )
+        {
+          const LineRun& lineRun = lineRuns[lineIndex];
+          height = lineRun.ascender + -lineRun.descender;
+          break;
+        }
+      }
+    }
 
-    FontMetrics metrics;
-    TextAbstraction::FontClient::Get().GetFontMetrics( glyphs[closestGlyph].fontId, metrics );
-    height = metrics.height; // TODO - Fix for multi-line
+    mDecorator->SetPosition( PRIMARY_CURSOR, visualX, visualY, height, height ); // TODO: To be fixed in the next patch.
+    mDecoratorUpdated = true;
   }
 
   LogicalModelPtr mLogicalModel;
   VisualModelPtr  mVisualModel;
   DecoratorPtr    mDecorator;
 
-  State mState;
+  std::string mPlaceholderText;
 
   /**
    * This is used to delay handling events until after the model has been updated.
@@ -242,24 +609,56 @@ struct Controller::TextInput
    */
   vector<Event> mEventQueue; ///< The queue of touch events etc.
 
-  bool mDecoratorUpdated;
+  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 ),
-    mNewText(),
-    mOperations( NO_OPERATION ),
+    mLogicalModel(),
+    mVisualModel(),
+    mFontDefaults( NULL ),
+    mTextInput( NULL ),
+    mFontClient(),
+    mView(),
+    mLayoutEngine(),
+    mModifyEvents(),
     mControlSize(),
-    mTextInput( NULL )
+    mAlignmentOffset(),
+    mOperationsPending( NO_OPERATION ),
+    mRecalculateNaturalSize( true )
   {
     mLogicalModel = LogicalModel::New();
     mVisualModel  = VisualModel::New();
 
+    mFontClient = TextAbstraction::FontClient::Get();
+
     mView.SetVisualModel( mVisualModel );
 
-    mFontClient = TextAbstraction::FontClient::Get();
+    // Set the text properties to default
+    mVisualModel->SetTextColor( Color::WHITE );
+    mVisualModel->SetShadowOffset( Vector2::ZERO );
+    mVisualModel->SetShadowColor( Vector4::ZERO );
+    mVisualModel->SetUnderlineEnabled( false );
   }
 
   ~Impl()
@@ -267,25 +666,19 @@ struct Controller::Impl
     delete mTextInput;
   }
 
-  ControlInterface& mControlInterface;
-
-  std::string mNewText;
-
-  LogicalModelPtr mLogicalModel;
-  VisualModelPtr  mVisualModel;
-
-  View mView;
-
-  LayoutEngine mLayoutEngine;
-
-  TextAbstraction::FontClient mFontClient;
-
-  OperationsMask mOperations;
-
-  Size mControlSize;
-
-  // Avoid allocating everything for text input until EnableTextInput()
-  Controller::TextInput* 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<ModifyEvent> 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 )
@@ -295,9 +688,14 @@ ControllerPtr Controller::New( ControlInterface& controlInterface )
 
 void Controller::SetText( const std::string& text )
 {
+  // Cancel previously queued inserts etc.
+  mImpl->mModifyEvents.clear();
+
   // Keep until size negotiation
-  mImpl->mNewText = text;
-  mImpl->mOperations = ALL_OPERATIONS;
+  ModifyEvent event;
+  event.type = REPLACE_TEXT;
+  event.text = text;
+  mImpl->mModifyEvents.push_back( event );
 
   if( mImpl->mTextInput )
   {
@@ -308,11 +706,12 @@ void Controller::SetText( const std::string& text )
   }
 }
 
-void Controller::GetText( std::string& text )
+void Controller::GetText( std::string& text ) const
 {
-  if( !mImpl->mNewText.empty() )
+  if( !mImpl->mModifyEvents.empty() &&
+       REPLACE_TEXT == mImpl->mModifyEvents[0].type )
   {
-    text = mImpl->mNewText;
+    text = mImpl->mModifyEvents[0].text;
   }
   else
   {
@@ -320,6 +719,191 @@ void Controller::GetText( std::string& text )
   }
 }
 
+void Controller::SetPlaceholderText( const std::string& text )
+{
+  if( !mImpl->mTextInput )
+  {
+    mImpl->mTextInput->mPlaceholderText = text;
+  }
+}
+
+void Controller::GetPlaceholderText( std::string& text ) const
+{
+  if( !mImpl->mTextInput )
+  {
+    text = mImpl->mTextInput->mPlaceholderText;
+  }
+}
+
+void Controller::SetDefaultFontFamily( const std::string& defaultFontFamily )
+{
+  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();
+
+  RequestRelayout();
+}
+
+const std::string& Controller::GetDefaultFontFamily() const
+{
+  if( mImpl->mFontDefaults )
+  {
+    return mImpl->mFontDefaults->mDefaultFontFamily;
+  }
+
+  return EMPTY_STRING;
+}
+
+void Controller::SetDefaultFontStyle( const std::string& defaultFontStyle )
+{
+  if( !mImpl->mFontDefaults )
+  {
+    mImpl->mFontDefaults = new Controller::FontDefaults();
+  }
+
+  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();
+
+  RequestRelayout();
+}
+
+const std::string& Controller::GetDefaultFontStyle() const
+{
+  if( mImpl->mFontDefaults )
+  {
+    return mImpl->mFontDefaults->mDefaultFontStyle;
+  }
+
+  return EMPTY_STRING;
+}
+
+void Controller::SetDefaultPointSize( float pointSize )
+{
+  if( !mImpl->mFontDefaults )
+  {
+    mImpl->mFontDefaults = new Controller::FontDefaults();
+  }
+
+  mImpl->mFontDefaults->mDefaultPointSize = pointSize;
+  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();
+
+  RequestRelayout();
+}
+
+float Controller::GetDefaultPointSize() const
+{
+  if( mImpl->mFontDefaults )
+  {
+    return mImpl->mFontDefaults->mDefaultPointSize;
+  }
+
+  return 0.0f;
+}
+
+void Controller::GetDefaultFonts( Vector<FontRun>& fonts, Length numberOfCharacters )
+{
+  if( mImpl->mFontDefaults )
+  {
+    FontRun fontRun;
+    fontRun.characterRun.characterIndex = 0;
+    fontRun.characterRun.numberOfCharacters = numberOfCharacters;
+    fontRun.fontId = mImpl->mFontDefaults->GetFontId( mImpl->mFontClient );
+    fontRun.isDefault = true;
+
+    fonts.PushBack( fontRun );
+  }
+}
+
+const Vector4& Controller::GetTextColor() const
+{
+  return mImpl->mVisualModel->GetTextColor();
+}
+
+const Vector2& Controller::GetShadowOffset() const
+{
+  return mImpl->mVisualModel->GetShadowOffset();
+}
+
+const Vector4& Controller::GetShadowColor() const
+{
+  return mImpl->mVisualModel->GetShadowColor();
+}
+
+const Vector4& Controller::GetUnderlineColor() const
+{
+  return mImpl->mVisualModel->GetUnderlineColor();
+}
+
+bool Controller::IsUnderlineEnabled() const
+{
+  return mImpl->mVisualModel->IsUnderlineEnabled();
+}
+
+void Controller::SetTextColor( const Vector4& textColor )
+{
+  mImpl->mVisualModel->SetTextColor( textColor );
+}
+
+void Controller::SetShadowOffset( const Vector2& shadowOffset )
+{
+  mImpl->mVisualModel->SetShadowOffset( shadowOffset );
+}
+
+void Controller::SetShadowColor( const Vector4& shadowColor )
+{
+  mImpl->mVisualModel->SetShadowColor( shadowColor );
+}
+
+void Controller::SetUnderlineColor( const Vector4& color )
+{
+  mImpl->mVisualModel->SetUnderlineColor( color );
+}
+
+void Controller::SetUnderlineEnabled( bool enabled )
+{
+  mImpl->mVisualModel->SetUnderlineEnabled( enabled );
+}
+
 void Controller::EnableTextInput( DecoratorPtr decorator )
 {
   if( !mImpl->mTextInput )
@@ -328,95 +912,425 @@ void Controller::EnableTextInput( DecoratorPtr decorator )
   }
 }
 
-bool Controller::Relayout( const Vector2& size )
+void Controller::SetEnableCursorBlink( bool enable )
+{
+  DALI_ASSERT_DEBUG( NULL != mImpl->mTextInput && "TextInput disabled" );
+
+  if( mImpl->mTextInput )
+  {
+    mImpl->mTextInput->mCursorBlinkEnabled = enable;
+
+    if( !enable &&
+        mImpl->mTextInput->mDecorator )
+    {
+      mImpl->mTextInput->mDecorator->StopCursorBlink();
+    }
+  }
+}
+
+bool Controller::GetEnableCursorBlink() const
+{
+  if( mImpl->mTextInput )
+  {
+    return mImpl->mTextInput->mCursorBlinkEnabled;
+  }
+
+  return false;
+}
+
+const Vector2& Controller::GetScrollPosition() const
+{
+  if( mImpl->mTextInput )
+  {
+    return mImpl->mTextInput->mScrollPosition;
+  }
+
+  return Vector2::ZERO;
+}
+
+const Vector2& Controller::GetAlignmentOffset() const
+{
+  return mImpl->mAlignmentOffset;
+}
+
+Vector3 Controller::GetNaturalSize()
+{
+  Vector3 naturalSize;
+
+  // Make sure the model is up-to-date before layouting
+  ProcessModifyEvents();
+
+  if( mImpl->mRecalculateNaturalSize )
+  {
+    // Operations that can be done only once until the text changes.
+    const OperationsMask onlyOnceOperations = static_cast<OperationsMask>( 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 );
+
+    // Operations that need to be done if the size changes.
+    const OperationsMask sizeOperations =  static_cast<OperationsMask>( LAYOUT |
+                                                                        ALIGN  |
+                                                                        REORDER );
+
+    DoRelayout( Size( MAX_FLOAT, MAX_FLOAT ),
+                static_cast<OperationsMask>( onlyOnceOperations |
+                                             sizeOperations ),
+                naturalSize.GetVectorXY() );
+
+    // Do not do again the only once operations.
+    mImpl->mOperationsPending = static_cast<OperationsMask>( mImpl->mOperationsPending & ~onlyOnceOperations );
+
+    // Do the size related operations again.
+    mImpl->mOperationsPending = static_cast<OperationsMask>( mImpl->mOperationsPending | sizeOperations );
+
+    // Stores the natural size to avoid recalculate it again
+    // unless the text/style changes.
+    mImpl->mVisualModel->SetNaturalSize( naturalSize.GetVectorXY() );
+
+    mImpl->mRecalculateNaturalSize = false;
+  }
+  else
+  {
+    naturalSize = mImpl->mVisualModel->GetNaturalSize();
+  }
+
+  return naturalSize;
+}
+
+float Controller::GetHeightForWidth( float width )
+{
+  // Make sure the model is up-to-date before layouting
+  ProcessModifyEvents();
+
+  Size layoutSize;
+  if( width != mImpl->mControlSize.width )
+  {
+    // Operations that can be done only once until the text changes.
+    const OperationsMask onlyOnceOperations = static_cast<OperationsMask>( 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 );
+
+    // Operations that need to be done if the size changes.
+    const OperationsMask sizeOperations =  static_cast<OperationsMask>( LAYOUT |
+                                                                        ALIGN  |
+                                                                        REORDER );
+
+    DoRelayout( Size( width, MAX_FLOAT ),
+                static_cast<OperationsMask>( onlyOnceOperations |
+                                             sizeOperations ),
+                layoutSize );
+
+    // Do not do again the only once operations.
+    mImpl->mOperationsPending = static_cast<OperationsMask>( mImpl->mOperationsPending & ~onlyOnceOperations );
+
+    // Do the size related operations again.
+    mImpl->mOperationsPending = static_cast<OperationsMask>( mImpl->mOperationsPending | sizeOperations );
+  }
+  else
+  {
+    layoutSize = mImpl->mVisualModel->GetActualSize();
+  }
+
+  return layoutSize.height;
+}
+
+bool Controller::Relayout( const Size& size )
 {
   if( ( size.width < Math::MACHINE_EPSILON_1000 ) || ( size.height < Math::MACHINE_EPSILON_1000 ) )
   {
+    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 false;
+    return glyphsRemoved;
   }
 
-  bool updated = false;
-
   if( size != mImpl->mControlSize )
   {
-    updated = DoRelayout( size, mImpl->mOperations );
-
-    // Do not re-do any operation until something changes.
-    mImpl->mOperations = NO_OPERATION;
+    // Operations that need to be done if the size changes.
+    mImpl->mOperationsPending = static_cast<OperationsMask>( mImpl->mOperationsPending |
+                                                             LAYOUT                    |
+                                                             ALIGN                     |
+                                                             UPDATE_ACTUAL_SIZE        |
+                                                             REORDER );
 
     mImpl->mControlSize = size;
   }
 
+  // Make sure the model is up-to-date before layouting
+  ProcessModifyEvents();
+  UpdateModel( mImpl->mOperationsPending );
+
+  Size layoutSize;
+  bool updated = DoRelayout( mImpl->mControlSize,
+                             mImpl->mOperationsPending,
+                             layoutSize );
+
+  // Do not re-do any operation until something changes.
+  mImpl->mOperationsPending = NO_OPERATION;
+
+  // After doing the text layout, the alignment offset to place the actor in the desired position can be calculated.
+  CalculateTextAlignment( size );
+
   if( mImpl->mTextInput )
   {
     // Move the cursor, grab handle etc.
-    updated = mImpl->mTextInput->ProcessTouchEvents() || updated;
+    updated = mImpl->mTextInput->ProcessInputEvents( mImpl->mControlSize, mImpl->mAlignmentOffset ) || updated;
   }
 
   return updated;
 }
 
-bool Controller::DoRelayout( const Vector2& size, OperationsMask operations )
+void Controller::ProcessModifyEvents()
 {
-  bool viewUpdated( false );
+  std::vector<ModifyEvent>& events = mImpl->mModifyEvents;
+
+  for( unsigned int i=0; i<events.size(); ++i )
+  {
+    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" );
+
+      ReplaceTextEvent( events[0].text );
+    }
+    else if( INSERT_TEXT == events[0].type )
+    {
+      InsertTextEvent( events[0].text );
+    }
+    else if( DELETE_TEXT == events[0].type )
+    {
+      DeleteTextEvent();
+    }
+  }
+
+  // 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();
+
+  //  Convert text into UTF-32
+  Vector<Character>& 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<const uint8_t*>( 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 )
+  {
+    mImpl->mTextInput->mPrimaryCursorPosition = characterCount;
+    // TODO - handle secondary cursor
+  }
 
+  // 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<OperationsMask>( LAYOUT             |
+                                                           ALIGN              |
+                                                           UPDATE_ACTUAL_SIZE |
+                                                           REORDER );
+}
+
+void Controller::InsertTextEvent( const std::string& text )
+{
+  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();
+
+  //  Convert text into UTF-32
   Vector<Character> utf32Characters;
-  Length characterCount = 0u;
-  if( CONVERT_TO_UTF32 & operations )
+  utf32Characters.Resize( text.size() );
+
+  // This is a bit horrible but std::string returns a (signed) char*
+  const uint8_t* utf8 = reinterpret_cast<const uint8_t*>( 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 );
+
+  // Insert at current cursor position
+  Vector<Character>& modifyText = mImpl->mLogicalModel->mText;
+  CharacterIndex& cursorIndex = mImpl->mTextInput->mPrimaryCursorPosition;
+
+  if( cursorIndex < modifyText.Count() )
   {
-    std::string& text = mImpl->mNewText;
+    modifyText.Insert( modifyText.Begin() + cursorIndex, utf32Characters.Begin(), utf32Characters.End() );
+  }
+  else
+  {
+    modifyText.Insert( modifyText.End(), utf32Characters.Begin(), utf32Characters.End() );
+  }
 
-    //  Convert text into UTF-32
-    utf32Characters.Resize( text.size() );
+  // Advance the cursor position
+  ++cursorIndex;
 
-    // This is a bit horrible but std::string returns a (signed) char*
-    const uint8_t* utf8 = reinterpret_cast<const uint8_t*>( text.c_str() );
+  // The natural size needs to be re-calculated.
+  mImpl->mRecalculateNaturalSize = true;
 
-    // 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 );
+  // Apply modifications to the model; TODO - Optimize this
+  mImpl->mOperationsPending = ALL_OPERATIONS;
+  UpdateModel( ALL_OPERATIONS );
+  mImpl->mOperationsPending = static_cast<OperationsMask>( LAYOUT             |
+                                                           ALIGN              |
+                                                           UPDATE_ACTUAL_SIZE |
+                                                           REORDER );
 
-    // Sets the text into the model.
-    mImpl->mLogicalModel->SetText( utf32Characters.Begin(), characterCount );
+  // Queue a cursor reposition event; this must wait until after DoRelayout()
+  mImpl->mTextInput->mUpdateCursorPosition = true;
+}
+
+void Controller::DeleteTextEvent()
+{
+  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();
+
+  // Delte at current cursor position
+  Vector<Character>& modifyText = mImpl->mLogicalModel->mText;
+  CharacterIndex& cursorIndex = mImpl->mTextInput->mPrimaryCursorPosition;
+
+  if( cursorIndex > 0 &&
+      cursorIndex-1 < modifyText.Count() )
+  {
+    modifyText.Remove( modifyText.Begin() + cursorIndex - 1 );
 
-    // Discard temporary text
-    //text.clear(); temporary keep the text. will be fixed in the next patch.
+    // Cursor position retreat
+    --cursorIndex;
   }
 
-  Vector<LineBreakInfo> lineBreakInfo;
+  // 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<OperationsMask>( LAYOUT             |
+                                                           ALIGN              |
+                                                           UPDATE_ACTUAL_SIZE |
+                                                           REORDER );
+
+  // Queue a cursor reposition event; this must wait until after DoRelayout()
+  mImpl->mTextInput->mUpdateCursorPosition = true;
+}
+
+void Controller::UpdateModel( OperationsMask operationsRequired )
+{
+  // Calculate the operations to be done.
+  const OperationsMask operations = static_cast<OperationsMask>( mImpl->mOperationsPending & operationsRequired );
+
+  Vector<Character>& utf32Characters = mImpl->mLogicalModel->mText;
+
+  const Length numberOfCharacters = mImpl->mLogicalModel->GetNumberOfCharacters();
+
+  Vector<LineBreakInfo>& lineBreakInfo = mImpl->mLogicalModel->mLineBreakInfo;
   if( GET_LINE_BREAKS & operations )
   {
     // 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( characterCount, TextAbstraction::LINE_NO_BREAK );
+    lineBreakInfo.Resize( numberOfCharacters, TextAbstraction::LINE_NO_BREAK );
 
     SetLineBreakInfo( utf32Characters,
                       lineBreakInfo );
-
-    mImpl->mLogicalModel->SetLineBreakInfo( lineBreakInfo.Begin(), characterCount );
   }
 
-  Vector<WordBreakInfo> wordBreakInfo;
+  Vector<WordBreakInfo>& wordBreakInfo = mImpl->mLogicalModel->mWordBreakInfo;
   if( GET_WORD_BREAKS & operations )
   {
     // Retrieves the word break info. The word break info is used to layout the text (where to wrap the text in lines).
-    wordBreakInfo.Resize( characterCount, TextAbstraction::WORD_NO_BREAK );
+    wordBreakInfo.Resize( numberOfCharacters, TextAbstraction::WORD_NO_BREAK );
 
     SetWordBreakInfo( utf32Characters,
                       wordBreakInfo );
-
-    mImpl->mLogicalModel->SetWordBreakInfo( wordBreakInfo.Begin(), characterCount );
   }
 
   const bool getScripts = GET_SCRIPTS & operations;
   const bool validateFonts = VALIDATE_FONTS & operations;
 
-  Vector<ScriptRun> scripts;
-  Vector<FontRun> fonts;
+  Vector<ScriptRun>& scripts = mImpl->mLogicalModel->mScriptRuns;
+  Vector<FontRun>& validFonts = mImpl->mLogicalModel->mFontRuns;
+
   if( getScripts || validateFonts )
   {
     // Validates the fonts assigned by the application or assigns default ones.
@@ -429,90 +1343,128 @@ bool Controller::DoRelayout( const Vector2& size, OperationsMask operations )
       multilanguageSupport.SetScripts( utf32Characters,
                                        lineBreakInfo,
                                        scripts );
-
-      // Sets the scripts into the model.
-      mImpl->mLogicalModel->SetScripts( scripts.Begin(), scripts.Count() );
     }
 
     if( validateFonts )
     {
+      if( 0u == validFonts.Count() )
+      {
+        // 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 );
+      }
+
       // 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,
-                                          fonts );
-
-      // Sets the fonts into the model.
-      mImpl->mLogicalModel->SetFonts( fonts.Begin(), fonts.Count() );
+                                          validFonts );
     }
   }
 
-  Vector<GlyphInfo> glyphs;
-  Vector<CharacterIndex> glyphsToCharactersMap;
-  Vector<Length> charactersPerGlyph;
+  Vector<Character> 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.
+
+    Length numberOfParagraphs = 0u;
+
+    const TextAbstraction::LineBreakInfo* lineBreakInfoBuffer = lineBreakInfo.Begin();
+    for( Length index = 0u; index < numberOfCharacters; ++index )
+    {
+      if( TextAbstraction::LINE_NO_BREAK == *( lineBreakInfoBuffer + index ) )
+      {
+        ++numberOfParagraphs;
+      }
+    }
+
+    Vector<BidirectionalParagraphInfoRun>& 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 );
+
+    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.
+
+      textMirrored = GetMirroredText( utf32Characters, mirroredUtf32Characters );
+
+      // Only set the character directions if there is right to left characters.
+      Vector<CharacterDirection>& directions = mImpl->mLogicalModel->mCharacterDirections;
+      directions.Resize( numberOfCharacters );
+
+      GetCharactersDirection( bidirectionalInfo,
+                              directions );
+    }
+    else
+    {
+      // There is no right to left characters. Clear the directions vector.
+      mImpl->mLogicalModel->mCharacterDirections.Clear();
+    }
+
+   }
+
+  Vector<GlyphInfo>& glyphs = mImpl->mVisualModel->mGlyphs;
+  Vector<CharacterIndex>& glyphsToCharactersMap = mImpl->mVisualModel->mGlyphsToCharacters;
+  Vector<Length>& charactersPerGlyph = mImpl->mVisualModel->mCharactersPerGlyph;
   if( SHAPE_TEXT & operations )
   {
+    const Vector<Character>& textToShape = textMirrored ? mirroredUtf32Characters : utf32Characters;
     // Shapes the text.
-    ShapeText( utf32Characters,
+    ShapeText( textToShape,
                lineBreakInfo,
                scripts,
-               fonts,
+               validFonts,
                glyphs,
                glyphsToCharactersMap,
                charactersPerGlyph );
+
+    // Create the 'number of glyphs' per character and the glyph to character conversion tables.
+    mImpl->mVisualModel->CreateGlyphsPerCharacterTable( numberOfCharacters );
+    mImpl->mVisualModel->CreateCharacterToGlyphTable( numberOfCharacters );
   }
 
+  const Length numberOfGlyphs = glyphs.Count();
+
   if( GET_GLYPH_METRICS & operations )
   {
-    mImpl->mFontClient.GetGlyphMetrics( glyphs.Begin(), glyphs.Count() );
+    mImpl->mFontClient.GetGlyphMetrics( glyphs.Begin(), numberOfGlyphs );
   }
+}
 
-  Length numberOfGlyphs = glyphs.Count();
-  if( 0u != numberOfGlyphs )
-  {
-    // Sets the glyphs into the model.
-    mImpl->mVisualModel->SetGlyphs( glyphs.Begin(),
-                                    glyphsToCharactersMap.Begin(),
-                                    charactersPerGlyph.Begin(),
-                                    numberOfGlyphs );
-  }
+bool Controller::DoRelayout( const Size& size,
+                             OperationsMask operationsRequired,
+                             Size& layoutSize )
+{
+  bool viewUpdated( false );
+
+  // Calculate the operations to be done.
+  const OperationsMask operations = static_cast<OperationsMask>( mImpl->mOperationsPending & operationsRequired );
 
   if( LAYOUT & operations )
   {
-    if( 0u == numberOfGlyphs )
-    {
-      const Length numberOfCharacters = mImpl->mLogicalModel->GetNumberOfCharacters();
-      numberOfGlyphs = mImpl->mVisualModel->GetNumberOfGlyphs();
-
-      lineBreakInfo.Resize( numberOfCharacters );
-      wordBreakInfo.Resize( numberOfCharacters );
-      glyphs.Resize( numberOfGlyphs );
-      glyphsToCharactersMap.Resize( numberOfGlyphs );
-      charactersPerGlyph.Resize( numberOfGlyphs );
-
-      mImpl->mLogicalModel->GetLineBreakInfo( lineBreakInfo.Begin(),
-                                              0u,
-                                              numberOfCharacters );
+    // 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.
 
-      mImpl->mLogicalModel->GetWordBreakInfo( wordBreakInfo.Begin(),
-                                              0u,
-                                              numberOfCharacters );
+    Length numberOfGlyphs = mImpl->mVisualModel->GetNumberOfGlyphs();
 
-      mImpl->mVisualModel->GetGlyphs( glyphs.Begin(),
-                                      0u,
-                                      numberOfGlyphs );
-
-      mImpl->mVisualModel->GetGlyphToCharacterMap( glyphsToCharactersMap.Begin(),
-                                                   0u,
-                                                   numberOfGlyphs );
-
-      mImpl->mVisualModel->GetCharactersPerGlyphMap( charactersPerGlyph.Begin(),
-                                                     0u,
-                                                     numberOfGlyphs );
-    }
+    Vector<LineBreakInfo>& lineBreakInfo = mImpl->mLogicalModel->mLineBreakInfo;
+    Vector<WordBreakInfo>& wordBreakInfo = mImpl->mLogicalModel->mWordBreakInfo;
+    Vector<GlyphInfo>& glyphs = mImpl->mVisualModel->mGlyphs;
+    Vector<CharacterIndex>& glyphsToCharactersMap = mImpl->mVisualModel->mGlyphsToCharacters;
+    Vector<Length>& charactersPerGlyph = mImpl->mVisualModel->mCharactersPerGlyph;
 
     // Set the layout parameters.
     LayoutParameters layoutParameters( size,
+                                       mImpl->mLogicalModel->mText.Begin(),
                                        lineBreakInfo.Begin(),
                                        wordBreakInfo.Begin(),
                                        numberOfGlyphs,
@@ -520,86 +1472,165 @@ bool Controller::DoRelayout( const Vector2& size, OperationsMask operations )
                                        glyphsToCharactersMap.Begin(),
                                        charactersPerGlyph.Begin() );
 
-    // Reserve space to set the positions of the glyphs.
-    Vector<Vector2> glyphPositions;
-    glyphPositions.Resize( numberOfGlyphs );
+    // 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<LineRun>& lines = mImpl->mVisualModel->mLines;
 
-    Size layoutSize;
+    // Delete any previous laid out lines before setting the new ones.
+    lines.Clear();
 
-    // Update the visual model
+    // The capacity of the bidirectional paragraph info is the number of paragraphs.
+    lines.Reserve( mImpl->mLogicalModel->mBidirectionalParagraphInfo.Capacity() );
+
+    // Resize the vector of positions to have the same size than the vector of glyphs.
+    Vector<Vector2>& glyphPositions = mImpl->mVisualModel->mGlyphPositions;
+    glyphPositions.Resize( numberOfGlyphs );
+
+    // Update the visual model.
     viewUpdated = mImpl->mLayoutEngine.LayoutText( layoutParameters,
                                                    glyphPositions,
+                                                   lines,
                                                    layoutSize );
 
-    // Sets the positions into the model.
-    mImpl->mVisualModel->SetGlyphPositions( glyphPositions.Begin(),
-                                            numberOfGlyphs );
-
-    // Sets the actual size.
-    mImpl->mVisualModel->SetActualSize( layoutSize );
-  }
-
-  return viewUpdated;
-}
-
-Vector3 Controller::GetNaturalSize()
-{
-  // TODO - Finish implementing
-  return Vector3::ZERO;
-
-  // Operations that can be done only once until the text changes.
-  const OperationsMask onlyOnceOperations = static_cast<OperationsMask>( CONVERT_TO_UTF32 |
-                                                                         GET_SCRIPTS      |
-                                                                         VALIDATE_FONTS   |
-                                                                         GET_LINE_BREAKS  |
-                                                                         GET_WORD_BREAKS  |
-                                                                         SHAPE_TEXT       |
-                                                                         GET_GLYPH_METRICS );
+    if( viewUpdated )
+    {
+      // Reorder the lines
+      if( REORDER & operations )
+      {
+        Vector<BidirectionalParagraphInfoRun>& bidirectionalInfo = mImpl->mLogicalModel->mBidirectionalParagraphInfo;
 
-  // Operations that need to be done if the size or the text changes.
-  const OperationsMask sizeOperations =  static_cast<OperationsMask>( LAYOUT |
-                                                                      REORDER );
+        // Check first if there are paragraphs with bidirectional info.
+        if( 0u != bidirectionalInfo.Count() )
+        {
+          // Get the lines
+          const Length numberOfLines = mImpl->mVisualModel->GetNumberOfLines();
+
+          // Reorder the lines.
+          Vector<BidirectionalLineInfoRun> lineBidirectionalInfoRuns;
+          lineBidirectionalInfoRuns.Reserve( numberOfLines ); // Reserve because is not known yet how many lines have right to left characters.
+          ReorderLines( bidirectionalInfo,
+                        lines,
+                        lineBidirectionalInfoRuns );
+
+          // Set the bidirectional info into the model.
+          const Length numberOfBidirectionalInfoRuns = lineBidirectionalInfoRuns.Count();
+          mImpl->mLogicalModel->SetVisualToLogicalMap( lineBidirectionalInfoRuns.Begin(),
+                                                       numberOfBidirectionalInfoRuns );
+
+          // Set the bidirectional info per line into the layout parameters.
+          layoutParameters.lineBidirectionalInfoRunsBuffer = lineBidirectionalInfoRuns.Begin();
+          layoutParameters.numberOfBidirectionalInfoRuns = numberOfBidirectionalInfoRuns;
+
+          // 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<BidirectionalLineInfoRun>::Iterator it = lineBidirectionalInfoRuns.Begin(),
+                 endIt = lineBidirectionalInfoRuns.End();
+               it != endIt;
+               ++it )
+          {
+            BidirectionalLineInfoRun& bidiLineInfo = *it;
 
-  const float maxFloat = std::numeric_limits<float>::max();
-  DoRelayout( Vector2( maxFloat, maxFloat ),
-              static_cast<OperationsMask>( onlyOnceOperations |
-                                           sizeOperations ) );
+            free( bidiLineInfo.visualToLogicalMap );
+          }
+        }
+      } // REORDER
 
-  // Do not do again the only once operations.
-  mImpl->mOperations = static_cast<OperationsMask>( mImpl->mOperations & ~onlyOnceOperations );
+      if( ALIGN & operations )
+      {
+        mImpl->mLayoutEngine.Align( layoutParameters,
+                                    layoutSize,
+                                    lines,
+                                    glyphPositions );
+      }
 
-  // Do the size related operations again.
-  mImpl->mOperations = static_cast<OperationsMask>( mImpl->mOperations | sizeOperations );
+      // Sets the actual size.
+      if( UPDATE_ACTUAL_SIZE & operations )
+      {
+        mImpl->mVisualModel->SetActualSize( layoutSize );
+      }
+    } // view updated
+  }
+  else
+  {
+    layoutSize = mImpl->mVisualModel->GetActualSize();
+  }
 
-  return Vector3( mImpl->mVisualModel->GetNaturalSize() );
+  return viewUpdated;
 }
 
-float Controller::GetHeightForWidth( float width )
+void Controller::CalculateTextAlignment( const Size& size )
 {
-  // Operations that can be done only once until the text changes.
-  const OperationsMask onlyOnceOperations = static_cast<OperationsMask>( CONVERT_TO_UTF32 |
-                                                                         GET_SCRIPTS      |
-                                                                         VALIDATE_FONTS   |
-                                                                         GET_LINE_BREAKS  |
-                                                                         GET_WORD_BREAKS  |
-                                                                         SHAPE_TEXT       |
-                                                                         GET_GLYPH_METRICS );
-
-  // Operations that need to be done if the size or the text changes.
-  const OperationsMask sizeOperations =  static_cast<OperationsMask>( LAYOUT |
-                                                                      REORDER );
+  // Get the direction of the first character.
+  const CharacterDirection firstParagraphDirection = mImpl->mLogicalModel->GetCharacterDirection( 0u );
 
-  DoRelayout( Size( width, 0.f ),
-              static_cast<OperationsMask>( onlyOnceOperations |
-                                           sizeOperations ) );
+  const Size& actualSize = mImpl->mVisualModel->GetActualSize();
 
-  // Do not do again the only once operations.
-  mImpl->mOperations = static_cast<OperationsMask>( mImpl->mOperations & ~onlyOnceOperations );
+  // 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 )
+    {
+      horizontalAlignment = LayoutEngine::HORIZONTAL_ALIGN_END;
+    }
+    else
+    {
+      horizontalAlignment = LayoutEngine::HORIZONTAL_ALIGN_BEGIN;
+    }
+  }
 
-  // Do the size related operations again.
-  mImpl->mOperations = static_cast<OperationsMask>( mImpl->mOperations | sizeOperations );
+  switch( horizontalAlignment )
+  {
+    case LayoutEngine::HORIZONTAL_ALIGN_BEGIN:
+    {
+      mImpl->mAlignmentOffset.x = 0.f;
+      break;
+    }
+    case LayoutEngine::HORIZONTAL_ALIGN_CENTER:
+    {
+      const int intOffset = static_cast<int>( 0.5f * ( size.width - actualSize.width ) ); // try to avoid pixel alignment.
+      mImpl->mAlignmentOffset.x = static_cast<float>( intOffset );
+      break;
+    }
+    case LayoutEngine::HORIZONTAL_ALIGN_END:
+    {
+      mImpl->mAlignmentOffset.x = size.width - actualSize.width;
+      break;
+    }
+  }
 
-  return mImpl->mVisualModel->GetActualSize().height;
+  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:
+    {
+      const int intOffset = static_cast<int>( 0.5f * ( size.height - actualSize.height ) ); // try to avoid pixel alignment.
+      mImpl->mAlignmentOffset.y = static_cast<float>( intOffset );
+      break;
+    }
+    case LayoutEngine::VERTICAL_ALIGN_BOTTOM:
+    {
+      mImpl->mAlignmentOffset.y = size.height - actualSize.height;
+      break;
+    }
+  }
 }
 
 View& Controller::GetView()
@@ -643,6 +1674,55 @@ void Controller::KeyboardFocusLostEvent()
   }
 }
 
+bool Controller::KeyEvent( const Dali::KeyEvent& keyEvent )
+{
+  DALI_ASSERT_DEBUG( mImpl->mTextInput && "Unexpected KeyEvent" );
+
+  if( mImpl->mTextInput &&
+      keyEvent.state == KeyEvent::Down )
+  {
+    int keyCode = keyEvent.keyCode;
+    const std::string& keyString = keyEvent.keyPressed;
+
+    // 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 )
+    {
+      // Queue a delete event
+      ModifyEvent event;
+      event.type = DELETE_TEXT;
+      mImpl->mModifyEvents.push_back( event );
+    }
+    else if( !keyString.empty() )
+    {
+      // Queue an insert event
+      ModifyEvent event;
+      event.type = INSERT_TEXT;
+      event.text = keyString;
+      mImpl->mModifyEvents.push_back( event );
+    }
+
+    mImpl->mTextInput->ChangeState( TextInput::EDITING ); // todo Confirm this is the best place to change the state of
+
+    RequestRelayout();
+  }
+
+  return false;
+}
+
 void Controller::TapEvent( unsigned int tapCount, float x, float y )
 {
   DALI_ASSERT_DEBUG( mImpl->mTextInput && "Unexpected TapEvent" );
@@ -659,6 +1739,22 @@ void Controller::TapEvent( unsigned int tapCount, float x, float y )
   }
 }
 
+void Controller::PanEvent( Gesture::State state, const Vector2& displacement )
+{
+  DALI_ASSERT_DEBUG( mImpl->mTextInput && "Unexpected PanEvent" );
+
+  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 );
+
+    RequestRelayout();
+  }
+}
+
 void Controller::GrabHandleEvent( GrabHandleState state, float x, float y )
 {
   DALI_ASSERT_DEBUG( mImpl->mTextInput && "Unexpected GrabHandleEvent" );