14689412be0de98c19a943dc3866b39451bba537
[platform/core/uifw/dali-toolkit.git] / dali-toolkit / internal / text / text-controller.cpp
1 /*
2  * Copyright (c) 2019 Samsung Electronics Co., Ltd.
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  * http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  *
16  */
17
18 // CLASS HEADER
19 #include <dali-toolkit/internal/text/text-controller.h>
20
21 // EXTERNAL INCLUDES
22 #include <limits>
23 #include <memory.h>
24 #include <dali/public-api/adaptor-framework/key.h>
25 #include <dali/integration-api/debug.h>
26 #include <dali/devel-api/adaptor-framework/clipboard-event-notifier.h>
27 #include <dali/devel-api/text-abstraction/font-client.h>
28 #include <dali/devel-api/adaptor-framework/key-devel.h>
29
30 // INTERNAL INCLUDES
31 #include <dali-toolkit/public-api/controls/text-controls/placeholder-properties.h>
32 #include <dali-toolkit/internal/text/bidirectional-support.h>
33 #include <dali-toolkit/internal/text/character-set-conversion.h>
34 #include <dali-toolkit/internal/text/layouts/layout-parameters.h>
35 #include <dali-toolkit/internal/text/markup-processor.h>
36 #include <dali-toolkit/internal/text/multi-language-support.h>
37 #include <dali-toolkit/internal/text/text-controller-impl.h>
38 #include <dali-toolkit/internal/text/text-editable-control-interface.h>
39 #include <dali-toolkit/internal/text/text-font-style.h>
40
41 namespace
42 {
43
44 #if defined(DEBUG_ENABLED)
45   Debug::Filter* gLogFilter = Debug::Filter::New(Debug::NoLogging, true, "LOG_TEXT_CONTROLS");
46 #endif
47
48 const float MAX_FLOAT = std::numeric_limits<float>::max();
49
50 const std::string EMPTY_STRING("");
51
52 const std::string KEY_C_NAME = "c";
53 const std::string KEY_V_NAME = "v";
54 const std::string KEY_X_NAME = "x";
55
56 const char * const PLACEHOLDER_TEXT = "text";
57 const char * const PLACEHOLDER_TEXT_FOCUSED = "textFocused";
58 const char * const PLACEHOLDER_COLOR = "color";
59 const char * const PLACEHOLDER_FONT_FAMILY = "fontFamily";
60 const char * const PLACEHOLDER_FONT_STYLE = "fontStyle";
61 const char * const PLACEHOLDER_POINT_SIZE = "pointSize";
62 const char * const PLACEHOLDER_PIXEL_SIZE = "pixelSize";
63 const char * const PLACEHOLDER_ELLIPSIS = "ellipsis";
64
65 float ConvertToEven( float value )
66 {
67   int intValue(static_cast<int>( value ));
68   return static_cast<float>(intValue % 2 == 0) ? intValue : (intValue + 1);
69 }
70
71 } // namespace
72
73 namespace Dali
74 {
75
76 namespace Toolkit
77 {
78
79 namespace Text
80 {
81
82 /**
83  * @brief Adds a new font description run for the selected text.
84  *
85  * The new font parameters are added after the call to this method.
86  *
87  * @param[in] eventData The event data pointer.
88  * @param[in] logicalModel The logical model where to add the new font description run.
89  * @param[out] startOfSelectedText Index to the first selected character.
90  * @param[out] lengthOfSelectedText Number of selected characters.
91  */
92 FontDescriptionRun& UpdateSelectionFontStyleRun( EventData* eventData,
93                                                  LogicalModelPtr logicalModel,
94                                                  CharacterIndex& startOfSelectedText,
95                                                  Length& lengthOfSelectedText )
96 {
97   const bool handlesCrossed = eventData->mLeftSelectionPosition > eventData->mRightSelectionPosition;
98
99   // Get start and end position of selection
100   startOfSelectedText = handlesCrossed ? eventData->mRightSelectionPosition : eventData->mLeftSelectionPosition;
101   lengthOfSelectedText = ( handlesCrossed ? eventData->mLeftSelectionPosition : eventData->mRightSelectionPosition ) - startOfSelectedText;
102
103   // Add the font run.
104   const VectorBase::SizeType numberOfRuns = logicalModel->mFontDescriptionRuns.Count();
105   logicalModel->mFontDescriptionRuns.Resize( numberOfRuns + 1u );
106
107   FontDescriptionRun& fontDescriptionRun = *( logicalModel->mFontDescriptionRuns.Begin() + numberOfRuns );
108
109   fontDescriptionRun.characterRun.characterIndex = startOfSelectedText;
110   fontDescriptionRun.characterRun.numberOfCharacters = lengthOfSelectedText;
111
112   // Recalculate the selection highlight as the metrics may have changed.
113   eventData->mUpdateLeftSelectionPosition = true;
114   eventData->mUpdateRightSelectionPosition = true;
115   eventData->mUpdateHighlightBox = true;
116
117   return fontDescriptionRun;
118 }
119
120 // public : Constructor.
121
122 ControllerPtr Controller::New()
123 {
124   return ControllerPtr( new Controller() );
125 }
126
127 ControllerPtr Controller::New( ControlInterface* controlInterface )
128 {
129   return ControllerPtr( new Controller( controlInterface ) );
130 }
131
132 ControllerPtr Controller::New( ControlInterface* controlInterface,
133                                EditableControlInterface* editableControlInterface )
134 {
135   return ControllerPtr( new Controller( controlInterface,
136                                         editableControlInterface ) );
137 }
138
139 // public : Configure the text controller.
140
141 void Controller::EnableTextInput( DecoratorPtr decorator, InputMethodContext& inputMethodContext )
142 {
143   if( !decorator )
144   {
145     delete mImpl->mEventData;
146     mImpl->mEventData = NULL;
147
148     // Nothing else to do.
149     return;
150   }
151
152   if( NULL == mImpl->mEventData )
153   {
154     mImpl->mEventData = new EventData( decorator, inputMethodContext );
155   }
156 }
157
158 void Controller::SetGlyphType( TextAbstraction::GlyphType glyphType )
159 {
160   // Metrics for bitmap & vector based glyphs are different
161   mImpl->mMetrics->SetGlyphType( glyphType );
162
163   // Clear the font-specific data
164   ClearFontData();
165
166   mImpl->RequestRelayout();
167 }
168
169 void Controller::SetMarkupProcessorEnabled( bool enable )
170 {
171   if( enable != mImpl->mMarkupProcessorEnabled )
172   {
173     //If Text was already set, call the SetText again for enabling or disabling markup
174     mImpl->mMarkupProcessorEnabled = enable;
175     std::string text;
176     GetText( text );
177     SetText( text );
178   }
179 }
180
181 bool Controller::IsMarkupProcessorEnabled() const
182 {
183   return mImpl->mMarkupProcessorEnabled;
184 }
185
186 void Controller::SetAutoScrollEnabled( bool enable )
187 {
188   DALI_LOG_INFO( gLogFilter, Debug::General, "Controller::SetAutoScrollEnabled[%s] SingleBox[%s]-> [%p]\n", (enable)?"true":"false", ( mImpl->mLayoutEngine.GetLayout() == Layout::Engine::SINGLE_LINE_BOX)?"true":"false", this );
189
190   if( mImpl->mLayoutEngine.GetLayout() == Layout::Engine::SINGLE_LINE_BOX )
191   {
192     if( enable )
193     {
194       DALI_LOG_INFO( gLogFilter, Debug::General, "Controller::SetAutoScrollEnabled for SINGLE_LINE_BOX\n" );
195       mImpl->mOperationsPending = static_cast<OperationsMask>( mImpl->mOperationsPending |
196                                                                LAYOUT                    |
197                                                                ALIGN                     |
198                                                                UPDATE_LAYOUT_SIZE        |
199                                                                UPDATE_DIRECTION          |
200                                                                REORDER );
201
202     }
203     else
204     {
205       DALI_LOG_INFO( gLogFilter, Debug::General, "Controller::SetAutoScrollEnabled Disabling autoscroll\n");
206       mImpl->mOperationsPending = static_cast<OperationsMask>( mImpl->mOperationsPending |
207                                                                LAYOUT                    |
208                                                                ALIGN                     |
209                                                                UPDATE_LAYOUT_SIZE        |
210                                                                REORDER );
211     }
212
213     mImpl->mIsAutoScrollEnabled = enable;
214     mImpl->RequestRelayout();
215   }
216   else
217   {
218     DALI_LOG_WARNING( "Attempted AutoScrolling on a non SINGLE_LINE_BOX, request ignored\n" );
219     mImpl->mIsAutoScrollEnabled = false;
220   }
221 }
222
223 bool Controller::IsAutoScrollEnabled() const
224 {
225   DALI_LOG_INFO( gLogFilter, Debug::Verbose, "Controller::IsAutoScrollEnabled[%s]\n", mImpl->mIsAutoScrollEnabled?"true":"false" );
226
227   return mImpl->mIsAutoScrollEnabled;
228 }
229
230 CharacterDirection Controller::GetAutoScrollDirection() const
231 {
232   return mImpl->mIsTextDirectionRTL;
233 }
234
235 float Controller::GetAutoScrollLineAlignment() const
236 {
237   float offset = 0.f;
238
239   if( mImpl->mModel->mVisualModel &&
240       ( 0u != mImpl->mModel->mVisualModel->mLines.Count() ) )
241   {
242     offset = ( *mImpl->mModel->mVisualModel->mLines.Begin() ).alignmentOffset;
243   }
244
245   return offset;
246 }
247
248 void Controller::SetHorizontalScrollEnabled( bool enable )
249 {
250   if( ( NULL != mImpl->mEventData ) &&
251       mImpl->mEventData->mDecorator )
252   {
253     mImpl->mEventData->mDecorator->SetHorizontalScrollEnabled( enable );
254   }
255 }
256 bool Controller::IsHorizontalScrollEnabled() const
257 {
258   if( ( NULL != mImpl->mEventData ) &&
259       mImpl->mEventData->mDecorator )
260   {
261     return mImpl->mEventData->mDecorator->IsHorizontalScrollEnabled();
262   }
263
264   return false;
265 }
266
267 void Controller::SetVerticalScrollEnabled( bool enable )
268 {
269   if( ( NULL != mImpl->mEventData ) &&
270       mImpl->mEventData->mDecorator )
271   {
272     if( mImpl->mEventData->mDecorator )
273     {
274       mImpl->mEventData->mDecorator->SetVerticalScrollEnabled( enable );
275     }
276   }
277 }
278
279 bool Controller::IsVerticalScrollEnabled() const
280 {
281   if( ( NULL != mImpl->mEventData ) &&
282       mImpl->mEventData->mDecorator )
283   {
284     return mImpl->mEventData->mDecorator->IsVerticalScrollEnabled();
285   }
286
287   return false;
288 }
289
290 void Controller::SetSmoothHandlePanEnabled( bool enable )
291 {
292   if( ( NULL != mImpl->mEventData ) &&
293       mImpl->mEventData->mDecorator )
294   {
295     mImpl->mEventData->mDecorator->SetSmoothHandlePanEnabled( enable );
296   }
297 }
298
299 bool Controller::IsSmoothHandlePanEnabled() const
300 {
301   if( ( NULL != mImpl->mEventData ) &&
302       mImpl->mEventData->mDecorator )
303   {
304     return mImpl->mEventData->mDecorator->IsSmoothHandlePanEnabled();
305   }
306
307   return false;
308 }
309
310 void Controller::SetMaximumNumberOfCharacters( Length maxCharacters )
311 {
312   mImpl->mMaximumNumberOfCharacters = maxCharacters;
313 }
314
315 int Controller::GetMaximumNumberOfCharacters()
316 {
317   return mImpl->mMaximumNumberOfCharacters;
318 }
319
320 void Controller::SetEnableCursorBlink( bool enable )
321 {
322   DALI_ASSERT_DEBUG( NULL != mImpl->mEventData && "TextInput disabled" );
323
324   if( NULL != mImpl->mEventData )
325   {
326     mImpl->mEventData->mCursorBlinkEnabled = enable;
327
328     if( !enable &&
329         mImpl->mEventData->mDecorator )
330     {
331       mImpl->mEventData->mDecorator->StopCursorBlink();
332     }
333   }
334 }
335
336 bool Controller::GetEnableCursorBlink() const
337 {
338   if( NULL != mImpl->mEventData )
339   {
340     return mImpl->mEventData->mCursorBlinkEnabled;
341   }
342
343   return false;
344 }
345
346 void Controller::SetMultiLineEnabled( bool enable )
347 {
348   const Layout::Engine::Type layout = enable ? Layout::Engine::MULTI_LINE_BOX : Layout::Engine::SINGLE_LINE_BOX;
349
350   if( layout != mImpl->mLayoutEngine.GetLayout() )
351   {
352     // Set the layout type.
353     mImpl->mLayoutEngine.SetLayout( layout );
354
355     // Set the flags to redo the layout operations
356     const OperationsMask layoutOperations =  static_cast<OperationsMask>( LAYOUT             |
357                                                                           UPDATE_LAYOUT_SIZE |
358                                                                           ALIGN              |
359                                                                           REORDER );
360
361     mImpl->mTextUpdateInfo.mFullRelayoutNeeded = true;
362     mImpl->mOperationsPending = static_cast<OperationsMask>( mImpl->mOperationsPending | layoutOperations );
363
364     // Need to recalculate natural size
365     mImpl->mRecalculateNaturalSize = true;
366
367     mImpl->RequestRelayout();
368   }
369 }
370
371 bool Controller::IsMultiLineEnabled() const
372 {
373   return Layout::Engine::MULTI_LINE_BOX == mImpl->mLayoutEngine.GetLayout();
374 }
375
376 void Controller::SetHorizontalAlignment( Text::HorizontalAlignment::Type alignment )
377 {
378   if( alignment != mImpl->mModel->mHorizontalAlignment )
379   {
380     // Set the alignment.
381     mImpl->mModel->mHorizontalAlignment = alignment;
382
383     // Set the flag to redo the alignment operation.
384     mImpl->mOperationsPending = static_cast<OperationsMask>( mImpl->mOperationsPending | ALIGN );
385
386     mImpl->RequestRelayout();
387   }
388 }
389
390 Text::HorizontalAlignment::Type Controller::GetHorizontalAlignment() const
391 {
392   return mImpl->mModel->mHorizontalAlignment;
393 }
394
395 void Controller::SetVerticalAlignment( VerticalAlignment::Type alignment )
396 {
397   if( alignment != mImpl->mModel->mVerticalAlignment )
398   {
399     // Set the alignment.
400     mImpl->mModel->mVerticalAlignment = alignment;
401
402     mImpl->mOperationsPending = static_cast<OperationsMask>( mImpl->mOperationsPending | ALIGN );
403
404     mImpl->RequestRelayout();
405   }
406 }
407
408 VerticalAlignment::Type Controller::GetVerticalAlignment() const
409 {
410   return mImpl->mModel->mVerticalAlignment;
411 }
412
413 bool Controller::IsIgnoreSpacesAfterText() const
414 {
415   return mImpl->mModel->mIgnoreSpacesAfterText;
416 }
417
418 void Controller::SetIgnoreSpacesAfterText( bool ignore )
419 {
420   mImpl->mModel->mIgnoreSpacesAfterText = ignore;
421 }
422
423 bool Controller::IsMatchSystemLanguageDirection() const
424 {
425   return mImpl->mModel->mMatchSystemLanguageDirection;
426 }
427
428 void Controller::SetMatchSystemLanguageDirection( bool match )
429 {
430   mImpl->mModel->mMatchSystemLanguageDirection = match;
431 }
432
433 void Controller::SetLayoutDirection( Dali::LayoutDirection::Type layoutDirection )
434 {
435   mImpl->mLayoutDirection = layoutDirection;
436 }
437
438
439 void Controller::SetLineWrapMode( Text::LineWrap::Mode lineWrapMode )
440 {
441   if( lineWrapMode != mImpl->mModel->mLineWrapMode )
442   {
443     // Set the text wrap mode.
444     mImpl->mModel->mLineWrapMode = lineWrapMode;
445
446
447     // Update Text layout for applying wrap mode
448     mImpl->mOperationsPending = static_cast<OperationsMask>( mImpl->mOperationsPending |
449                                                              ALIGN                     |
450                                                              LAYOUT                    |
451                                                              UPDATE_LAYOUT_SIZE        |
452                                                              REORDER                   );
453     mImpl->mTextUpdateInfo.mCharacterIndex = 0u;
454     mImpl->mTextUpdateInfo.mNumberOfCharactersToRemove = mImpl->mTextUpdateInfo.mPreviousNumberOfCharacters;
455     mImpl->mTextUpdateInfo.mNumberOfCharactersToAdd = mImpl->mModel->mLogicalModel->mText.Count();
456
457     // Request relayout
458     mImpl->RequestRelayout();
459   }
460 }
461
462 Text::LineWrap::Mode Controller::GetLineWrapMode() const
463 {
464   return mImpl->mModel->mLineWrapMode;
465 }
466
467 void Controller::SetTextElideEnabled( bool enabled )
468 {
469   mImpl->mModel->mElideEnabled = enabled;
470 }
471
472 bool Controller::IsTextElideEnabled() const
473 {
474   return mImpl->mModel->mElideEnabled;
475 }
476
477 void Controller::SetPlaceholderTextElideEnabled( bool enabled )
478 {
479   mImpl->mEventData->mIsPlaceholderElideEnabled = enabled;
480   mImpl->mEventData->mPlaceholderEllipsisFlag = true;
481
482   // Update placeholder if there is no text
483   if( mImpl->IsShowingPlaceholderText() ||
484       ( 0u == mImpl->mModel->mLogicalModel->mText.Count() ) )
485   {
486     ShowPlaceholderText();
487   }
488 }
489
490 bool Controller::IsPlaceholderTextElideEnabled() const
491 {
492   return mImpl->mEventData->mIsPlaceholderElideEnabled;
493 }
494
495 void Controller::SetSelectionEnabled( bool enabled )
496 {
497   mImpl->mEventData->mSelectionEnabled = enabled;
498 }
499
500 bool Controller::IsSelectionEnabled() const
501 {
502   return mImpl->mEventData->mSelectionEnabled;
503 }
504
505 void Controller::SetShiftSelectionEnabled( bool enabled )
506 {
507   mImpl->mEventData->mShiftSelectionFlag = enabled;
508 }
509
510 bool Controller::IsShiftSelectionEnabled() const
511 {
512   return mImpl->mEventData->mShiftSelectionFlag;
513 }
514
515 void Controller::SetGrabHandleEnabled( bool enabled )
516 {
517   mImpl->mEventData->mGrabHandleEnabled = enabled;
518 }
519
520 bool Controller::IsGrabHandleEnabled() const
521 {
522   return mImpl->mEventData->mGrabHandleEnabled;
523 }
524
525 // public : Update
526
527 void Controller::SetText( const std::string& text )
528 {
529   DALI_LOG_INFO( gLogFilter, Debug::Verbose, "Controller::SetText\n" );
530
531   // Reset keyboard as text changed
532   mImpl->ResetInputMethodContext();
533
534   // Remove the previously set text and style.
535   ResetText();
536
537   // Remove the style.
538   ClearStyleData();
539
540   CharacterIndex lastCursorIndex = 0u;
541
542   if( NULL != mImpl->mEventData )
543   {
544     // If popup shown then hide it by switching to Editing state
545     if( ( EventData::SELECTING == mImpl->mEventData->mState )          ||
546         ( EventData::EDITING_WITH_POPUP == mImpl->mEventData->mState ) ||
547         ( EventData::EDITING_WITH_GRAB_HANDLE == mImpl->mEventData->mState ) ||
548         ( EventData::EDITING_WITH_PASTE_POPUP == mImpl->mEventData->mState ) )
549     {
550       mImpl->ChangeState( EventData::EDITING );
551     }
552   }
553
554   if( !text.empty() )
555   {
556     mImpl->mModel->mVisualModel->SetTextColor( mImpl->mTextColor );
557
558     MarkupProcessData markupProcessData( mImpl->mModel->mLogicalModel->mColorRuns,
559                                          mImpl->mModel->mLogicalModel->mFontDescriptionRuns );
560
561     Length textSize = 0u;
562     const uint8_t* utf8 = NULL;
563     if( mImpl->mMarkupProcessorEnabled )
564     {
565       ProcessMarkupString( text, markupProcessData );
566       textSize = markupProcessData.markupProcessedText.size();
567
568       // This is a bit horrible but std::string returns a (signed) char*
569       utf8 = reinterpret_cast<const uint8_t*>( markupProcessData.markupProcessedText.c_str() );
570     }
571     else
572     {
573       textSize = text.size();
574
575       // This is a bit horrible but std::string returns a (signed) char*
576       utf8 = reinterpret_cast<const uint8_t*>( text.c_str() );
577     }
578
579     //  Convert text into UTF-32
580     Vector<Character>& utf32Characters = mImpl->mModel->mLogicalModel->mText;
581     utf32Characters.Resize( textSize );
582
583     // Transform a text array encoded in utf8 into an array encoded in utf32.
584     // It returns the actual number of characters.
585     Length characterCount = Utf8ToUtf32( utf8, textSize, utf32Characters.Begin() );
586     utf32Characters.Resize( characterCount );
587
588     DALI_ASSERT_DEBUG( textSize >= characterCount && "Invalid UTF32 conversion length" );
589     DALI_LOG_INFO( gLogFilter, Debug::Verbose, "Controller::SetText %p UTF8 size %d, UTF32 size %d\n", this, textSize, mImpl->mModel->mLogicalModel->mText.Count() );
590
591     // The characters to be added.
592     mImpl->mTextUpdateInfo.mNumberOfCharactersToAdd = mImpl->mModel->mLogicalModel->mText.Count();
593
594     // To reset the cursor position
595     lastCursorIndex = characterCount;
596
597     // Update the rest of the model during size negotiation
598     mImpl->QueueModifyEvent( ModifyEvent::TEXT_REPLACED );
599
600     // The natural size needs to be re-calculated.
601     mImpl->mRecalculateNaturalSize = true;
602
603     // The text direction needs to be updated.
604     mImpl->mUpdateTextDirection = true;
605
606     // Apply modifications to the model
607     mImpl->mOperationsPending = ALL_OPERATIONS;
608   }
609   else
610   {
611     ShowPlaceholderText();
612   }
613
614   // Resets the cursor position.
615   ResetCursorPosition( lastCursorIndex );
616
617   // Scrolls the text to make the cursor visible.
618   ResetScrollPosition();
619
620   mImpl->RequestRelayout();
621
622   if( NULL != mImpl->mEventData )
623   {
624     // Cancel previously queued events
625     mImpl->mEventData->mEventQueue.clear();
626   }
627
628   // Do this last since it provides callbacks into application code.
629   if( NULL != mImpl->mEditableControlInterface )
630   {
631     mImpl->mEditableControlInterface->TextChanged();
632   }
633 }
634
635 void Controller::GetText( std::string& text ) const
636 {
637   if( !mImpl->IsShowingPlaceholderText() )
638   {
639     // Retrieves the text string.
640     mImpl->GetText( 0u, text );
641   }
642   else
643   {
644     DALI_LOG_INFO( gLogFilter, Debug::Verbose, "Controller::GetText %p empty (but showing placeholder)\n", this );
645   }
646 }
647
648 void Controller::SetPlaceholderText( PlaceholderType type, const std::string& text )
649 {
650   if( NULL != mImpl->mEventData )
651   {
652     if( PLACEHOLDER_TYPE_INACTIVE == type )
653     {
654       mImpl->mEventData->mPlaceholderTextInactive = text;
655     }
656     else
657     {
658       mImpl->mEventData->mPlaceholderTextActive = text;
659     }
660
661     // Update placeholder if there is no text
662     if( mImpl->IsShowingPlaceholderText() ||
663         ( 0u == mImpl->mModel->mLogicalModel->mText.Count() ) )
664     {
665       ShowPlaceholderText();
666     }
667   }
668 }
669
670 void Controller::GetPlaceholderText( PlaceholderType type, std::string& text ) const
671 {
672   if( NULL != mImpl->mEventData )
673   {
674     if( PLACEHOLDER_TYPE_INACTIVE == type )
675     {
676       text = mImpl->mEventData->mPlaceholderTextInactive;
677     }
678     else
679     {
680       text = mImpl->mEventData->mPlaceholderTextActive;
681     }
682   }
683 }
684
685 void Controller::UpdateAfterFontChange( const std::string& newDefaultFont )
686 {
687   DALI_LOG_INFO( gLogFilter, Debug::Verbose, "Controller::UpdateAfterFontChange\n");
688
689   if( !mImpl->mFontDefaults->familyDefined ) // If user defined font then should not update when system font changes
690   {
691     DALI_LOG_INFO( gLogFilter, Debug::Concise, "Controller::UpdateAfterFontChange newDefaultFont(%s)\n", newDefaultFont.c_str() );
692     mImpl->mFontDefaults->mFontDescription.family = newDefaultFont;
693
694     ClearFontData();
695
696     mImpl->RequestRelayout();
697   }
698 }
699
700 // public : Default style & Input style
701
702 void Controller::SetDefaultFontFamily( const std::string& defaultFontFamily )
703 {
704   if( NULL == mImpl->mFontDefaults )
705   {
706     mImpl->mFontDefaults = new FontDefaults();
707   }
708
709   mImpl->mFontDefaults->mFontDescription.family = defaultFontFamily;
710   DALI_LOG_INFO( gLogFilter, Debug::General, "Controller::SetDefaultFontFamily %s\n", defaultFontFamily.c_str());
711   mImpl->mFontDefaults->familyDefined = !defaultFontFamily.empty();
712
713   // Clear the font-specific data
714   ClearFontData();
715
716   mImpl->RequestRelayout();
717 }
718
719 const std::string& Controller::GetDefaultFontFamily() const
720 {
721   if( NULL != mImpl->mFontDefaults )
722   {
723     return mImpl->mFontDefaults->mFontDescription.family;
724   }
725
726   return EMPTY_STRING;
727 }
728
729 void Controller::SetPlaceholderFontFamily( const std::string& placeholderTextFontFamily )
730 {
731   if( NULL != mImpl->mEventData )
732   {
733     if( NULL == mImpl->mEventData->mPlaceholderFont )
734     {
735       mImpl->mEventData->mPlaceholderFont = new FontDefaults();
736     }
737
738     mImpl->mEventData->mPlaceholderFont->mFontDescription.family = placeholderTextFontFamily;
739     DALI_LOG_INFO( gLogFilter, Debug::General, "Controller::SetPlaceholderFontFamily %s\n", placeholderTextFontFamily.c_str());
740     mImpl->mEventData->mPlaceholderFont->familyDefined = !placeholderTextFontFamily.empty();
741
742     mImpl->RequestRelayout();
743   }
744 }
745
746 const std::string& Controller::GetPlaceholderFontFamily() const
747 {
748   if( ( NULL != mImpl->mEventData ) && ( NULL != mImpl->mEventData->mPlaceholderFont ) )
749   {
750     return mImpl->mEventData->mPlaceholderFont->mFontDescription.family;
751   }
752
753   return EMPTY_STRING;
754 }
755
756 void Controller::SetDefaultFontWeight( FontWeight weight )
757 {
758   if( NULL == mImpl->mFontDefaults )
759   {
760     mImpl->mFontDefaults = new FontDefaults();
761   }
762
763   mImpl->mFontDefaults->mFontDescription.weight = weight;
764   mImpl->mFontDefaults->weightDefined = true;
765
766   // Clear the font-specific data
767   ClearFontData();
768
769   mImpl->RequestRelayout();
770 }
771
772 bool Controller::IsDefaultFontWeightDefined() const
773 {
774   if( NULL != mImpl->mFontDefaults )
775   {
776     return mImpl->mFontDefaults->weightDefined;
777   }
778
779   return false;
780 }
781
782 FontWeight Controller::GetDefaultFontWeight() const
783 {
784   if( NULL != mImpl->mFontDefaults )
785   {
786     return mImpl->mFontDefaults->mFontDescription.weight;
787   }
788
789   return TextAbstraction::FontWeight::NORMAL;
790 }
791
792 void Controller::SetPlaceholderTextFontWeight( FontWeight weight )
793 {
794   if( NULL != mImpl->mEventData )
795   {
796     if( NULL == mImpl->mEventData->mPlaceholderFont )
797     {
798       mImpl->mEventData->mPlaceholderFont = new FontDefaults();
799     }
800
801     mImpl->mEventData->mPlaceholderFont->mFontDescription.weight = weight;
802     mImpl->mEventData->mPlaceholderFont->weightDefined = true;
803
804     mImpl->RequestRelayout();
805   }
806 }
807
808 bool Controller::IsPlaceholderTextFontWeightDefined() const
809 {
810   if( ( NULL != mImpl->mEventData ) && ( NULL != mImpl->mEventData->mPlaceholderFont ) )
811   {
812     return mImpl->mEventData->mPlaceholderFont->weightDefined;
813   }
814   return false;
815 }
816
817 FontWeight Controller::GetPlaceholderTextFontWeight() const
818 {
819   if( ( NULL != mImpl->mEventData ) && ( NULL != mImpl->mEventData->mPlaceholderFont ) )
820   {
821     return mImpl->mEventData->mPlaceholderFont->mFontDescription.weight;
822   }
823
824   return TextAbstraction::FontWeight::NORMAL;
825 }
826
827 void Controller::SetDefaultFontWidth( FontWidth width )
828 {
829   if( NULL == mImpl->mFontDefaults )
830   {
831     mImpl->mFontDefaults = new FontDefaults();
832   }
833
834   mImpl->mFontDefaults->mFontDescription.width = width;
835   mImpl->mFontDefaults->widthDefined = true;
836
837   // Clear the font-specific data
838   ClearFontData();
839
840   mImpl->RequestRelayout();
841 }
842
843 bool Controller::IsDefaultFontWidthDefined() const
844 {
845   if( NULL != mImpl->mFontDefaults )
846   {
847     return mImpl->mFontDefaults->widthDefined;
848   }
849
850   return false;
851 }
852
853 FontWidth Controller::GetDefaultFontWidth() const
854 {
855   if( NULL != mImpl->mFontDefaults )
856   {
857     return mImpl->mFontDefaults->mFontDescription.width;
858   }
859
860   return TextAbstraction::FontWidth::NORMAL;
861 }
862
863 void Controller::SetPlaceholderTextFontWidth( FontWidth width )
864 {
865   if( NULL != mImpl->mEventData )
866   {
867     if( NULL == mImpl->mEventData->mPlaceholderFont )
868     {
869       mImpl->mEventData->mPlaceholderFont = new FontDefaults();
870     }
871
872     mImpl->mEventData->mPlaceholderFont->mFontDescription.width = width;
873     mImpl->mEventData->mPlaceholderFont->widthDefined = true;
874
875     mImpl->RequestRelayout();
876   }
877 }
878
879 bool Controller::IsPlaceholderTextFontWidthDefined() const
880 {
881   if( ( NULL != mImpl->mEventData ) && ( NULL != mImpl->mEventData->mPlaceholderFont ) )
882   {
883     return mImpl->mEventData->mPlaceholderFont->widthDefined;
884   }
885   return false;
886 }
887
888 FontWidth Controller::GetPlaceholderTextFontWidth() const
889 {
890   if( ( NULL != mImpl->mEventData ) && ( NULL != mImpl->mEventData->mPlaceholderFont ) )
891   {
892     return mImpl->mEventData->mPlaceholderFont->mFontDescription.width;
893   }
894
895   return TextAbstraction::FontWidth::NORMAL;
896 }
897
898 void Controller::SetDefaultFontSlant( FontSlant slant )
899 {
900   if( NULL == mImpl->mFontDefaults )
901   {
902     mImpl->mFontDefaults = new FontDefaults();
903   }
904
905   mImpl->mFontDefaults->mFontDescription.slant = slant;
906   mImpl->mFontDefaults->slantDefined = true;
907
908   // Clear the font-specific data
909   ClearFontData();
910
911   mImpl->RequestRelayout();
912 }
913
914 bool Controller::IsDefaultFontSlantDefined() const
915 {
916   if( NULL != mImpl->mFontDefaults )
917   {
918     return mImpl->mFontDefaults->slantDefined;
919   }
920   return false;
921 }
922
923 FontSlant Controller::GetDefaultFontSlant() const
924 {
925   if( NULL != mImpl->mFontDefaults )
926   {
927     return mImpl->mFontDefaults->mFontDescription.slant;
928   }
929
930   return TextAbstraction::FontSlant::NORMAL;
931 }
932
933 void Controller::SetPlaceholderTextFontSlant( FontSlant slant )
934 {
935   if( NULL != mImpl->mEventData )
936   {
937     if( NULL == mImpl->mEventData->mPlaceholderFont )
938     {
939       mImpl->mEventData->mPlaceholderFont = new FontDefaults();
940     }
941
942     mImpl->mEventData->mPlaceholderFont->mFontDescription.slant = slant;
943     mImpl->mEventData->mPlaceholderFont->slantDefined = true;
944
945     mImpl->RequestRelayout();
946   }
947 }
948
949 bool Controller::IsPlaceholderTextFontSlantDefined() const
950 {
951   if( ( NULL != mImpl->mEventData ) && ( NULL != mImpl->mEventData->mPlaceholderFont ) )
952   {
953     return mImpl->mEventData->mPlaceholderFont->slantDefined;
954   }
955   return false;
956 }
957
958 FontSlant Controller::GetPlaceholderTextFontSlant() const
959 {
960   if( ( NULL != mImpl->mEventData ) && ( NULL != mImpl->mEventData->mPlaceholderFont ) )
961   {
962     return mImpl->mEventData->mPlaceholderFont->mFontDescription.slant;
963   }
964
965   return TextAbstraction::FontSlant::NORMAL;
966 }
967
968 void Controller::SetDefaultFontSize( float fontSize, FontSizeType type )
969 {
970   if( NULL == mImpl->mFontDefaults )
971   {
972     mImpl->mFontDefaults = new FontDefaults();
973   }
974
975   switch( type )
976   {
977     case POINT_SIZE:
978     {
979       mImpl->mFontDefaults->mDefaultPointSize = fontSize;
980       mImpl->mFontDefaults->sizeDefined = true;
981       break;
982     }
983     case PIXEL_SIZE:
984     {
985       // Point size = Pixel size * 72.f / DPI
986       unsigned int horizontalDpi = 0u;
987       unsigned int verticalDpi = 0u;
988       TextAbstraction::FontClient fontClient = TextAbstraction::FontClient::Get();
989       fontClient.GetDpi( horizontalDpi, verticalDpi );
990
991       mImpl->mFontDefaults->mDefaultPointSize = ( fontSize * 72.f ) / static_cast< float >( horizontalDpi );
992       mImpl->mFontDefaults->sizeDefined = true;
993       break;
994     }
995   }
996
997   // Clear the font-specific data
998   ClearFontData();
999
1000   mImpl->RequestRelayout();
1001 }
1002
1003 float Controller::GetDefaultFontSize( FontSizeType type ) const
1004 {
1005   float value = 0.0f;
1006   if( NULL != mImpl->mFontDefaults )
1007   {
1008     switch( type )
1009     {
1010       case POINT_SIZE:
1011       {
1012         value = mImpl->mFontDefaults->mDefaultPointSize;
1013         break;
1014       }
1015       case PIXEL_SIZE:
1016       {
1017         // Pixel size = Point size * DPI / 72.f
1018         unsigned int horizontalDpi = 0u;
1019         unsigned int verticalDpi = 0u;
1020         TextAbstraction::FontClient fontClient = TextAbstraction::FontClient::Get();
1021         fontClient.GetDpi( horizontalDpi, verticalDpi );
1022
1023         value = mImpl->mFontDefaults->mDefaultPointSize * static_cast< float >( horizontalDpi ) / 72.f;
1024         break;
1025       }
1026     }
1027     return value;
1028   }
1029
1030   return value;
1031 }
1032
1033 void Controller::SetPlaceholderTextFontSize( float fontSize, FontSizeType type )
1034 {
1035   if( NULL != mImpl->mEventData )
1036   {
1037     if( NULL == mImpl->mEventData->mPlaceholderFont )
1038     {
1039       mImpl->mEventData->mPlaceholderFont = new FontDefaults();
1040     }
1041
1042     switch( type )
1043     {
1044       case POINT_SIZE:
1045       {
1046         mImpl->mEventData->mPlaceholderFont->mDefaultPointSize = fontSize;
1047         mImpl->mEventData->mPlaceholderFont->sizeDefined = true;
1048         mImpl->mEventData->mIsPlaceholderPixelSize = false; // Font size flag
1049         break;
1050       }
1051       case PIXEL_SIZE:
1052       {
1053         // Point size = Pixel size * 72.f / DPI
1054         unsigned int horizontalDpi = 0u;
1055         unsigned int verticalDpi = 0u;
1056         TextAbstraction::FontClient fontClient = TextAbstraction::FontClient::Get();
1057         fontClient.GetDpi( horizontalDpi, verticalDpi );
1058
1059         mImpl->mEventData->mPlaceholderFont->mDefaultPointSize = ( fontSize * 72.f ) / static_cast< float >( horizontalDpi );
1060         mImpl->mEventData->mPlaceholderFont->sizeDefined = true;
1061         mImpl->mEventData->mIsPlaceholderPixelSize = true; // Font size flag
1062         break;
1063       }
1064     }
1065
1066     mImpl->RequestRelayout();
1067   }
1068 }
1069
1070 float Controller::GetPlaceholderTextFontSize( FontSizeType type ) const
1071 {
1072   float value = 0.0f;
1073   if( NULL != mImpl->mEventData )
1074   {
1075     switch( type )
1076     {
1077       case POINT_SIZE:
1078       {
1079         if( NULL != mImpl->mEventData->mPlaceholderFont )
1080         {
1081           value = mImpl->mEventData->mPlaceholderFont->mDefaultPointSize;
1082         }
1083         else
1084         {
1085           // If the placeholder text font size is not set, then return the default font size.
1086           value = GetDefaultFontSize( POINT_SIZE );
1087         }
1088         break;
1089       }
1090       case PIXEL_SIZE:
1091       {
1092         if( NULL != mImpl->mEventData->mPlaceholderFont )
1093         {
1094           // Pixel size = Point size * DPI / 72.f
1095           unsigned int horizontalDpi = 0u;
1096           unsigned int verticalDpi = 0u;
1097           TextAbstraction::FontClient fontClient = TextAbstraction::FontClient::Get();
1098           fontClient.GetDpi( horizontalDpi, verticalDpi );
1099
1100           value = mImpl->mEventData->mPlaceholderFont->mDefaultPointSize * static_cast< float >( horizontalDpi ) / 72.f;
1101         }
1102         else
1103         {
1104           // If the placeholder text font size is not set, then return the default font size.
1105           value = GetDefaultFontSize( PIXEL_SIZE );
1106         }
1107         break;
1108       }
1109     }
1110     return value;
1111   }
1112
1113   return value;
1114 }
1115
1116 void Controller::SetDefaultColor( const Vector4& color )
1117 {
1118   mImpl->mTextColor = color;
1119
1120   if( !mImpl->IsShowingPlaceholderText() )
1121   {
1122     mImpl->mModel->mVisualModel->SetTextColor( color );
1123
1124     mImpl->RequestRelayout();
1125   }
1126 }
1127
1128 const Vector4& Controller::GetDefaultColor() const
1129 {
1130   return mImpl->mTextColor;
1131 }
1132
1133 void Controller::SetPlaceholderTextColor( const Vector4& textColor )
1134 {
1135   if( NULL != mImpl->mEventData )
1136   {
1137     mImpl->mEventData->mPlaceholderTextColor = textColor;
1138   }
1139
1140   if( mImpl->IsShowingPlaceholderText() )
1141   {
1142     mImpl->mModel->mVisualModel->SetTextColor( textColor );
1143     mImpl->RequestRelayout();
1144   }
1145 }
1146
1147 const Vector4& Controller::GetPlaceholderTextColor() const
1148 {
1149   if( NULL != mImpl->mEventData )
1150   {
1151     return mImpl->mEventData->mPlaceholderTextColor;
1152   }
1153
1154   return Color::BLACK;
1155 }
1156
1157 void Controller::SetShadowOffset( const Vector2& shadowOffset )
1158 {
1159   mImpl->mModel->mVisualModel->SetShadowOffset( shadowOffset );
1160
1161   mImpl->RequestRelayout();
1162 }
1163
1164 const Vector2& Controller::GetShadowOffset() const
1165 {
1166   return mImpl->mModel->mVisualModel->GetShadowOffset();
1167 }
1168
1169 void Controller::SetShadowColor( const Vector4& shadowColor )
1170 {
1171   mImpl->mModel->mVisualModel->SetShadowColor( shadowColor );
1172
1173   mImpl->RequestRelayout();
1174 }
1175
1176 const Vector4& Controller::GetShadowColor() const
1177 {
1178   return mImpl->mModel->mVisualModel->GetShadowColor();
1179 }
1180
1181 void Controller::SetShadowBlurRadius( const float& shadowBlurRadius )
1182 {
1183   if ( fabsf( GetShadowBlurRadius() - shadowBlurRadius ) > Math::MACHINE_EPSILON_1 )
1184   {
1185     mImpl->mModel->mVisualModel->SetShadowBlurRadius( shadowBlurRadius );
1186
1187     mImpl->RequestRelayout();
1188   }
1189 }
1190
1191 const float& Controller::GetShadowBlurRadius() const
1192 {
1193   return mImpl->mModel->mVisualModel->GetShadowBlurRadius();
1194 }
1195
1196 void Controller::SetUnderlineColor( const Vector4& color )
1197 {
1198   mImpl->mModel->mVisualModel->SetUnderlineColor( color );
1199
1200   mImpl->RequestRelayout();
1201 }
1202
1203 const Vector4& Controller::GetUnderlineColor() const
1204 {
1205   return mImpl->mModel->mVisualModel->GetUnderlineColor();
1206 }
1207
1208 void Controller::SetUnderlineEnabled( bool enabled )
1209 {
1210   mImpl->mModel->mVisualModel->SetUnderlineEnabled( enabled );
1211
1212   mImpl->RequestRelayout();
1213 }
1214
1215 bool Controller::IsUnderlineEnabled() const
1216 {
1217   return mImpl->mModel->mVisualModel->IsUnderlineEnabled();
1218 }
1219
1220 void Controller::SetUnderlineHeight( float height )
1221 {
1222   mImpl->mModel->mVisualModel->SetUnderlineHeight( height );
1223
1224   mImpl->RequestRelayout();
1225 }
1226
1227 float Controller::GetUnderlineHeight() const
1228 {
1229   return mImpl->mModel->mVisualModel->GetUnderlineHeight();
1230 }
1231
1232 void Controller::SetOutlineColor( const Vector4& color )
1233 {
1234   mImpl->mModel->mVisualModel->SetOutlineColor( color );
1235
1236   mImpl->RequestRelayout();
1237 }
1238
1239 const Vector4& Controller::GetOutlineColor() const
1240 {
1241   return mImpl->mModel->mVisualModel->GetOutlineColor();
1242 }
1243
1244 void Controller::SetOutlineWidth( unsigned int width )
1245 {
1246   mImpl->mModel->mVisualModel->SetOutlineWidth( width );
1247
1248   mImpl->RequestRelayout();
1249 }
1250
1251 unsigned int Controller::GetOutlineWidth() const
1252 {
1253   return mImpl->mModel->mVisualModel->GetOutlineWidth();
1254 }
1255
1256 void Controller::SetBackgroundColor( const Vector4& color )
1257 {
1258   mImpl->mModel->mVisualModel->SetBackgroundColor( color );
1259
1260   mImpl->RequestRelayout();
1261 }
1262
1263 const Vector4& Controller::GetBackgroundColor() const
1264 {
1265   return mImpl->mModel->mVisualModel->GetBackgroundColor();
1266 }
1267
1268 void Controller::SetBackgroundEnabled( bool enabled )
1269 {
1270   mImpl->mModel->mVisualModel->SetBackgroundEnabled( enabled );
1271
1272   mImpl->RequestRelayout();
1273 }
1274
1275 bool Controller::IsBackgroundEnabled() const
1276 {
1277   return mImpl->mModel->mVisualModel->IsBackgroundEnabled();
1278 }
1279
1280 void Controller::SetDefaultEmbossProperties( const std::string& embossProperties )
1281 {
1282   if( NULL == mImpl->mEmbossDefaults )
1283   {
1284     mImpl->mEmbossDefaults = new EmbossDefaults();
1285   }
1286
1287   mImpl->mEmbossDefaults->properties = embossProperties;
1288 }
1289
1290 const std::string& Controller::GetDefaultEmbossProperties() const
1291 {
1292   if( NULL != mImpl->mEmbossDefaults )
1293   {
1294     return mImpl->mEmbossDefaults->properties;
1295   }
1296
1297   return EMPTY_STRING;
1298 }
1299
1300 void Controller::SetDefaultOutlineProperties( const std::string& outlineProperties )
1301 {
1302   if( NULL == mImpl->mOutlineDefaults )
1303   {
1304     mImpl->mOutlineDefaults = new OutlineDefaults();
1305   }
1306
1307   mImpl->mOutlineDefaults->properties = outlineProperties;
1308 }
1309
1310 const std::string& Controller::GetDefaultOutlineProperties() const
1311 {
1312   if( NULL != mImpl->mOutlineDefaults )
1313   {
1314     return mImpl->mOutlineDefaults->properties;
1315   }
1316
1317   return EMPTY_STRING;
1318 }
1319
1320 bool Controller::SetDefaultLineSpacing( float lineSpacing )
1321 {
1322   if( std::abs(lineSpacing - mImpl->mLayoutEngine.GetDefaultLineSpacing()) > Math::MACHINE_EPSILON_1000 )
1323   {
1324     mImpl->mLayoutEngine.SetDefaultLineSpacing(lineSpacing);
1325     mImpl->mRecalculateNaturalSize = true;
1326     return true;
1327   }
1328   return false;
1329 }
1330
1331 float Controller::GetDefaultLineSpacing() const
1332 {
1333   return mImpl->mLayoutEngine.GetDefaultLineSpacing();
1334 }
1335
1336 void Controller::SetInputColor( const Vector4& color )
1337 {
1338   if( NULL != mImpl->mEventData )
1339   {
1340     mImpl->mEventData->mInputStyle.textColor = color;
1341     mImpl->mEventData->mInputStyle.isDefaultColor = false;
1342
1343     if( EventData::SELECTING == mImpl->mEventData->mState )
1344     {
1345       const bool handlesCrossed = mImpl->mEventData->mLeftSelectionPosition > mImpl->mEventData->mRightSelectionPosition;
1346
1347       // Get start and end position of selection
1348       const CharacterIndex startOfSelectedText = handlesCrossed ? mImpl->mEventData->mRightSelectionPosition : mImpl->mEventData->mLeftSelectionPosition;
1349       const Length lengthOfSelectedText = ( handlesCrossed ? mImpl->mEventData->mLeftSelectionPosition : mImpl->mEventData->mRightSelectionPosition ) - startOfSelectedText;
1350
1351       // Add the color run.
1352       const VectorBase::SizeType numberOfRuns = mImpl->mModel->mLogicalModel->mColorRuns.Count();
1353       mImpl->mModel->mLogicalModel->mColorRuns.Resize( numberOfRuns + 1u );
1354
1355       ColorRun& colorRun = *( mImpl->mModel->mLogicalModel->mColorRuns.Begin() + numberOfRuns );
1356       colorRun.color = color;
1357       colorRun.characterRun.characterIndex = startOfSelectedText;
1358       colorRun.characterRun.numberOfCharacters = lengthOfSelectedText;
1359
1360       // Request to relayout.
1361       mImpl->mOperationsPending = static_cast<OperationsMask>( mImpl->mOperationsPending | COLOR );
1362       mImpl->RequestRelayout();
1363
1364       mImpl->mTextUpdateInfo.mCharacterIndex = startOfSelectedText;
1365       mImpl->mTextUpdateInfo.mNumberOfCharactersToRemove = lengthOfSelectedText;
1366       mImpl->mTextUpdateInfo.mNumberOfCharactersToAdd = lengthOfSelectedText;
1367     }
1368   }
1369 }
1370
1371 const Vector4& Controller::GetInputColor() const
1372 {
1373   if( NULL != mImpl->mEventData )
1374   {
1375     return mImpl->mEventData->mInputStyle.textColor;
1376   }
1377
1378   // Return the default text's color if there is no EventData.
1379   return mImpl->mTextColor;
1380
1381 }
1382
1383 void Controller::SetInputFontFamily( const std::string& fontFamily )
1384 {
1385   if( NULL != mImpl->mEventData )
1386   {
1387     mImpl->mEventData->mInputStyle.familyName = fontFamily;
1388     mImpl->mEventData->mInputStyle.isFamilyDefined = true;
1389
1390     if( EventData::SELECTING == mImpl->mEventData->mState )
1391     {
1392       CharacterIndex startOfSelectedText = 0u;
1393       Length lengthOfSelectedText = 0u;
1394       FontDescriptionRun& fontDescriptionRun = UpdateSelectionFontStyleRun( mImpl->mEventData,
1395                                                                             mImpl->mModel->mLogicalModel,
1396                                                                             startOfSelectedText,
1397                                                                             lengthOfSelectedText );
1398
1399       fontDescriptionRun.familyLength = fontFamily.size();
1400       fontDescriptionRun.familyName = new char[fontDescriptionRun.familyLength];
1401       memcpy( fontDescriptionRun.familyName, fontFamily.c_str(), fontDescriptionRun.familyLength );
1402       fontDescriptionRun.familyDefined = true;
1403
1404       // The memory allocated for the font family name is freed when the font description is removed from the logical model.
1405
1406       // Request to relayout.
1407       mImpl->mOperationsPending = static_cast<OperationsMask>( mImpl->mOperationsPending |
1408                                                                VALIDATE_FONTS            |
1409                                                                SHAPE_TEXT                |
1410                                                                GET_GLYPH_METRICS         |
1411                                                                LAYOUT                    |
1412                                                                UPDATE_LAYOUT_SIZE        |
1413                                                                REORDER                   |
1414                                                                ALIGN );
1415       mImpl->mRecalculateNaturalSize = true;
1416       mImpl->RequestRelayout();
1417
1418       mImpl->mTextUpdateInfo.mCharacterIndex = startOfSelectedText;
1419       mImpl->mTextUpdateInfo.mNumberOfCharactersToRemove = lengthOfSelectedText;
1420       mImpl->mTextUpdateInfo.mNumberOfCharactersToAdd = lengthOfSelectedText;
1421
1422       // As the font changes, recalculate the handle positions is needed.
1423       mImpl->mEventData->mUpdateLeftSelectionPosition = true;
1424       mImpl->mEventData->mUpdateRightSelectionPosition = true;
1425       mImpl->mEventData->mUpdateHighlightBox = true;
1426       mImpl->mEventData->mScrollAfterUpdatePosition = true;
1427     }
1428   }
1429 }
1430
1431 const std::string& Controller::GetInputFontFamily() const
1432 {
1433   if( NULL != mImpl->mEventData )
1434   {
1435     return mImpl->mEventData->mInputStyle.familyName;
1436   }
1437
1438   // Return the default font's family if there is no EventData.
1439   return GetDefaultFontFamily();
1440 }
1441
1442 void Controller::SetInputFontWeight( FontWeight weight )
1443 {
1444   if( NULL != mImpl->mEventData )
1445   {
1446     mImpl->mEventData->mInputStyle.weight = weight;
1447     mImpl->mEventData->mInputStyle.isWeightDefined = true;
1448
1449     if( EventData::SELECTING == mImpl->mEventData->mState )
1450     {
1451       CharacterIndex startOfSelectedText = 0u;
1452       Length lengthOfSelectedText = 0u;
1453       FontDescriptionRun& fontDescriptionRun = UpdateSelectionFontStyleRun( mImpl->mEventData,
1454                                                                             mImpl->mModel->mLogicalModel,
1455                                                                             startOfSelectedText,
1456                                                                             lengthOfSelectedText );
1457
1458       fontDescriptionRun.weight = weight;
1459       fontDescriptionRun.weightDefined = true;
1460
1461       // Request to relayout.
1462       mImpl->mOperationsPending = static_cast<OperationsMask>( mImpl->mOperationsPending |
1463                                                                VALIDATE_FONTS            |
1464                                                                SHAPE_TEXT                |
1465                                                                GET_GLYPH_METRICS         |
1466                                                                LAYOUT                    |
1467                                                                UPDATE_LAYOUT_SIZE        |
1468                                                                REORDER                   |
1469                                                                ALIGN );
1470       mImpl->mRecalculateNaturalSize = true;
1471       mImpl->RequestRelayout();
1472
1473       mImpl->mTextUpdateInfo.mCharacterIndex = startOfSelectedText;
1474       mImpl->mTextUpdateInfo.mNumberOfCharactersToRemove = lengthOfSelectedText;
1475       mImpl->mTextUpdateInfo.mNumberOfCharactersToAdd = lengthOfSelectedText;
1476
1477       // As the font might change, recalculate the handle positions is needed.
1478       mImpl->mEventData->mUpdateLeftSelectionPosition = true;
1479       mImpl->mEventData->mUpdateRightSelectionPosition = true;
1480       mImpl->mEventData->mUpdateHighlightBox = true;
1481       mImpl->mEventData->mScrollAfterUpdatePosition = true;
1482     }
1483   }
1484 }
1485
1486 bool Controller::IsInputFontWeightDefined() const
1487 {
1488   bool defined = false;
1489
1490   if( NULL != mImpl->mEventData )
1491   {
1492     defined = mImpl->mEventData->mInputStyle.isWeightDefined;
1493   }
1494
1495   return defined;
1496 }
1497
1498 FontWeight Controller::GetInputFontWeight() const
1499 {
1500   if( NULL != mImpl->mEventData )
1501   {
1502     return mImpl->mEventData->mInputStyle.weight;
1503   }
1504
1505   return GetDefaultFontWeight();
1506 }
1507
1508 void Controller::SetInputFontWidth( FontWidth width )
1509 {
1510   if( NULL != mImpl->mEventData )
1511   {
1512     mImpl->mEventData->mInputStyle.width = width;
1513     mImpl->mEventData->mInputStyle.isWidthDefined = true;
1514
1515     if( EventData::SELECTING == mImpl->mEventData->mState )
1516     {
1517       CharacterIndex startOfSelectedText = 0u;
1518       Length lengthOfSelectedText = 0u;
1519       FontDescriptionRun& fontDescriptionRun = UpdateSelectionFontStyleRun( mImpl->mEventData,
1520                                                                             mImpl->mModel->mLogicalModel,
1521                                                                             startOfSelectedText,
1522                                                                             lengthOfSelectedText );
1523
1524       fontDescriptionRun.width = width;
1525       fontDescriptionRun.widthDefined = true;
1526
1527       // Request to relayout.
1528       mImpl->mOperationsPending = static_cast<OperationsMask>( mImpl->mOperationsPending |
1529                                                                VALIDATE_FONTS            |
1530                                                                SHAPE_TEXT                |
1531                                                                GET_GLYPH_METRICS         |
1532                                                                LAYOUT                    |
1533                                                                UPDATE_LAYOUT_SIZE        |
1534                                                                REORDER                   |
1535                                                                ALIGN );
1536       mImpl->mRecalculateNaturalSize = true;
1537       mImpl->RequestRelayout();
1538
1539       mImpl->mTextUpdateInfo.mCharacterIndex = startOfSelectedText;
1540       mImpl->mTextUpdateInfo.mNumberOfCharactersToRemove = lengthOfSelectedText;
1541       mImpl->mTextUpdateInfo.mNumberOfCharactersToAdd = lengthOfSelectedText;
1542
1543       // As the font might change, recalculate the handle positions is needed.
1544       mImpl->mEventData->mUpdateLeftSelectionPosition = true;
1545       mImpl->mEventData->mUpdateRightSelectionPosition = true;
1546       mImpl->mEventData->mUpdateHighlightBox = true;
1547       mImpl->mEventData->mScrollAfterUpdatePosition = true;
1548     }
1549   }
1550 }
1551
1552 bool Controller::IsInputFontWidthDefined() const
1553 {
1554   bool defined = false;
1555
1556   if( NULL != mImpl->mEventData )
1557   {
1558     defined = mImpl->mEventData->mInputStyle.isWidthDefined;
1559   }
1560
1561   return defined;
1562 }
1563
1564 FontWidth Controller::GetInputFontWidth() const
1565 {
1566   if( NULL != mImpl->mEventData )
1567   {
1568     return mImpl->mEventData->mInputStyle.width;
1569   }
1570
1571   return GetDefaultFontWidth();
1572 }
1573
1574 void Controller::SetInputFontSlant( FontSlant slant )
1575 {
1576   if( NULL != mImpl->mEventData )
1577   {
1578     mImpl->mEventData->mInputStyle.slant = slant;
1579     mImpl->mEventData->mInputStyle.isSlantDefined = true;
1580
1581     if( EventData::SELECTING == mImpl->mEventData->mState )
1582     {
1583       CharacterIndex startOfSelectedText = 0u;
1584       Length lengthOfSelectedText = 0u;
1585       FontDescriptionRun& fontDescriptionRun = UpdateSelectionFontStyleRun( mImpl->mEventData,
1586                                                                             mImpl->mModel->mLogicalModel,
1587                                                                             startOfSelectedText,
1588                                                                             lengthOfSelectedText );
1589
1590       fontDescriptionRun.slant = slant;
1591       fontDescriptionRun.slantDefined = true;
1592
1593       // Request to relayout.
1594       mImpl->mOperationsPending = static_cast<OperationsMask>( mImpl->mOperationsPending |
1595                                                                VALIDATE_FONTS            |
1596                                                                SHAPE_TEXT                |
1597                                                                GET_GLYPH_METRICS         |
1598                                                                LAYOUT                    |
1599                                                                UPDATE_LAYOUT_SIZE        |
1600                                                                REORDER                   |
1601                                                                ALIGN );
1602       mImpl->mRecalculateNaturalSize = true;
1603       mImpl->RequestRelayout();
1604
1605       mImpl->mTextUpdateInfo.mCharacterIndex = startOfSelectedText;
1606       mImpl->mTextUpdateInfo.mNumberOfCharactersToRemove = lengthOfSelectedText;
1607       mImpl->mTextUpdateInfo.mNumberOfCharactersToAdd = lengthOfSelectedText;
1608
1609       // As the font might change, recalculate the handle positions is needed.
1610       mImpl->mEventData->mUpdateLeftSelectionPosition = true;
1611       mImpl->mEventData->mUpdateRightSelectionPosition = true;
1612       mImpl->mEventData->mUpdateHighlightBox = true;
1613       mImpl->mEventData->mScrollAfterUpdatePosition = true;
1614     }
1615   }
1616 }
1617
1618 bool Controller::IsInputFontSlantDefined() const
1619 {
1620   bool defined = false;
1621
1622   if( NULL != mImpl->mEventData )
1623   {
1624     defined = mImpl->mEventData->mInputStyle.isSlantDefined;
1625   }
1626
1627   return defined;
1628 }
1629
1630 FontSlant Controller::GetInputFontSlant() const
1631 {
1632   if( NULL != mImpl->mEventData )
1633   {
1634     return mImpl->mEventData->mInputStyle.slant;
1635   }
1636
1637   return GetDefaultFontSlant();
1638 }
1639
1640 void Controller::SetInputFontPointSize( float size )
1641 {
1642   if( NULL != mImpl->mEventData )
1643   {
1644     mImpl->mEventData->mInputStyle.size = size;
1645     mImpl->mEventData->mInputStyle.isSizeDefined = true;
1646
1647     if( EventData::SELECTING == mImpl->mEventData->mState )
1648     {
1649       CharacterIndex startOfSelectedText = 0u;
1650       Length lengthOfSelectedText = 0u;
1651       FontDescriptionRun& fontDescriptionRun = UpdateSelectionFontStyleRun( mImpl->mEventData,
1652                                                                             mImpl->mModel->mLogicalModel,
1653                                                                             startOfSelectedText,
1654                                                                             lengthOfSelectedText );
1655
1656       fontDescriptionRun.size = static_cast<PointSize26Dot6>( size * 64.f );
1657       fontDescriptionRun.sizeDefined = true;
1658
1659       // Request to relayout.
1660       mImpl->mOperationsPending = static_cast<OperationsMask>( mImpl->mOperationsPending |
1661                                                                VALIDATE_FONTS            |
1662                                                                SHAPE_TEXT                |
1663                                                                GET_GLYPH_METRICS         |
1664                                                                LAYOUT                    |
1665                                                                UPDATE_LAYOUT_SIZE        |
1666                                                                REORDER                   |
1667                                                                ALIGN );
1668       mImpl->mRecalculateNaturalSize = true;
1669       mImpl->RequestRelayout();
1670
1671       mImpl->mTextUpdateInfo.mCharacterIndex = startOfSelectedText;
1672       mImpl->mTextUpdateInfo.mNumberOfCharactersToRemove = lengthOfSelectedText;
1673       mImpl->mTextUpdateInfo.mNumberOfCharactersToAdd = lengthOfSelectedText;
1674
1675       // As the font might change, recalculate the handle positions is needed.
1676       mImpl->mEventData->mUpdateLeftSelectionPosition = true;
1677       mImpl->mEventData->mUpdateRightSelectionPosition = true;
1678       mImpl->mEventData->mUpdateHighlightBox = true;
1679       mImpl->mEventData->mScrollAfterUpdatePosition = true;
1680     }
1681   }
1682 }
1683
1684 float Controller::GetInputFontPointSize() const
1685 {
1686   if( NULL != mImpl->mEventData )
1687   {
1688     return mImpl->mEventData->mInputStyle.size;
1689   }
1690
1691   // Return the default font's point size if there is no EventData.
1692   return GetDefaultFontSize( Text::Controller::POINT_SIZE );
1693 }
1694
1695 void Controller::SetInputLineSpacing( float lineSpacing )
1696 {
1697   if( NULL != mImpl->mEventData )
1698   {
1699     mImpl->mEventData->mInputStyle.lineSpacing = lineSpacing;
1700     mImpl->mEventData->mInputStyle.isLineSpacingDefined = true;
1701   }
1702 }
1703
1704 float Controller::GetInputLineSpacing() const
1705 {
1706   if( NULL != mImpl->mEventData )
1707   {
1708     return mImpl->mEventData->mInputStyle.lineSpacing;
1709   }
1710
1711   return 0.f;
1712 }
1713
1714 void Controller::SetInputShadowProperties( const std::string& shadowProperties )
1715 {
1716   if( NULL != mImpl->mEventData )
1717   {
1718     mImpl->mEventData->mInputStyle.shadowProperties = shadowProperties;
1719   }
1720 }
1721
1722 const std::string& Controller::GetInputShadowProperties() const
1723 {
1724   if( NULL != mImpl->mEventData )
1725   {
1726     return mImpl->mEventData->mInputStyle.shadowProperties;
1727   }
1728
1729   return EMPTY_STRING;
1730 }
1731
1732 void Controller::SetInputUnderlineProperties( const std::string& underlineProperties )
1733 {
1734   if( NULL != mImpl->mEventData )
1735   {
1736     mImpl->mEventData->mInputStyle.underlineProperties = underlineProperties;
1737   }
1738 }
1739
1740 const std::string& Controller::GetInputUnderlineProperties() const
1741 {
1742   if( NULL != mImpl->mEventData )
1743   {
1744     return mImpl->mEventData->mInputStyle.underlineProperties;
1745   }
1746
1747   return EMPTY_STRING;
1748 }
1749
1750 void Controller::SetInputEmbossProperties( const std::string& embossProperties )
1751 {
1752   if( NULL != mImpl->mEventData )
1753   {
1754     mImpl->mEventData->mInputStyle.embossProperties = embossProperties;
1755   }
1756 }
1757
1758 const std::string& Controller::GetInputEmbossProperties() const
1759 {
1760   if( NULL != mImpl->mEventData )
1761   {
1762     return mImpl->mEventData->mInputStyle.embossProperties;
1763   }
1764
1765   return GetDefaultEmbossProperties();
1766 }
1767
1768 void Controller::SetInputOutlineProperties( const std::string& outlineProperties )
1769 {
1770   if( NULL != mImpl->mEventData )
1771   {
1772     mImpl->mEventData->mInputStyle.outlineProperties = outlineProperties;
1773   }
1774 }
1775
1776 const std::string& Controller::GetInputOutlineProperties() const
1777 {
1778   if( NULL != mImpl->mEventData )
1779   {
1780     return mImpl->mEventData->mInputStyle.outlineProperties;
1781   }
1782
1783   return GetDefaultOutlineProperties();
1784 }
1785
1786 void Controller::SetInputModePassword( bool passwordInput )
1787 {
1788   if( NULL != mImpl->mEventData )
1789   {
1790     mImpl->mEventData->mPasswordInput = passwordInput;
1791   }
1792 }
1793
1794 bool Controller::IsInputModePassword()
1795 {
1796   if( NULL != mImpl->mEventData )
1797   {
1798     return mImpl->mEventData->mPasswordInput;
1799   }
1800   return false;
1801 }
1802
1803 void Controller::SetNoTextDoubleTapAction( NoTextTap::Action action )
1804 {
1805   if( NULL != mImpl->mEventData )
1806   {
1807     mImpl->mEventData->mDoubleTapAction = action;
1808   }
1809 }
1810
1811 Controller::NoTextTap::Action Controller::GetNoTextDoubleTapAction() const
1812 {
1813   NoTextTap::Action action = NoTextTap::NO_ACTION;
1814
1815   if( NULL != mImpl->mEventData )
1816   {
1817     action = mImpl->mEventData->mDoubleTapAction;
1818   }
1819
1820   return action;
1821 }
1822
1823 void Controller::SetNoTextLongPressAction( NoTextTap::Action action )
1824 {
1825   if( NULL != mImpl->mEventData )
1826   {
1827     mImpl->mEventData->mLongPressAction = action;
1828   }
1829 }
1830
1831 Controller::NoTextTap::Action Controller::GetNoTextLongPressAction() const
1832 {
1833   NoTextTap::Action action = NoTextTap::NO_ACTION;
1834
1835   if( NULL != mImpl->mEventData )
1836   {
1837     action = mImpl->mEventData->mLongPressAction;
1838   }
1839
1840   return action;
1841 }
1842
1843 bool Controller::IsUnderlineSetByString()
1844 {
1845   return mImpl->mUnderlineSetByString;
1846 }
1847
1848 void Controller::UnderlineSetByString( bool setByString )
1849 {
1850   mImpl->mUnderlineSetByString = setByString;
1851 }
1852
1853 bool Controller::IsShadowSetByString()
1854 {
1855   return mImpl->mShadowSetByString;
1856 }
1857
1858 void Controller::ShadowSetByString( bool setByString )
1859 {
1860   mImpl->mShadowSetByString = setByString;
1861 }
1862
1863 bool Controller::IsOutlineSetByString()
1864 {
1865   return mImpl->mOutlineSetByString;
1866 }
1867
1868 void Controller::OutlineSetByString( bool setByString )
1869 {
1870   mImpl->mOutlineSetByString = setByString;
1871 }
1872
1873 bool Controller::IsFontStyleSetByString()
1874 {
1875   return mImpl->mFontStyleSetByString;
1876 }
1877
1878 void Controller::FontStyleSetByString( bool setByString )
1879 {
1880   mImpl->mFontStyleSetByString = setByString;
1881 }
1882
1883 // public : Queries & retrieves.
1884
1885 Layout::Engine& Controller::GetLayoutEngine()
1886 {
1887   return mImpl->mLayoutEngine;
1888 }
1889
1890 View& Controller::GetView()
1891 {
1892   return mImpl->mView;
1893 }
1894
1895 Vector3 Controller::GetNaturalSize()
1896 {
1897   DALI_LOG_INFO( gLogFilter, Debug::Verbose, "-->Controller::GetNaturalSize\n" );
1898   Vector3 naturalSize;
1899
1900   // Make sure the model is up-to-date before layouting
1901   ProcessModifyEvents();
1902
1903   if( mImpl->mRecalculateNaturalSize )
1904   {
1905     // Operations that can be done only once until the text changes.
1906     const OperationsMask onlyOnceOperations = static_cast<OperationsMask>( CONVERT_TO_UTF32  |
1907                                                                            GET_SCRIPTS       |
1908                                                                            VALIDATE_FONTS    |
1909                                                                            GET_LINE_BREAKS   |
1910                                                                            GET_WORD_BREAKS   |
1911                                                                            BIDI_INFO         |
1912                                                                            SHAPE_TEXT        |
1913                                                                            GET_GLYPH_METRICS );
1914
1915     // Set the update info to relayout the whole text.
1916     mImpl->mTextUpdateInfo.mParagraphCharacterIndex = 0u;
1917     mImpl->mTextUpdateInfo.mRequestedNumberOfCharacters = mImpl->mModel->mLogicalModel->mText.Count();
1918
1919     // Make sure the model is up-to-date before layouting
1920     mImpl->UpdateModel( onlyOnceOperations );
1921
1922     // Layout the text for the new width.
1923     mImpl->mOperationsPending = static_cast<OperationsMask>( mImpl->mOperationsPending | LAYOUT | REORDER );
1924
1925     // Store the actual control's size to restore later.
1926     const Size actualControlSize = mImpl->mModel->mVisualModel->mControlSize;
1927
1928     DoRelayout( Size( MAX_FLOAT, MAX_FLOAT ),
1929                 static_cast<OperationsMask>( onlyOnceOperations |
1930                                              LAYOUT | REORDER ),
1931                 naturalSize.GetVectorXY() );
1932
1933     // Do not do again the only once operations.
1934     mImpl->mOperationsPending = static_cast<OperationsMask>( mImpl->mOperationsPending & ~onlyOnceOperations );
1935
1936     // Do the size related operations again.
1937     const OperationsMask sizeOperations =  static_cast<OperationsMask>( LAYOUT |
1938                                                                         ALIGN  |
1939                                                                         REORDER );
1940     mImpl->mOperationsPending = static_cast<OperationsMask>( mImpl->mOperationsPending | sizeOperations );
1941
1942     // Stores the natural size to avoid recalculate it again
1943     // unless the text/style changes.
1944     mImpl->mModel->mVisualModel->SetNaturalSize( naturalSize.GetVectorXY() );
1945
1946     mImpl->mRecalculateNaturalSize = false;
1947
1948     // Clear the update info. This info will be set the next time the text is updated.
1949     mImpl->mTextUpdateInfo.Clear();
1950     mImpl->mTextUpdateInfo.mClearAll = true;
1951
1952     // Restore the actual control's size.
1953     mImpl->mModel->mVisualModel->mControlSize = actualControlSize;
1954
1955     DALI_LOG_INFO( gLogFilter, Debug::Verbose, "<--Controller::GetNaturalSize calculated %f,%f,%f\n", naturalSize.x, naturalSize.y, naturalSize.z );
1956   }
1957   else
1958   {
1959     naturalSize = mImpl->mModel->mVisualModel->GetNaturalSize();
1960
1961     DALI_LOG_INFO( gLogFilter, Debug::Verbose, "<--Controller::GetNaturalSize cached %f,%f,%f\n", naturalSize.x, naturalSize.y, naturalSize.z );
1962   }
1963
1964   naturalSize.x = ConvertToEven( naturalSize.x );
1965   naturalSize.y = ConvertToEven( naturalSize.y );
1966
1967   return naturalSize;
1968 }
1969
1970 float Controller::GetHeightForWidth( float width )
1971 {
1972   DALI_LOG_INFO( gLogFilter, Debug::Verbose, "-->Controller::GetHeightForWidth %p width %f\n", this, width );
1973   // Make sure the model is up-to-date before layouting
1974   ProcessModifyEvents();
1975
1976   Size layoutSize;
1977   if( fabsf( width - mImpl->mModel->mVisualModel->mControlSize.width ) > Math::MACHINE_EPSILON_1000 ||
1978                                                          mImpl->mTextUpdateInfo.mFullRelayoutNeeded ||
1979                                                          mImpl->mTextUpdateInfo.mClearAll            )
1980   {
1981     // Operations that can be done only once until the text changes.
1982     const OperationsMask onlyOnceOperations = static_cast<OperationsMask>( CONVERT_TO_UTF32  |
1983                                                                            GET_SCRIPTS       |
1984                                                                            VALIDATE_FONTS    |
1985                                                                            GET_LINE_BREAKS   |
1986                                                                            GET_WORD_BREAKS   |
1987                                                                            BIDI_INFO         |
1988                                                                            SHAPE_TEXT        |
1989                                                                            GET_GLYPH_METRICS );
1990
1991     // Set the update info to relayout the whole text.
1992     mImpl->mTextUpdateInfo.mParagraphCharacterIndex = 0u;
1993     mImpl->mTextUpdateInfo.mRequestedNumberOfCharacters = mImpl->mModel->mLogicalModel->mText.Count();
1994
1995     // Make sure the model is up-to-date before layouting
1996     mImpl->UpdateModel( onlyOnceOperations );
1997
1998
1999     // Layout the text for the new width.
2000     mImpl->mOperationsPending = static_cast<OperationsMask>( mImpl->mOperationsPending | LAYOUT );
2001
2002     // Store the actual control's width.
2003     const float actualControlWidth = mImpl->mModel->mVisualModel->mControlSize.width;
2004
2005     DoRelayout( Size( width, MAX_FLOAT ),
2006                 static_cast<OperationsMask>( onlyOnceOperations |
2007                                              LAYOUT ),
2008                 layoutSize );
2009
2010     // Do not do again the only once operations.
2011     mImpl->mOperationsPending = static_cast<OperationsMask>( mImpl->mOperationsPending & ~onlyOnceOperations );
2012
2013     // Do the size related operations again.
2014     const OperationsMask sizeOperations =  static_cast<OperationsMask>( LAYOUT |
2015                                                                         ALIGN  |
2016                                                                         REORDER );
2017
2018     mImpl->mOperationsPending = static_cast<OperationsMask>( mImpl->mOperationsPending | sizeOperations );
2019
2020     // Clear the update info. This info will be set the next time the text is updated.
2021     mImpl->mTextUpdateInfo.Clear();
2022     mImpl->mTextUpdateInfo.mClearAll = true;
2023
2024     // Restore the actual control's width.
2025     mImpl->mModel->mVisualModel->mControlSize.width = actualControlWidth;
2026
2027     DALI_LOG_INFO( gLogFilter, Debug::Verbose, "<--Controller::GetHeightForWidth calculated %f\n", layoutSize.height );
2028   }
2029   else
2030   {
2031     layoutSize = mImpl->mModel->mVisualModel->GetLayoutSize();
2032     DALI_LOG_INFO( gLogFilter, Debug::Verbose, "<--Controller::GetHeightForWidth cached %f\n", layoutSize.height );
2033   }
2034
2035   return layoutSize.height;
2036 }
2037
2038 int Controller::GetLineCount( float width )
2039 {
2040   GetHeightForWidth( width );
2041   int numberofLines = mImpl->mModel->GetNumberOfLines();
2042   return numberofLines;
2043 }
2044
2045 const ModelInterface* const Controller::GetTextModel() const
2046 {
2047   return mImpl->mModel.Get();
2048 }
2049
2050 float Controller::GetScrollAmountByUserInput()
2051 {
2052   float scrollAmount = 0.0f;
2053
2054   if (NULL != mImpl->mEventData && mImpl->mEventData->mCheckScrollAmount)
2055   {
2056     scrollAmount = mImpl->mModel->mScrollPosition.y -  mImpl->mModel->mScrollPositionLast.y;
2057     mImpl->mEventData->mCheckScrollAmount = false;
2058   }
2059   return scrollAmount;
2060 }
2061
2062 bool Controller::GetTextScrollInfo( float& scrollPosition, float& controlHeight, float& layoutHeight )
2063 {
2064   const Vector2& layout = mImpl->mModel->mVisualModel->GetLayoutSize();
2065   bool isScrolled;
2066
2067   controlHeight = mImpl->mModel->mVisualModel->mControlSize.height;
2068   layoutHeight = layout.height;
2069   scrollPosition = mImpl->mModel->mScrollPosition.y;
2070   isScrolled = !Equals( mImpl->mModel->mScrollPosition.y, mImpl->mModel->mScrollPositionLast.y, Math::MACHINE_EPSILON_1 );
2071   return isScrolled;
2072 }
2073
2074 void Controller::SetHiddenInputOption(const Property::Map& options )
2075 {
2076   if( NULL == mImpl->mHiddenInput )
2077   {
2078     mImpl->mHiddenInput = new HiddenText( this );
2079   }
2080   mImpl->mHiddenInput->SetProperties(options);
2081 }
2082
2083 void Controller::GetHiddenInputOption(Property::Map& options )
2084 {
2085   if( NULL != mImpl->mHiddenInput )
2086   {
2087     mImpl->mHiddenInput->GetProperties(options);
2088   }
2089 }
2090
2091 void Controller::SetPlaceholderProperty( const Property::Map& map )
2092 {
2093   const Property::Map::SizeType count = map.Count();
2094
2095   for( Property::Map::SizeType position = 0; position < count; ++position )
2096   {
2097     KeyValuePair keyValue = map.GetKeyValue( position );
2098     Property::Key& key = keyValue.first;
2099     Property::Value& value = keyValue.second;
2100
2101     if( key == Toolkit::Text::PlaceHolder::Property::TEXT  || key == PLACEHOLDER_TEXT )
2102     {
2103       std::string text = "";
2104       value.Get( text );
2105       SetPlaceholderText( Controller::PLACEHOLDER_TYPE_INACTIVE, text );
2106     }
2107     else if( key == Toolkit::Text::PlaceHolder::Property::TEXT_FOCUSED || key == PLACEHOLDER_TEXT_FOCUSED )
2108     {
2109       std::string text = "";
2110       value.Get( text );
2111       SetPlaceholderText( Controller::PLACEHOLDER_TYPE_ACTIVE, text );
2112     }
2113     else if( key == Toolkit::Text::PlaceHolder::Property::COLOR || key == PLACEHOLDER_COLOR )
2114     {
2115       Vector4 textColor;
2116       value.Get( textColor );
2117       if( GetPlaceholderTextColor() != textColor )
2118       {
2119         SetPlaceholderTextColor( textColor );
2120       }
2121     }
2122     else if( key == Toolkit::Text::PlaceHolder::Property::FONT_FAMILY || key == PLACEHOLDER_FONT_FAMILY )
2123     {
2124       std::string fontFamily = "";
2125       value.Get( fontFamily );
2126       SetPlaceholderFontFamily( fontFamily );
2127     }
2128     else if( key == Toolkit::Text::PlaceHolder::Property::FONT_STYLE || key == PLACEHOLDER_FONT_STYLE )
2129     {
2130       SetFontStyleProperty( this, value, Text::FontStyle::PLACEHOLDER );
2131     }
2132     else if( key == Toolkit::Text::PlaceHolder::Property::POINT_SIZE || key == PLACEHOLDER_POINT_SIZE )
2133     {
2134       float pointSize;
2135       value.Get( pointSize );
2136       if( !Equals( GetPlaceholderTextFontSize( Text::Controller::POINT_SIZE ), pointSize ) )
2137       {
2138         SetPlaceholderTextFontSize( pointSize, Text::Controller::POINT_SIZE );
2139       }
2140     }
2141     else if( key == Toolkit::Text::PlaceHolder::Property::PIXEL_SIZE || key == PLACEHOLDER_PIXEL_SIZE )
2142     {
2143       float pixelSize;
2144       value.Get( pixelSize );
2145       if( !Equals( GetPlaceholderTextFontSize( Text::Controller::PIXEL_SIZE ), pixelSize ) )
2146       {
2147         SetPlaceholderTextFontSize( pixelSize, Text::Controller::PIXEL_SIZE );
2148       }
2149     }
2150     else if( key == Toolkit::Text::PlaceHolder::Property::ELLIPSIS || key == PLACEHOLDER_ELLIPSIS )
2151     {
2152       bool ellipsis;
2153       value.Get( ellipsis );
2154       SetPlaceholderTextElideEnabled( ellipsis );
2155     }
2156   }
2157 }
2158
2159 void Controller::GetPlaceholderProperty( Property::Map& map )
2160 {
2161   if( NULL != mImpl->mEventData )
2162   {
2163     if( !mImpl->mEventData->mPlaceholderTextActive.empty() )
2164     {
2165       map[ Text::PlaceHolder::Property::TEXT_FOCUSED ] = mImpl->mEventData->mPlaceholderTextActive;
2166     }
2167     if( !mImpl->mEventData->mPlaceholderTextInactive.empty() )
2168     {
2169       map[ Text::PlaceHolder::Property::TEXT ] = mImpl->mEventData->mPlaceholderTextInactive;
2170     }
2171
2172     map[ Text::PlaceHolder::Property::COLOR ] = mImpl->mEventData->mPlaceholderTextColor;
2173     map[ Text::PlaceHolder::Property::FONT_FAMILY ] = GetPlaceholderFontFamily();
2174
2175     Property::Value fontStyleMapGet;
2176     GetFontStyleProperty( this, fontStyleMapGet, Text::FontStyle::PLACEHOLDER );
2177     map[ Text::PlaceHolder::Property::FONT_STYLE ] = fontStyleMapGet;
2178
2179     // Choose font size : POINT_SIZE or PIXEL_SIZE
2180     if( !mImpl->mEventData->mIsPlaceholderPixelSize )
2181     {
2182       map[ Text::PlaceHolder::Property::POINT_SIZE ] = GetPlaceholderTextFontSize( Text::Controller::POINT_SIZE );
2183     }
2184     else
2185     {
2186       map[ Text::PlaceHolder::Property::PIXEL_SIZE ] = GetPlaceholderTextFontSize( Text::Controller::PIXEL_SIZE );
2187     }
2188
2189     if( mImpl->mEventData->mPlaceholderEllipsisFlag )
2190     {
2191       map[ Text::PlaceHolder::Property::ELLIPSIS ] = IsPlaceholderTextElideEnabled();
2192     }
2193   }
2194 }
2195
2196 Toolkit::DevelText::TextDirection::Type Controller::GetTextDirection()
2197 {
2198   // Make sure the model is up-to-date before layouting
2199   ProcessModifyEvents();
2200
2201   if ( mImpl->mUpdateTextDirection )
2202   {
2203     // Operations that can be done only once until the text changes.
2204     const OperationsMask onlyOnceOperations = static_cast<OperationsMask>( CONVERT_TO_UTF32  |
2205                                                                            GET_SCRIPTS       |
2206                                                                            VALIDATE_FONTS    |
2207                                                                            GET_LINE_BREAKS   |
2208                                                                            GET_WORD_BREAKS   |
2209                                                                            BIDI_INFO         |
2210                                                                            SHAPE_TEXT        |
2211                                                                            GET_GLYPH_METRICS );
2212
2213     // Set the update info to relayout the whole text.
2214     mImpl->mTextUpdateInfo.mParagraphCharacterIndex = 0u;
2215     mImpl->mTextUpdateInfo.mRequestedNumberOfCharacters = mImpl->mModel->mLogicalModel->mText.Count();
2216
2217     // Make sure the model is up-to-date before layouting
2218     mImpl->UpdateModel( onlyOnceOperations );
2219
2220     Vector3 naturalSize;
2221     DoRelayout( Size( MAX_FLOAT, MAX_FLOAT ),
2222                 static_cast<OperationsMask>( onlyOnceOperations |
2223                                              LAYOUT | REORDER | UPDATE_DIRECTION ),
2224                 naturalSize.GetVectorXY() );
2225
2226     // Do not do again the only once operations.
2227     mImpl->mOperationsPending = static_cast<OperationsMask>( mImpl->mOperationsPending & ~onlyOnceOperations );
2228
2229     // Clear the update info. This info will be set the next time the text is updated.
2230     mImpl->mTextUpdateInfo.Clear();
2231
2232     mImpl->mUpdateTextDirection = false;
2233   }
2234
2235   return mImpl->mIsTextDirectionRTL ? Toolkit::DevelText::TextDirection::RIGHT_TO_LEFT : Toolkit::DevelText::TextDirection::LEFT_TO_RIGHT;
2236 }
2237
2238 Toolkit::DevelText::VerticalLineAlignment::Type Controller::GetVerticalLineAlignment() const
2239 {
2240   return mImpl->mModel->GetVerticalLineAlignment();
2241 }
2242
2243 void Controller::SetVerticalLineAlignment( Toolkit::DevelText::VerticalLineAlignment::Type alignment )
2244 {
2245   mImpl->mModel->mVerticalLineAlignment = alignment;
2246 }
2247
2248 // public : Relayout.
2249
2250 Controller::UpdateTextType Controller::Relayout( const Size& size, Dali::LayoutDirection::Type layoutDirection )
2251 {
2252   DALI_LOG_INFO( gLogFilter, Debug::Verbose, "-->Controller::Relayout %p size %f,%f, autoScroll[%s]\n", this, size.width, size.height, mImpl->mIsAutoScrollEnabled ?"true":"false"  );
2253
2254   UpdateTextType updateTextType = NONE_UPDATED;
2255
2256   if( ( size.width < Math::MACHINE_EPSILON_1000 ) || ( size.height < Math::MACHINE_EPSILON_1000 ) )
2257   {
2258     if( 0u != mImpl->mModel->mVisualModel->mGlyphPositions.Count() )
2259     {
2260       mImpl->mModel->mVisualModel->mGlyphPositions.Clear();
2261       updateTextType = MODEL_UPDATED;
2262     }
2263
2264     // Clear the update info. This info will be set the next time the text is updated.
2265     mImpl->mTextUpdateInfo.Clear();
2266
2267     // Not worth to relayout if width or height is equal to zero.
2268     DALI_LOG_INFO( gLogFilter, Debug::Verbose, "<--Controller::Relayout (skipped)\n" );
2269
2270     return updateTextType;
2271   }
2272
2273   // Whether a new size has been set.
2274   const bool newSize = ( size != mImpl->mModel->mVisualModel->mControlSize );
2275
2276   if( newSize )
2277   {
2278     DALI_LOG_INFO( gLogFilter, Debug::Verbose, "new size (previous size %f,%f)\n", mImpl->mModel->mVisualModel->mControlSize.width, mImpl->mModel->mVisualModel->mControlSize.height );
2279
2280     if( ( 0 == mImpl->mTextUpdateInfo.mNumberOfCharactersToAdd ) &&
2281         ( 0 == mImpl->mTextUpdateInfo.mPreviousNumberOfCharacters ) &&
2282         ( ( mImpl->mModel->mVisualModel->mControlSize.width < Math::MACHINE_EPSILON_1000 ) || ( mImpl->mModel->mVisualModel->mControlSize.height < Math::MACHINE_EPSILON_1000 ) ) )
2283     {
2284       mImpl->mTextUpdateInfo.mNumberOfCharactersToAdd = mImpl->mModel->mLogicalModel->mText.Count();
2285     }
2286
2287     // Layout operations that need to be done if the size changes.
2288     mImpl->mOperationsPending = static_cast<OperationsMask>( mImpl->mOperationsPending |
2289                                                              LAYOUT                    |
2290                                                              ALIGN                     |
2291                                                              UPDATE_LAYOUT_SIZE        |
2292                                                              REORDER );
2293     // Set the update info to relayout the whole text.
2294     mImpl->mTextUpdateInfo.mFullRelayoutNeeded = true;
2295     mImpl->mTextUpdateInfo.mCharacterIndex = 0u;
2296
2297     // Store the size used to layout the text.
2298     mImpl->mModel->mVisualModel->mControlSize = size;
2299   }
2300
2301   // Whether there are modify events.
2302   if( 0u != mImpl->mModifyEvents.Count() )
2303   {
2304     // Style operations that need to be done if the text is modified.
2305     mImpl->mOperationsPending = static_cast<OperationsMask>( mImpl->mOperationsPending |
2306                                                              COLOR );
2307   }
2308
2309   // Set the update info to elide the text.
2310   if( mImpl->mModel->mElideEnabled ||
2311       ( ( NULL != mImpl->mEventData ) && mImpl->mEventData->mIsPlaceholderElideEnabled ) )
2312   {
2313     // Update Text layout for applying elided
2314     mImpl->mOperationsPending = static_cast<OperationsMask>( mImpl->mOperationsPending |
2315                                                              ALIGN                     |
2316                                                              LAYOUT                    |
2317                                                              UPDATE_LAYOUT_SIZE        |
2318                                                              REORDER );
2319     mImpl->mTextUpdateInfo.mFullRelayoutNeeded = true;
2320     mImpl->mTextUpdateInfo.mCharacterIndex = 0u;
2321   }
2322
2323   if( mImpl->mModel->mMatchSystemLanguageDirection  && mImpl->mLayoutDirection != layoutDirection )
2324   {
2325     // Clear the update info. This info will be set the next time the text is updated.
2326     mImpl->mTextUpdateInfo.mClearAll = true;
2327     // Apply modifications to the model
2328     // Shape the text again is needed because characters like '()[]{}' have to be mirrored and the glyphs generated again.
2329     mImpl->mOperationsPending = static_cast<OperationsMask>( mImpl->mOperationsPending |
2330                                                              GET_GLYPH_METRICS         |
2331                                                              SHAPE_TEXT                |
2332                                                              UPDATE_DIRECTION          |
2333                                                              LAYOUT                    |
2334                                                              BIDI_INFO                 |
2335                                                              REORDER );
2336     mImpl->mLayoutDirection = layoutDirection;
2337   }
2338
2339   // Make sure the model is up-to-date before layouting.
2340   ProcessModifyEvents();
2341   bool updated = mImpl->UpdateModel( mImpl->mOperationsPending );
2342
2343   // Layout the text.
2344   Size layoutSize;
2345   updated = DoRelayout( size,
2346                         mImpl->mOperationsPending,
2347                         layoutSize ) || updated;
2348
2349
2350   if( updated )
2351   {
2352     updateTextType = MODEL_UPDATED;
2353   }
2354
2355   // Do not re-do any operation until something changes.
2356   mImpl->mOperationsPending = NO_OPERATION;
2357   mImpl->mModel->mScrollPositionLast = mImpl->mModel->mScrollPosition;
2358
2359   // Whether the text control is editable
2360   const bool isEditable = NULL != mImpl->mEventData;
2361
2362   // Keep the current offset as it will be used to update the decorator's positions (if the size changes).
2363   Vector2 offset;
2364   if( newSize && isEditable )
2365   {
2366     offset = mImpl->mModel->mScrollPosition;
2367   }
2368
2369   if( !isEditable || !IsMultiLineEnabled() )
2370   {
2371     // After doing the text layout, the vertical offset to place the actor in the desired position can be calculated.
2372     CalculateVerticalOffset( size );
2373   }
2374
2375   if( isEditable )
2376   {
2377     if( newSize )
2378     {
2379       // If there is a new size, the scroll position needs to be clamped.
2380       mImpl->ClampHorizontalScroll( layoutSize );
2381
2382       // Update the decorator's positions is needed if there is a new size.
2383       mImpl->mEventData->mDecorator->UpdatePositions( mImpl->mModel->mScrollPosition - offset );
2384     }
2385
2386     // Move the cursor, grab handle etc.
2387     if( mImpl->ProcessInputEvents() )
2388     {
2389       updateTextType = static_cast<UpdateTextType>( updateTextType | DECORATOR_UPDATED );
2390     }
2391   }
2392
2393   // Clear the update info. This info will be set the next time the text is updated.
2394   mImpl->mTextUpdateInfo.Clear();
2395   DALI_LOG_INFO( gLogFilter, Debug::Verbose, "<--Controller::Relayout\n" );
2396
2397   return updateTextType;
2398 }
2399
2400 void Controller::RequestRelayout()
2401 {
2402   mImpl->RequestRelayout();
2403 }
2404
2405 // public : Input style change signals.
2406
2407 bool Controller::IsInputStyleChangedSignalsQueueEmpty()
2408 {
2409   return ( NULL == mImpl->mEventData ) || ( 0u == mImpl->mEventData->mInputStyleChangedQueue.Count() );
2410 }
2411
2412 void Controller::ProcessInputStyleChangedSignals()
2413 {
2414   if( NULL == mImpl->mEventData )
2415   {
2416     // Nothing to do.
2417     return;
2418   }
2419
2420   for( Vector<InputStyle::Mask>::ConstIterator it = mImpl->mEventData->mInputStyleChangedQueue.Begin(),
2421          endIt = mImpl->mEventData->mInputStyleChangedQueue.End();
2422        it != endIt;
2423        ++it )
2424   {
2425     const InputStyle::Mask mask = *it;
2426
2427     if( NULL != mImpl->mEditableControlInterface )
2428     {
2429       // Emit the input style changed signal.
2430       mImpl->mEditableControlInterface->InputStyleChanged( mask );
2431     }
2432   }
2433
2434   mImpl->mEventData->mInputStyleChangedQueue.Clear();
2435 }
2436
2437 // public : Text-input Event Queuing.
2438
2439 void Controller::KeyboardFocusGainEvent()
2440 {
2441   DALI_ASSERT_DEBUG( mImpl->mEventData && "Unexpected KeyboardFocusGainEvent" );
2442
2443   if( NULL != mImpl->mEventData )
2444   {
2445     if( ( EventData::INACTIVE == mImpl->mEventData->mState ) ||
2446         ( EventData::INTERRUPTED == mImpl->mEventData->mState ) )
2447     {
2448       mImpl->ChangeState( EventData::EDITING );
2449       mImpl->mEventData->mUpdateCursorPosition = true; //If editing started without tap event, cursor update must be triggered.
2450       mImpl->mEventData->mUpdateInputStyle = true;
2451       mImpl->mEventData->mScrollAfterUpdatePosition = true;
2452     }
2453     mImpl->NotifyInputMethodContextMultiLineStatus();
2454     if( mImpl->IsShowingPlaceholderText() )
2455     {
2456       // Show alternative placeholder-text when editing
2457       ShowPlaceholderText();
2458     }
2459
2460     mImpl->RequestRelayout();
2461   }
2462 }
2463
2464 void Controller::KeyboardFocusLostEvent()
2465 {
2466   DALI_ASSERT_DEBUG( mImpl->mEventData && "Unexpected KeyboardFocusLostEvent" );
2467
2468   if( NULL != mImpl->mEventData )
2469   {
2470     if( EventData::INTERRUPTED != mImpl->mEventData->mState )
2471     {
2472       mImpl->ChangeState( EventData::INACTIVE );
2473
2474       if( !mImpl->IsShowingRealText() )
2475       {
2476         // Revert to regular placeholder-text when not editing
2477         ShowPlaceholderText();
2478       }
2479     }
2480   }
2481   mImpl->RequestRelayout();
2482 }
2483
2484 bool Controller::KeyEvent( const Dali::KeyEvent& keyEvent )
2485 {
2486   DALI_ASSERT_DEBUG( mImpl->mEventData && "Unexpected KeyEvent" );
2487
2488   bool textChanged = false;
2489   bool relayoutNeeded = false;
2490
2491   if( ( NULL != mImpl->mEventData ) &&
2492       ( keyEvent.state == KeyEvent::Down ) )
2493   {
2494     int keyCode = keyEvent.keyCode;
2495     const std::string& keyString = keyEvent.keyPressed;
2496     const std::string keyName = keyEvent.keyPressedName;
2497
2498     const bool isNullKey = ( 0 == keyCode ) && ( keyString.empty() );
2499
2500     // Pre-process to separate modifying events from non-modifying input events.
2501     if( isNullKey )
2502     {
2503       // In some platforms arrive key events with no key code.
2504       // Do nothing.
2505       return false;
2506     }
2507     else if( Dali::DALI_KEY_ESCAPE == keyCode || Dali::DALI_KEY_BACK == keyCode  || Dali::DALI_KEY_SEARCH == keyCode )
2508     {
2509       // Do nothing
2510       return false;
2511     }
2512     else if( ( Dali::DALI_KEY_CURSOR_LEFT  == keyCode ) ||
2513              ( Dali::DALI_KEY_CURSOR_RIGHT == keyCode ) ||
2514              ( Dali::DALI_KEY_CURSOR_UP    == keyCode ) ||
2515              ( Dali::DALI_KEY_CURSOR_DOWN  == keyCode ) )
2516     {
2517       // If don't have any text, do nothing.
2518       if( !mImpl->mTextUpdateInfo.mPreviousNumberOfCharacters )
2519       {
2520         return false;
2521       }
2522
2523       uint32_t cursorPosition = mImpl->mEventData->mPrimaryCursorPosition;
2524       uint32_t numberOfCharacters = mImpl->mTextUpdateInfo.mPreviousNumberOfCharacters;
2525       uint32_t cursorLine = mImpl->mModel->mVisualModel->GetLineOfCharacter( cursorPosition );
2526       uint32_t numberOfLines = mImpl->mModel->GetNumberOfLines();
2527
2528       // Logic to determine whether this text control will lose focus or not.
2529       if( ( Dali::DALI_KEY_CURSOR_LEFT == keyCode && 0 == cursorPosition && !keyEvent.IsShiftModifier() ) ||
2530           ( Dali::DALI_KEY_CURSOR_RIGHT == keyCode && numberOfCharacters == cursorPosition && !keyEvent.IsShiftModifier() ) ||
2531           ( Dali::DALI_KEY_CURSOR_DOWN == keyCode && cursorLine == numberOfLines -1 ) ||
2532           ( Dali::DALI_KEY_CURSOR_DOWN == keyCode && numberOfCharacters == cursorPosition && cursorLine -1 == numberOfLines -1 ) ||
2533           ( Dali::DALI_KEY_CURSOR_UP == keyCode && cursorLine == 0 ) ||
2534           ( Dali::DALI_KEY_CURSOR_UP == keyCode && numberOfCharacters == cursorPosition && cursorLine == 1 ) )
2535       {
2536         // Release the active highlight.
2537         if( mImpl->mEventData->mState == EventData::SELECTING )
2538         {
2539           mImpl->ChangeState( EventData::EDITING );
2540
2541           // Update selection position.
2542           mImpl->mEventData->mLeftSelectionPosition = mImpl->mEventData->mPrimaryCursorPosition;
2543           mImpl->mEventData->mRightSelectionPosition = mImpl->mEventData->mPrimaryCursorPosition;
2544           mImpl->mEventData->mUpdateCursorPosition = true;
2545           mImpl->RequestRelayout();
2546         }
2547         return false;
2548       }
2549
2550       mImpl->mEventData->mCheckScrollAmount = true;
2551       Event event( Event::CURSOR_KEY_EVENT );
2552       event.p1.mInt = keyCode;
2553       event.p2.mBool = keyEvent.IsShiftModifier();
2554       mImpl->mEventData->mEventQueue.push_back( event );
2555
2556       // Will request for relayout.
2557       relayoutNeeded = true;
2558     }
2559     else if ( Dali::DevelKey::DALI_KEY_CONTROL_LEFT == keyCode || Dali::DevelKey::DALI_KEY_CONTROL_RIGHT == keyCode )
2560     {
2561       // Left or Right Control key event is received before Ctrl-C/V/X key event is received
2562       // If not handle it here, any selected text will be deleted
2563
2564       // Do nothing
2565       return false;
2566     }
2567     else if ( keyEvent.IsCtrlModifier() )
2568     {
2569       bool consumed = false;
2570       if (keyName == KEY_C_NAME)
2571       {
2572         // Ctrl-C to copy the selected text
2573         TextPopupButtonTouched( Toolkit::TextSelectionPopup::COPY );
2574         consumed = true;
2575       }
2576       else if (keyName == KEY_V_NAME)
2577       {
2578         // Ctrl-V to paste the copied text
2579         TextPopupButtonTouched( Toolkit::TextSelectionPopup::PASTE );
2580         consumed = true;
2581       }
2582       else if (keyName == KEY_X_NAME)
2583       {
2584         // Ctrl-X to cut the selected text
2585         TextPopupButtonTouched( Toolkit::TextSelectionPopup::CUT );
2586         consumed = true;
2587       }
2588       return consumed;
2589     }
2590     else if( ( Dali::DALI_KEY_BACKSPACE == keyCode ) ||
2591              ( Dali::DevelKey::DALI_KEY_DELETE == keyCode ) )
2592     {
2593       textChanged = DeleteEvent( keyCode );
2594
2595       // Will request for relayout.
2596       relayoutNeeded = true;
2597     }
2598     else if( IsKey( keyEvent, Dali::DALI_KEY_POWER ) ||
2599              IsKey( keyEvent, Dali::DALI_KEY_MENU ) ||
2600              IsKey( keyEvent, Dali::DALI_KEY_HOME ) )
2601     {
2602       // Power key/Menu/Home key behaviour does not allow edit mode to resume.
2603       mImpl->ChangeState( EventData::INACTIVE );
2604
2605       // Will request for relayout.
2606       relayoutNeeded = true;
2607
2608       // This branch avoids calling the InsertText() method of the 'else' branch which can delete selected text.
2609     }
2610     else if( Dali::DALI_KEY_SHIFT_LEFT == keyCode )
2611     {
2612       // DALI_KEY_SHIFT_LEFT is the key code for the Left Shift. It's sent (by the InputMethodContext?) when the predictive text is enabled
2613       // and a character is typed after the type of a upper case latin character.
2614
2615       // Do nothing.
2616       return false;
2617     }
2618     else if( ( Dali::DALI_KEY_VOLUME_UP == keyCode ) || ( Dali::DALI_KEY_VOLUME_DOWN == keyCode ) )
2619     {
2620       // This branch avoids calling the InsertText() method of the 'else' branch which can delete selected text.
2621       // Do nothing.
2622       return false;
2623     }
2624     else
2625     {
2626       DALI_LOG_INFO( gLogFilter, Debug::Verbose, "Controller::KeyEvent %p keyString %s\n", this, keyString.c_str() );
2627
2628       // InputMethodContext is no longer handling key-events
2629       mImpl->ClearPreEditFlag();
2630
2631       InsertText( keyString, COMMIT );
2632       textChanged = true;
2633
2634       // Will request for relayout.
2635       relayoutNeeded = true;
2636     }
2637
2638     if ( ( mImpl->mEventData->mState != EventData::INTERRUPTED ) &&
2639          ( mImpl->mEventData->mState != EventData::INACTIVE ) &&
2640          ( !isNullKey ) &&
2641          ( Dali::DALI_KEY_SHIFT_LEFT != keyCode ) &&
2642          ( Dali::DALI_KEY_VOLUME_UP != keyCode ) &&
2643          ( Dali::DALI_KEY_VOLUME_DOWN != keyCode ) )
2644     {
2645       // Should not change the state if the key is the shift send by the InputMethodContext.
2646       // Otherwise, when the state is SELECTING the text controller can't send the right
2647       // surrounding info to the InputMethodContext.
2648       mImpl->ChangeState( EventData::EDITING );
2649
2650       // Will request for relayout.
2651       relayoutNeeded = true;
2652     }
2653
2654     if( relayoutNeeded )
2655     {
2656       mImpl->RequestRelayout();
2657     }
2658   }
2659
2660   if( textChanged &&
2661       ( NULL != mImpl->mEditableControlInterface ) )
2662   {
2663     // Do this last since it provides callbacks into application code
2664     mImpl->mEditableControlInterface->TextChanged();
2665   }
2666
2667   return true;
2668 }
2669
2670 void Controller::TapEvent( unsigned int tapCount, float x, float y )
2671 {
2672   DALI_ASSERT_DEBUG( mImpl->mEventData && "Unexpected TapEvent" );
2673
2674   if( NULL != mImpl->mEventData )
2675   {
2676     DALI_LOG_INFO( gLogFilter, Debug::Concise, "TapEvent state:%d \n", mImpl->mEventData->mState );
2677     EventData::State state( mImpl->mEventData->mState );
2678     bool relayoutNeeded( false );   // to avoid unnecessary relayouts when tapping an empty text-field
2679
2680     if( mImpl->IsClipboardVisible() )
2681     {
2682       if( EventData::INACTIVE == state || EventData::EDITING == state)
2683       {
2684         mImpl->ChangeState( EventData::EDITING_WITH_GRAB_HANDLE );
2685       }
2686       relayoutNeeded = true;
2687     }
2688     else if( 1u == tapCount )
2689     {
2690       if( EventData::EDITING_WITH_POPUP == state || EventData::EDITING_WITH_PASTE_POPUP == state )
2691       {
2692         mImpl->ChangeState( EventData::EDITING_WITH_GRAB_HANDLE );  // If Popup shown hide it here so can be shown again if required.
2693       }
2694
2695       if( mImpl->IsShowingRealText() && ( EventData::INACTIVE != state ) )
2696       {
2697         mImpl->ChangeState( EventData::EDITING_WITH_GRAB_HANDLE );
2698         relayoutNeeded = true;
2699       }
2700       else
2701       {
2702         if( mImpl->IsShowingPlaceholderText() && !mImpl->IsFocusedPlaceholderAvailable() )
2703         {
2704           // Hide placeholder text
2705           ResetText();
2706         }
2707
2708         if( EventData::INACTIVE == state )
2709         {
2710           mImpl->ChangeState( EventData::EDITING );
2711         }
2712         else if( !mImpl->IsClipboardEmpty() )
2713         {
2714           mImpl->ChangeState( EventData::EDITING_WITH_POPUP );
2715         }
2716         relayoutNeeded = true;
2717       }
2718     }
2719     else if( 2u == tapCount )
2720     {
2721       if( mImpl->mEventData->mSelectionEnabled &&
2722           mImpl->IsShowingRealText() )
2723       {
2724         relayoutNeeded = true;
2725         mImpl->mEventData->mIsLeftHandleSelected = true;
2726         mImpl->mEventData->mIsRightHandleSelected = true;
2727       }
2728     }
2729
2730     // Handles & cursors must be repositioned after Relayout() i.e. after the Model has been updated
2731     if( relayoutNeeded )
2732     {
2733       Event event( Event::TAP_EVENT );
2734       event.p1.mUint = tapCount;
2735       event.p2.mFloat = x;
2736       event.p3.mFloat = y;
2737       mImpl->mEventData->mEventQueue.push_back( event );
2738
2739       mImpl->RequestRelayout();
2740     }
2741   }
2742
2743   // Reset keyboard as tap event has occurred.
2744   mImpl->ResetInputMethodContext();
2745 }
2746
2747 void Controller::PanEvent( Gesture::State state, const Vector2& displacement )
2748 {
2749   DALI_ASSERT_DEBUG( mImpl->mEventData && "Unexpected PanEvent" );
2750
2751   if( NULL != mImpl->mEventData )
2752   {
2753     Event event( Event::PAN_EVENT );
2754     event.p1.mInt = state;
2755     event.p2.mFloat = displacement.x;
2756     event.p3.mFloat = displacement.y;
2757     mImpl->mEventData->mEventQueue.push_back( event );
2758
2759     mImpl->RequestRelayout();
2760   }
2761 }
2762
2763 void Controller::LongPressEvent( Gesture::State state, float x, float y  )
2764 {
2765   DALI_ASSERT_DEBUG( mImpl->mEventData && "Unexpected LongPressEvent" );
2766
2767   if( ( state == Gesture::Started ) &&
2768       ( NULL != mImpl->mEventData ) )
2769   {
2770     // The 1st long-press on inactive text-field is treated as tap
2771     if( EventData::INACTIVE == mImpl->mEventData->mState )
2772     {
2773       mImpl->ChangeState( EventData::EDITING );
2774
2775       Event event( Event::TAP_EVENT );
2776       event.p1.mUint = 1;
2777       event.p2.mFloat = x;
2778       event.p3.mFloat = y;
2779       mImpl->mEventData->mEventQueue.push_back( event );
2780
2781       mImpl->RequestRelayout();
2782     }
2783     else if( !mImpl->IsShowingRealText() )
2784     {
2785       Event event( Event::LONG_PRESS_EVENT );
2786       event.p1.mInt = state;
2787       event.p2.mFloat = x;
2788       event.p3.mFloat = y;
2789       mImpl->mEventData->mEventQueue.push_back( event );
2790       mImpl->RequestRelayout();
2791     }
2792     else if( !mImpl->IsClipboardVisible() )
2793     {
2794       // Reset the InputMethodContext to commit the pre-edit before selecting the text.
2795       mImpl->ResetInputMethodContext();
2796
2797       Event event( Event::LONG_PRESS_EVENT );
2798       event.p1.mInt = state;
2799       event.p2.mFloat = x;
2800       event.p3.mFloat = y;
2801       mImpl->mEventData->mEventQueue.push_back( event );
2802       mImpl->RequestRelayout();
2803
2804       mImpl->mEventData->mIsLeftHandleSelected = true;
2805       mImpl->mEventData->mIsRightHandleSelected = true;
2806     }
2807   }
2808 }
2809
2810 InputMethodContext::CallbackData Controller::OnInputMethodContextEvent( InputMethodContext& inputMethodContext, const InputMethodContext::EventData& inputMethodContextEvent )
2811 {
2812   // Whether the text needs to be relaid-out.
2813   bool requestRelayout = false;
2814
2815   // Whether to retrieve the text and cursor position to be sent to the InputMethodContext.
2816   bool retrieveText = false;
2817   bool retrieveCursor = false;
2818
2819   switch( inputMethodContextEvent.eventName )
2820   {
2821     case InputMethodContext::COMMIT:
2822     {
2823       InsertText( inputMethodContextEvent.predictiveString, Text::Controller::COMMIT );
2824       requestRelayout = true;
2825       retrieveCursor = true;
2826       break;
2827     }
2828     case InputMethodContext::PRE_EDIT:
2829     {
2830       InsertText( inputMethodContextEvent.predictiveString, Text::Controller::PRE_EDIT );
2831       requestRelayout = true;
2832       retrieveCursor = true;
2833       break;
2834     }
2835     case InputMethodContext::DELETE_SURROUNDING:
2836     {
2837       const bool textDeleted = RemoveText( inputMethodContextEvent.cursorOffset,
2838                                            inputMethodContextEvent.numberOfChars,
2839                                            DONT_UPDATE_INPUT_STYLE );
2840
2841       if( textDeleted )
2842       {
2843         if( ( 0u != mImpl->mModel->mLogicalModel->mText.Count() ) ||
2844             !mImpl->IsPlaceholderAvailable() )
2845         {
2846           mImpl->QueueModifyEvent( ModifyEvent::TEXT_DELETED );
2847         }
2848         else
2849         {
2850           ShowPlaceholderText();
2851         }
2852         mImpl->mEventData->mUpdateCursorPosition = true;
2853         mImpl->mEventData->mScrollAfterDelete = true;
2854
2855         requestRelayout = true;
2856       }
2857       break;
2858     }
2859     case InputMethodContext::GET_SURROUNDING:
2860     {
2861       retrieveText = true;
2862       retrieveCursor = true;
2863       break;
2864     }
2865     case InputMethodContext::PRIVATE_COMMAND:
2866     {
2867       // PRIVATECOMMAND event is just for getting the private command message
2868       retrieveText = true;
2869       retrieveCursor = true;
2870       break;
2871     }
2872     case InputMethodContext::VOID:
2873     {
2874       // do nothing
2875       break;
2876     }
2877   } // end switch
2878
2879   if( requestRelayout )
2880   {
2881     mImpl->mOperationsPending = ALL_OPERATIONS;
2882     mImpl->RequestRelayout();
2883   }
2884
2885   std::string text;
2886   CharacterIndex cursorPosition = 0u;
2887   Length numberOfWhiteSpaces = 0u;
2888
2889   if( retrieveCursor )
2890   {
2891     numberOfWhiteSpaces = mImpl->GetNumberOfWhiteSpaces( 0u );
2892
2893     cursorPosition = mImpl->GetLogicalCursorPosition();
2894
2895     if( cursorPosition < numberOfWhiteSpaces )
2896     {
2897       cursorPosition = 0u;
2898     }
2899     else
2900     {
2901       cursorPosition -= numberOfWhiteSpaces;
2902     }
2903   }
2904
2905   if( retrieveText )
2906   {
2907     if( !mImpl->IsShowingPlaceholderText() )
2908     {
2909       // Retrieves the normal text string.
2910       mImpl->GetText( numberOfWhiteSpaces, text );
2911     }
2912     else
2913     {
2914       // When the current text is Placeholder Text, the surrounding text should be empty string.
2915       // It means DALi should send empty string ("") to IME.
2916       text = "";
2917     }
2918   }
2919
2920   InputMethodContext::CallbackData callbackData( ( retrieveText || retrieveCursor ), cursorPosition, text, false );
2921
2922   if( requestRelayout &&
2923       ( NULL != mImpl->mEditableControlInterface ) )
2924   {
2925     // Do this last since it provides callbacks into application code
2926     mImpl->mEditableControlInterface->TextChanged();
2927   }
2928
2929   return callbackData;
2930 }
2931
2932 void Controller::PasteClipboardItemEvent()
2933 {
2934   // Retrieve the clipboard contents first
2935   ClipboardEventNotifier notifier( ClipboardEventNotifier::Get() );
2936   std::string stringToPaste( notifier.GetContent() );
2937
2938   // Commit the current pre-edit text; the contents of the clipboard should be appended
2939   mImpl->ResetInputMethodContext();
2940
2941   // Temporary disable hiding clipboard
2942   mImpl->SetClipboardHideEnable( false );
2943
2944   // Paste
2945   PasteText( stringToPaste );
2946
2947   mImpl->SetClipboardHideEnable( true );
2948 }
2949
2950 // protected : Inherit from Text::Decorator::ControllerInterface.
2951
2952 void Controller::GetTargetSize( Vector2& targetSize )
2953 {
2954   targetSize = mImpl->mModel->mVisualModel->mControlSize;
2955 }
2956
2957 void Controller::AddDecoration( Actor& actor, bool needsClipping )
2958 {
2959   if( NULL != mImpl->mEditableControlInterface )
2960   {
2961     mImpl->mEditableControlInterface->AddDecoration( actor, needsClipping );
2962   }
2963 }
2964
2965 void Controller::DecorationEvent( HandleType handleType, HandleState state, float x, float y )
2966 {
2967   DALI_ASSERT_DEBUG( mImpl->mEventData && "Unexpected DecorationEvent" );
2968
2969   if( NULL != mImpl->mEventData )
2970   {
2971     switch( handleType )
2972     {
2973       case GRAB_HANDLE:
2974       {
2975         Event event( Event::GRAB_HANDLE_EVENT );
2976         event.p1.mUint  = state;
2977         event.p2.mFloat = x;
2978         event.p3.mFloat = y;
2979
2980         mImpl->mEventData->mEventQueue.push_back( event );
2981         break;
2982       }
2983       case LEFT_SELECTION_HANDLE:
2984       {
2985         Event event( Event::LEFT_SELECTION_HANDLE_EVENT );
2986         event.p1.mUint  = state;
2987         event.p2.mFloat = x;
2988         event.p3.mFloat = y;
2989
2990         mImpl->mEventData->mEventQueue.push_back( event );
2991         break;
2992       }
2993       case RIGHT_SELECTION_HANDLE:
2994       {
2995         Event event( Event::RIGHT_SELECTION_HANDLE_EVENT );
2996         event.p1.mUint  = state;
2997         event.p2.mFloat = x;
2998         event.p3.mFloat = y;
2999
3000         mImpl->mEventData->mEventQueue.push_back( event );
3001         break;
3002       }
3003       case LEFT_SELECTION_HANDLE_MARKER:
3004       case RIGHT_SELECTION_HANDLE_MARKER:
3005       {
3006         // Markers do not move the handles.
3007         break;
3008       }
3009       case HANDLE_TYPE_COUNT:
3010       {
3011         DALI_ASSERT_DEBUG( !"Controller::HandleEvent. Unexpected handle type" );
3012       }
3013     }
3014
3015     mImpl->RequestRelayout();
3016   }
3017 }
3018
3019 // protected : Inherit from TextSelectionPopup::TextPopupButtonCallbackInterface.
3020
3021 void Controller::TextPopupButtonTouched( Dali::Toolkit::TextSelectionPopup::Buttons button )
3022 {
3023   if( NULL == mImpl->mEventData )
3024   {
3025     return;
3026   }
3027
3028   switch( button )
3029   {
3030     case Toolkit::TextSelectionPopup::CUT:
3031     {
3032       mImpl->SendSelectionToClipboard( true ); // Synchronous call to modify text
3033       mImpl->mOperationsPending = ALL_OPERATIONS;
3034
3035       if( ( 0u != mImpl->mModel->mLogicalModel->mText.Count() ) ||
3036           !mImpl->IsPlaceholderAvailable() )
3037       {
3038         mImpl->QueueModifyEvent( ModifyEvent::TEXT_DELETED );
3039       }
3040       else
3041       {
3042         ShowPlaceholderText();
3043       }
3044
3045       mImpl->mEventData->mUpdateCursorPosition = true;
3046       mImpl->mEventData->mScrollAfterDelete = true;
3047
3048       mImpl->RequestRelayout();
3049
3050       if( NULL != mImpl->mEditableControlInterface )
3051       {
3052         mImpl->mEditableControlInterface->TextChanged();
3053       }
3054       break;
3055     }
3056     case Toolkit::TextSelectionPopup::COPY:
3057     {
3058       mImpl->SendSelectionToClipboard( false ); // Text not modified
3059
3060       mImpl->mEventData->mUpdateCursorPosition = true;
3061
3062       mImpl->RequestRelayout(); // Cursor, Handles, Selection Highlight, Popup
3063       break;
3064     }
3065     case Toolkit::TextSelectionPopup::PASTE:
3066     {
3067       mImpl->RequestGetTextFromClipboard(); // Request clipboard service to retrieve an item
3068       break;
3069     }
3070     case Toolkit::TextSelectionPopup::SELECT:
3071     {
3072       const Vector2& currentCursorPosition = mImpl->mEventData->mDecorator->GetPosition( PRIMARY_CURSOR );
3073
3074       if( mImpl->mEventData->mSelectionEnabled )
3075       {
3076         // Creates a SELECT event.
3077         SelectEvent( currentCursorPosition.x, currentCursorPosition.y, false );
3078       }
3079       break;
3080     }
3081     case Toolkit::TextSelectionPopup::SELECT_ALL:
3082     {
3083       // Creates a SELECT_ALL event
3084       SelectEvent( 0.f, 0.f, true );
3085       break;
3086     }
3087     case Toolkit::TextSelectionPopup::CLIPBOARD:
3088     {
3089       mImpl->ShowClipboard();
3090       break;
3091     }
3092     case Toolkit::TextSelectionPopup::NONE:
3093     {
3094       // Nothing to do.
3095       break;
3096     }
3097   }
3098 }
3099
3100 void Controller::DisplayTimeExpired()
3101 {
3102   mImpl->mEventData->mUpdateCursorPosition = true;
3103   // Apply modifications to the model
3104   mImpl->mOperationsPending = ALL_OPERATIONS;
3105
3106   mImpl->RequestRelayout();
3107 }
3108
3109 // private : Update.
3110
3111 void Controller::InsertText( const std::string& text, Controller::InsertType type )
3112 {
3113   bool removedPrevious = false;
3114   bool removedSelected = false;
3115   bool maxLengthReached = false;
3116
3117   DALI_ASSERT_DEBUG( NULL != mImpl->mEventData && "Unexpected InsertText" )
3118
3119   if( NULL == mImpl->mEventData )
3120   {
3121     return;
3122   }
3123
3124   DALI_LOG_INFO( gLogFilter, Debug::Verbose, "Controller::InsertText %p %s (%s) mPrimaryCursorPosition %d mPreEditFlag %d mPreEditStartPosition %d mPreEditLength %d\n",
3125                  this, text.c_str(), (COMMIT == type ? "COMMIT" : "PRE_EDIT"),
3126                  mImpl->mEventData->mPrimaryCursorPosition, mImpl->mEventData->mPreEditFlag, mImpl->mEventData->mPreEditStartPosition, mImpl->mEventData->mPreEditLength );
3127
3128   // TODO: At the moment the underline runs are only for pre-edit.
3129   mImpl->mModel->mVisualModel->mUnderlineRuns.Clear();
3130
3131   // Remove the previous InputMethodContext pre-edit.
3132   if( mImpl->mEventData->mPreEditFlag && ( 0u != mImpl->mEventData->mPreEditLength ) )
3133   {
3134     removedPrevious = RemoveText( -static_cast<int>( mImpl->mEventData->mPrimaryCursorPosition - mImpl->mEventData->mPreEditStartPosition ),
3135                                   mImpl->mEventData->mPreEditLength,
3136                                   DONT_UPDATE_INPUT_STYLE );
3137
3138     mImpl->mEventData->mPrimaryCursorPosition = mImpl->mEventData->mPreEditStartPosition;
3139     mImpl->mEventData->mPreEditLength = 0u;
3140   }
3141   else
3142   {
3143     // Remove the previous Selection.
3144     removedSelected = RemoveSelectedText();
3145
3146   }
3147
3148   Vector<Character> utf32Characters;
3149   Length characterCount = 0u;
3150
3151   if( !text.empty() )
3152   {
3153     //  Convert text into UTF-32
3154     utf32Characters.Resize( text.size() );
3155
3156     // This is a bit horrible but std::string returns a (signed) char*
3157     const uint8_t* utf8 = reinterpret_cast<const uint8_t*>( text.c_str() );
3158
3159     // Transform a text array encoded in utf8 into an array encoded in utf32.
3160     // It returns the actual number of characters.
3161     characterCount = Utf8ToUtf32( utf8, text.size(), utf32Characters.Begin() );
3162     utf32Characters.Resize( characterCount );
3163
3164     DALI_ASSERT_DEBUG( text.size() >= utf32Characters.Count() && "Invalid UTF32 conversion length" );
3165     DALI_LOG_INFO( gLogFilter, Debug::Verbose, "UTF8 size %d, UTF32 size %d\n", text.size(), utf32Characters.Count() );
3166   }
3167
3168   if( 0u != utf32Characters.Count() ) // Check if Utf8ToUtf32 conversion succeeded
3169   {
3170     // The placeholder text is no longer needed
3171     if( mImpl->IsShowingPlaceholderText() )
3172     {
3173       ResetText();
3174     }
3175
3176     mImpl->ChangeState( EventData::EDITING );
3177
3178     // Handle the InputMethodContext (predicitive text) state changes
3179     if( COMMIT == type )
3180     {
3181       // InputMethodContext is no longer handling key-events
3182       mImpl->ClearPreEditFlag();
3183     }
3184     else // PRE_EDIT
3185     {
3186       if( !mImpl->mEventData->mPreEditFlag )
3187       {
3188         DALI_LOG_INFO( gLogFilter, Debug::Verbose, "Entered PreEdit state\n" );
3189
3190         // Record the start of the pre-edit text
3191         mImpl->mEventData->mPreEditStartPosition = mImpl->mEventData->mPrimaryCursorPosition;
3192       }
3193
3194       mImpl->mEventData->mPreEditLength = utf32Characters.Count();
3195       mImpl->mEventData->mPreEditFlag = true;
3196
3197       DALI_LOG_INFO( gLogFilter, Debug::Verbose, "mPreEditStartPosition %d mPreEditLength %d\n", mImpl->mEventData->mPreEditStartPosition, mImpl->mEventData->mPreEditLength );
3198     }
3199
3200     const Length numberOfCharactersInModel = mImpl->mModel->mLogicalModel->mText.Count();
3201
3202     // Restrict new text to fit within Maximum characters setting.
3203     Length maxSizeOfNewText = std::min( ( mImpl->mMaximumNumberOfCharacters - numberOfCharactersInModel ), characterCount );
3204     maxLengthReached = ( characterCount > maxSizeOfNewText );
3205
3206     // The cursor position.
3207     CharacterIndex& cursorIndex = mImpl->mEventData->mPrimaryCursorPosition;
3208
3209     // Update the text's style.
3210
3211     // Updates the text style runs by adding characters.
3212     mImpl->mModel->mLogicalModel->UpdateTextStyleRuns( cursorIndex, maxSizeOfNewText );
3213
3214     // Get the character index from the cursor index.
3215     const CharacterIndex styleIndex = ( cursorIndex > 0u ) ? cursorIndex - 1u : 0u;
3216
3217     // Retrieve the text's style for the given index.
3218     InputStyle style;
3219     mImpl->RetrieveDefaultInputStyle( style );
3220     mImpl->mModel->mLogicalModel->RetrieveStyle( styleIndex, style );
3221
3222     // Whether to add a new text color run.
3223     const bool addColorRun = ( style.textColor != mImpl->mEventData->mInputStyle.textColor );
3224
3225     // Whether to add a new font run.
3226     const bool addFontNameRun = style.familyName != mImpl->mEventData->mInputStyle.familyName;
3227     const bool addFontWeightRun = style.weight != mImpl->mEventData->mInputStyle.weight;
3228     const bool addFontWidthRun = style.width != mImpl->mEventData->mInputStyle.width;
3229     const bool addFontSlantRun = style.slant != mImpl->mEventData->mInputStyle.slant;
3230     const bool addFontSizeRun = style.size != mImpl->mEventData->mInputStyle.size;
3231
3232     // Add style runs.
3233     if( addColorRun )
3234     {
3235       const VectorBase::SizeType numberOfRuns = mImpl->mModel->mLogicalModel->mColorRuns.Count();
3236       mImpl->mModel->mLogicalModel->mColorRuns.Resize( numberOfRuns + 1u );
3237
3238       ColorRun& colorRun = *( mImpl->mModel->mLogicalModel->mColorRuns.Begin() + numberOfRuns );
3239       colorRun.color = mImpl->mEventData->mInputStyle.textColor;
3240       colorRun.characterRun.characterIndex = cursorIndex;
3241       colorRun.characterRun.numberOfCharacters = maxSizeOfNewText;
3242     }
3243
3244     if( addFontNameRun   ||
3245         addFontWeightRun ||
3246         addFontWidthRun  ||
3247         addFontSlantRun  ||
3248         addFontSizeRun )
3249     {
3250       const VectorBase::SizeType numberOfRuns = mImpl->mModel->mLogicalModel->mFontDescriptionRuns.Count();
3251       mImpl->mModel->mLogicalModel->mFontDescriptionRuns.Resize( numberOfRuns + 1u );
3252
3253       FontDescriptionRun& fontDescriptionRun = *( mImpl->mModel->mLogicalModel->mFontDescriptionRuns.Begin() + numberOfRuns );
3254
3255       if( addFontNameRun )
3256       {
3257         fontDescriptionRun.familyLength = mImpl->mEventData->mInputStyle.familyName.size();
3258         fontDescriptionRun.familyName = new char[fontDescriptionRun.familyLength];
3259         memcpy( fontDescriptionRun.familyName, mImpl->mEventData->mInputStyle.familyName.c_str(), fontDescriptionRun.familyLength );
3260         fontDescriptionRun.familyDefined = true;
3261
3262         // The memory allocated for the font family name is freed when the font description is removed from the logical model.
3263       }
3264
3265       if( addFontWeightRun )
3266       {
3267         fontDescriptionRun.weight = mImpl->mEventData->mInputStyle.weight;
3268         fontDescriptionRun.weightDefined = true;
3269       }
3270
3271       if( addFontWidthRun )
3272       {
3273         fontDescriptionRun.width = mImpl->mEventData->mInputStyle.width;
3274         fontDescriptionRun.widthDefined = true;
3275       }
3276
3277       if( addFontSlantRun )
3278       {
3279         fontDescriptionRun.slant = mImpl->mEventData->mInputStyle.slant;
3280         fontDescriptionRun.slantDefined = true;
3281       }
3282
3283       if( addFontSizeRun )
3284       {
3285         fontDescriptionRun.size = static_cast<PointSize26Dot6>( mImpl->mEventData->mInputStyle.size * 64.f );
3286         fontDescriptionRun.sizeDefined = true;
3287       }
3288
3289       fontDescriptionRun.characterRun.characterIndex = cursorIndex;
3290       fontDescriptionRun.characterRun.numberOfCharacters = maxSizeOfNewText;
3291     }
3292
3293     // Insert at current cursor position.
3294     Vector<Character>& modifyText = mImpl->mModel->mLogicalModel->mText;
3295
3296     if( cursorIndex < numberOfCharactersInModel )
3297     {
3298       modifyText.Insert( modifyText.Begin() + cursorIndex, utf32Characters.Begin(), utf32Characters.Begin() + maxSizeOfNewText );
3299     }
3300     else
3301     {
3302       modifyText.Insert( modifyText.End(), utf32Characters.Begin(), utf32Characters.Begin() + maxSizeOfNewText );
3303     }
3304
3305     // Mark the first paragraph to be updated.
3306     if( Layout::Engine::SINGLE_LINE_BOX == mImpl->mLayoutEngine.GetLayout() )
3307     {
3308       mImpl->mTextUpdateInfo.mCharacterIndex = 0;
3309       mImpl->mTextUpdateInfo.mNumberOfCharactersToRemove = mImpl->mTextUpdateInfo.mPreviousNumberOfCharacters;
3310       mImpl->mTextUpdateInfo.mNumberOfCharactersToAdd = numberOfCharactersInModel + maxSizeOfNewText;
3311       mImpl->mTextUpdateInfo.mClearAll = true;
3312     }
3313     else
3314     {
3315       mImpl->mTextUpdateInfo.mCharacterIndex = std::min( cursorIndex, mImpl->mTextUpdateInfo.mCharacterIndex );
3316       mImpl->mTextUpdateInfo.mNumberOfCharactersToAdd += maxSizeOfNewText;
3317     }
3318
3319     // Update the cursor index.
3320     cursorIndex += maxSizeOfNewText;
3321
3322     DALI_LOG_INFO( gLogFilter, Debug::Verbose, "Inserted %d characters, new size %d new cursor %d\n", maxSizeOfNewText, mImpl->mModel->mLogicalModel->mText.Count(), mImpl->mEventData->mPrimaryCursorPosition );
3323   }
3324
3325   if( ( 0u == mImpl->mModel->mLogicalModel->mText.Count() ) &&
3326       mImpl->IsPlaceholderAvailable() )
3327   {
3328     // Show place-holder if empty after removing the pre-edit text
3329     ShowPlaceholderText();
3330     mImpl->mEventData->mUpdateCursorPosition = true;
3331     mImpl->ClearPreEditFlag();
3332   }
3333   else if( removedPrevious ||
3334            removedSelected ||
3335            ( 0 != utf32Characters.Count() ) )
3336   {
3337     // Queue an inserted event
3338     mImpl->QueueModifyEvent( ModifyEvent::TEXT_INSERTED );
3339
3340     mImpl->mEventData->mUpdateCursorPosition = true;
3341     if( removedSelected )
3342     {
3343       mImpl->mEventData->mScrollAfterDelete = true;
3344     }
3345     else
3346     {
3347       mImpl->mEventData->mScrollAfterUpdatePosition = true;
3348     }
3349   }
3350
3351   if( maxLengthReached )
3352   {
3353     DALI_LOG_INFO( gLogFilter, Debug::Verbose, "MaxLengthReached (%d)\n", mImpl->mModel->mLogicalModel->mText.Count() );
3354
3355     mImpl->ResetInputMethodContext();
3356
3357     if( NULL != mImpl->mEditableControlInterface )
3358     {
3359       // Do this last since it provides callbacks into application code
3360       mImpl->mEditableControlInterface->MaxLengthReached();
3361     }
3362   }
3363 }
3364
3365 void Controller::PasteText( const std::string& stringToPaste )
3366 {
3367   InsertText( stringToPaste, Text::Controller::COMMIT );
3368   mImpl->ChangeState( EventData::EDITING );
3369   mImpl->RequestRelayout();
3370
3371   if( NULL != mImpl->mEditableControlInterface )
3372   {
3373     // Do this last since it provides callbacks into application code
3374     mImpl->mEditableControlInterface->TextChanged();
3375   }
3376 }
3377
3378 bool Controller::RemoveText( int cursorOffset,
3379                              int numberOfCharacters,
3380                              UpdateInputStyleType type )
3381 {
3382   bool removed = false;
3383
3384   if( NULL == mImpl->mEventData )
3385   {
3386     return removed;
3387   }
3388
3389   DALI_LOG_INFO( gLogFilter, Debug::General, "Controller::RemoveText %p mText.Count() %d cursor %d cursorOffset %d numberOfCharacters %d\n",
3390                  this, mImpl->mModel->mLogicalModel->mText.Count(), mImpl->mEventData->mPrimaryCursorPosition, cursorOffset, numberOfCharacters );
3391
3392   if( !mImpl->IsShowingPlaceholderText() )
3393   {
3394     // Delete at current cursor position
3395     Vector<Character>& currentText = mImpl->mModel->mLogicalModel->mText;
3396     CharacterIndex& oldCursorIndex = mImpl->mEventData->mPrimaryCursorPosition;
3397
3398     CharacterIndex cursorIndex = 0;
3399
3400     // Validate the cursor position & number of characters
3401     if( ( static_cast< int >( mImpl->mEventData->mPrimaryCursorPosition ) + cursorOffset ) >= 0 )
3402     {
3403       cursorIndex = mImpl->mEventData->mPrimaryCursorPosition + cursorOffset;
3404     }
3405
3406     if( ( cursorIndex + numberOfCharacters ) > currentText.Count() )
3407     {
3408       numberOfCharacters = currentText.Count() - cursorIndex;
3409     }
3410
3411     if( mImpl->mEventData->mPreEditFlag || // If the preedit flag is enabled, it means two (or more) of them came together i.e. when two keys have been pressed at the same time.
3412         ( ( cursorIndex + numberOfCharacters ) <= mImpl->mTextUpdateInfo.mPreviousNumberOfCharacters ) )
3413     {
3414       // Mark the paragraphs to be updated.
3415       if( Layout::Engine::SINGLE_LINE_BOX == mImpl->mLayoutEngine.GetLayout() )
3416       {
3417         mImpl->mTextUpdateInfo.mCharacterIndex = 0;
3418         mImpl->mTextUpdateInfo.mNumberOfCharactersToRemove = mImpl->mTextUpdateInfo.mPreviousNumberOfCharacters;
3419         mImpl->mTextUpdateInfo.mNumberOfCharactersToAdd = mImpl->mTextUpdateInfo.mPreviousNumberOfCharacters - numberOfCharacters;
3420         mImpl->mTextUpdateInfo.mClearAll = true;
3421       }
3422       else
3423       {
3424         mImpl->mTextUpdateInfo.mCharacterIndex = std::min( cursorIndex, mImpl->mTextUpdateInfo.mCharacterIndex );
3425         mImpl->mTextUpdateInfo.mNumberOfCharactersToRemove += numberOfCharacters;
3426       }
3427
3428       // Update the input style and remove the text's style before removing the text.
3429
3430       if( UPDATE_INPUT_STYLE == type )
3431       {
3432         // Keep a copy of the current input style.
3433         InputStyle currentInputStyle;
3434         currentInputStyle.Copy( mImpl->mEventData->mInputStyle );
3435
3436         // Set first the default input style.
3437         mImpl->RetrieveDefaultInputStyle( mImpl->mEventData->mInputStyle );
3438
3439         // Update the input style.
3440         mImpl->mModel->mLogicalModel->RetrieveStyle( cursorIndex, mImpl->mEventData->mInputStyle );
3441
3442         // Compare if the input style has changed.
3443         const bool hasInputStyleChanged = !currentInputStyle.Equal( mImpl->mEventData->mInputStyle );
3444
3445         if( hasInputStyleChanged )
3446         {
3447           const InputStyle::Mask styleChangedMask = currentInputStyle.GetInputStyleChangeMask( mImpl->mEventData->mInputStyle );
3448           // Queue the input style changed signal.
3449           mImpl->mEventData->mInputStyleChangedQueue.PushBack( styleChangedMask );
3450         }
3451       }
3452
3453       // Updates the text style runs by removing characters. Runs with no characters are removed.
3454       mImpl->mModel->mLogicalModel->UpdateTextStyleRuns( cursorIndex, -numberOfCharacters );
3455
3456       // Remove the characters.
3457       Vector<Character>::Iterator first = currentText.Begin() + cursorIndex;
3458       Vector<Character>::Iterator last  = first + numberOfCharacters;
3459
3460       currentText.Erase( first, last );
3461
3462       // Cursor position retreat
3463       oldCursorIndex = cursorIndex;
3464
3465       mImpl->mEventData->mScrollAfterDelete = true;
3466
3467       DALI_LOG_INFO( gLogFilter, Debug::General, "Controller::RemoveText %p removed %d\n", this, numberOfCharacters );
3468       removed = true;
3469     }
3470   }
3471
3472   return removed;
3473 }
3474
3475 bool Controller::RemoveSelectedText()
3476 {
3477   bool textRemoved( false );
3478
3479   if( EventData::SELECTING == mImpl->mEventData->mState )
3480   {
3481     std::string removedString;
3482     mImpl->RetrieveSelection( removedString, true );
3483
3484     if( !removedString.empty() )
3485     {
3486       textRemoved = true;
3487       mImpl->ChangeState( EventData::EDITING );
3488     }
3489   }
3490
3491   return textRemoved;
3492 }
3493
3494 // private : Relayout.
3495
3496 bool Controller::DoRelayout( const Size& size,
3497                              OperationsMask operationsRequired,
3498                              Size& layoutSize )
3499 {
3500   DALI_LOG_INFO( gLogFilter, Debug::Verbose, "-->Controller::DoRelayout %p size %f,%f\n", this, size.width, size.height );
3501   bool viewUpdated( false );
3502
3503   // Calculate the operations to be done.
3504   const OperationsMask operations = static_cast<OperationsMask>( mImpl->mOperationsPending & operationsRequired );
3505
3506   const CharacterIndex startIndex = mImpl->mTextUpdateInfo.mParagraphCharacterIndex;
3507   const Length requestedNumberOfCharacters = mImpl->mTextUpdateInfo.mRequestedNumberOfCharacters;
3508
3509   // Get the current layout size.
3510   layoutSize = mImpl->mModel->mVisualModel->GetLayoutSize();
3511
3512   if( NO_OPERATION != ( LAYOUT & operations ) )
3513   {
3514     DALI_LOG_INFO( gLogFilter, Debug::Verbose, "-->Controller::DoRelayout LAYOUT & operations\n");
3515
3516     // Some vectors with data needed to layout and reorder may be void
3517     // after the first time the text has been laid out.
3518     // Fill the vectors again.
3519
3520     // Calculate the number of glyphs to layout.
3521     const Vector<GlyphIndex>& charactersToGlyph = mImpl->mModel->mVisualModel->mCharactersToGlyph;
3522     const Vector<Length>& glyphsPerCharacter = mImpl->mModel->mVisualModel->mGlyphsPerCharacter;
3523     const GlyphIndex* const charactersToGlyphBuffer = charactersToGlyph.Begin();
3524     const Length* const glyphsPerCharacterBuffer = glyphsPerCharacter.Begin();
3525
3526     const CharacterIndex lastIndex = startIndex + ( ( requestedNumberOfCharacters > 0u ) ? requestedNumberOfCharacters - 1u : 0u );
3527     const GlyphIndex startGlyphIndex = mImpl->mTextUpdateInfo.mStartGlyphIndex;
3528
3529     // Make sure the index is not out of bound
3530     if ( charactersToGlyph.Count() != glyphsPerCharacter.Count() ||
3531          requestedNumberOfCharacters > charactersToGlyph.Count() ||
3532          ( lastIndex >= charactersToGlyph.Count() && charactersToGlyph.Count() > 0u ) )
3533     {
3534       std::string currentText;
3535       GetText( currentText );
3536
3537       DALI_LOG_ERROR( "Controller::DoRelayout: Attempting to access invalid buffer\n" );
3538       DALI_LOG_ERROR( "Current text is: %s\n", currentText.c_str() );
3539       DALI_LOG_ERROR( "startIndex: %u, lastIndex: %u, requestedNumberOfCharacters: %u, charactersToGlyph.Count = %lu, glyphsPerCharacter.Count = %lu\n", startIndex, lastIndex, requestedNumberOfCharacters, charactersToGlyph.Count(), glyphsPerCharacter.Count());
3540
3541       return false;
3542     }
3543
3544     const Length numberOfGlyphs = ( requestedNumberOfCharacters > 0u ) ? *( charactersToGlyphBuffer + lastIndex ) + *( glyphsPerCharacterBuffer + lastIndex ) - startGlyphIndex : 0u;
3545     const Length totalNumberOfGlyphs = mImpl->mModel->mVisualModel->mGlyphs.Count();
3546
3547     if( 0u == totalNumberOfGlyphs )
3548     {
3549       if( NO_OPERATION != ( UPDATE_LAYOUT_SIZE & operations ) )
3550       {
3551         mImpl->mModel->mVisualModel->SetLayoutSize( Size::ZERO );
3552       }
3553
3554       // Nothing else to do if there is no glyphs.
3555       DALI_LOG_INFO( gLogFilter, Debug::Verbose, "<--Controller::DoRelayout no glyphs, view updated true\n" );
3556       return true;
3557     }
3558
3559     const Vector<LineBreakInfo>& lineBreakInfo = mImpl->mModel->mLogicalModel->mLineBreakInfo;
3560     const Vector<WordBreakInfo>& wordBreakInfo = mImpl->mModel->mLogicalModel->mWordBreakInfo;
3561     const Vector<CharacterDirection>& characterDirection = mImpl->mModel->mLogicalModel->mCharacterDirections;
3562     const Vector<GlyphInfo>& glyphs = mImpl->mModel->mVisualModel->mGlyphs;
3563     const Vector<CharacterIndex>& glyphsToCharactersMap = mImpl->mModel->mVisualModel->mGlyphsToCharacters;
3564     const Vector<Length>& charactersPerGlyph = mImpl->mModel->mVisualModel->mCharactersPerGlyph;
3565     const Character* const textBuffer = mImpl->mModel->mLogicalModel->mText.Begin();
3566     const float outlineWidth = static_cast<float>( mImpl->mModel->GetOutlineWidth() );
3567
3568     // Set the layout parameters.
3569     Layout::Parameters layoutParameters( size,
3570                                          textBuffer,
3571                                          lineBreakInfo.Begin(),
3572                                          wordBreakInfo.Begin(),
3573                                          ( 0u != characterDirection.Count() ) ? characterDirection.Begin() : NULL,
3574                                          glyphs.Begin(),
3575                                          glyphsToCharactersMap.Begin(),
3576                                          charactersPerGlyph.Begin(),
3577                                          charactersToGlyphBuffer,
3578                                          glyphsPerCharacterBuffer,
3579                                          totalNumberOfGlyphs,
3580                                          mImpl->mModel->mHorizontalAlignment,
3581                                          mImpl->mModel->mLineWrapMode,
3582                                          outlineWidth,
3583                                          mImpl->mModel->mIgnoreSpacesAfterText,
3584                                          mImpl->mModel->mMatchSystemLanguageDirection );
3585
3586     // Resize the vector of positions to have the same size than the vector of glyphs.
3587     Vector<Vector2>& glyphPositions = mImpl->mModel->mVisualModel->mGlyphPositions;
3588     glyphPositions.Resize( totalNumberOfGlyphs );
3589
3590     // Whether the last character is a new paragraph character.
3591     mImpl->mTextUpdateInfo.mIsLastCharacterNewParagraph =  TextAbstraction::IsNewParagraph( *( textBuffer + ( mImpl->mModel->mLogicalModel->mText.Count() - 1u ) ) );
3592     layoutParameters.isLastNewParagraph = mImpl->mTextUpdateInfo.mIsLastCharacterNewParagraph;
3593
3594     // The initial glyph and the number of glyphs to layout.
3595     layoutParameters.startGlyphIndex = startGlyphIndex;
3596     layoutParameters.numberOfGlyphs = numberOfGlyphs;
3597     layoutParameters.startLineIndex = mImpl->mTextUpdateInfo.mStartLineIndex;
3598     layoutParameters.estimatedNumberOfLines = mImpl->mTextUpdateInfo.mEstimatedNumberOfLines;
3599
3600     // Update the ellipsis
3601     bool elideTextEnabled = mImpl->mModel->mElideEnabled;
3602
3603     if( NULL != mImpl->mEventData )
3604     {
3605       if( mImpl->mEventData->mPlaceholderEllipsisFlag && mImpl->IsShowingPlaceholderText() )
3606       {
3607         elideTextEnabled = mImpl->mEventData->mIsPlaceholderElideEnabled;
3608       }
3609       else if( EventData::INACTIVE != mImpl->mEventData->mState )
3610       {
3611         // Disable ellipsis when editing
3612         elideTextEnabled = false;
3613       }
3614
3615       // Reset the scroll position in inactive state
3616       if( elideTextEnabled && ( mImpl->mEventData->mState == EventData::INACTIVE ) )
3617       {
3618         ResetScrollPosition();
3619       }
3620     }
3621
3622     // Update the visual model.
3623     bool isAutoScrollEnabled = mImpl->mIsAutoScrollEnabled;
3624     Size newLayoutSize;
3625     viewUpdated = mImpl->mLayoutEngine.LayoutText( layoutParameters,
3626                                                    glyphPositions,
3627                                                    mImpl->mModel->mVisualModel->mLines,
3628                                                    newLayoutSize,
3629                                                    elideTextEnabled,
3630                                                    isAutoScrollEnabled );
3631     mImpl->mIsAutoScrollEnabled = isAutoScrollEnabled;
3632
3633     viewUpdated = viewUpdated || ( newLayoutSize != layoutSize );
3634
3635     if( viewUpdated )
3636     {
3637       layoutSize = newLayoutSize;
3638
3639       if( NO_OPERATION != ( UPDATE_DIRECTION & operations ) )
3640       {
3641         mImpl->mIsTextDirectionRTL = false;
3642       }
3643
3644       // Reorder the lines
3645       if( NO_OPERATION != ( REORDER & operations ) )
3646       {
3647         Vector<BidirectionalParagraphInfoRun>& bidirectionalInfo = mImpl->mModel->mLogicalModel->mBidirectionalParagraphInfo;
3648         Vector<BidirectionalLineInfoRun>& bidirectionalLineInfo = mImpl->mModel->mLogicalModel->mBidirectionalLineInfo;
3649
3650         // Check first if there are paragraphs with bidirectional info.
3651         if( 0u != bidirectionalInfo.Count() )
3652         {
3653           // Get the lines
3654           const Length numberOfLines = mImpl->mModel->mVisualModel->mLines.Count();
3655
3656           // Reorder the lines.
3657           bidirectionalLineInfo.Reserve( numberOfLines ); // Reserve because is not known yet how many lines have right to left characters.
3658           ReorderLines( bidirectionalInfo,
3659                         startIndex,
3660                         requestedNumberOfCharacters,
3661                         mImpl->mModel->mVisualModel->mLines,
3662                         bidirectionalLineInfo );
3663
3664           // Set the bidirectional info per line into the layout parameters.
3665           layoutParameters.lineBidirectionalInfoRunsBuffer = bidirectionalLineInfo.Begin();
3666           layoutParameters.numberOfBidirectionalInfoRuns = bidirectionalLineInfo.Count();
3667
3668           // Re-layout the text. Reorder those lines with right to left characters.
3669           mImpl->mLayoutEngine.ReLayoutRightToLeftLines( layoutParameters,
3670                                                          startIndex,
3671                                                          requestedNumberOfCharacters,
3672                                                          glyphPositions );
3673
3674           if ( ( NO_OPERATION != ( UPDATE_DIRECTION & operations ) ) && ( numberOfLines > 0 ) )
3675           {
3676             const LineRun* const firstline = mImpl->mModel->mVisualModel->mLines.Begin();
3677             if ( firstline )
3678             {
3679               mImpl->mIsTextDirectionRTL = firstline->direction;
3680             }
3681           }
3682         }
3683       } // REORDER
3684
3685       // Sets the layout size.
3686       if( NO_OPERATION != ( UPDATE_LAYOUT_SIZE & operations ) )
3687       {
3688         mImpl->mModel->mVisualModel->SetLayoutSize( layoutSize );
3689       }
3690     } // view updated
3691   }
3692
3693   if( NO_OPERATION != ( ALIGN & operations ) )
3694   {
3695     // The laid-out lines.
3696     Vector<LineRun>& lines = mImpl->mModel->mVisualModel->mLines;
3697
3698     // Need to align with the control's size as the text may contain lines
3699     // starting either with left to right text or right to left.
3700     mImpl->mLayoutEngine.Align( size,
3701                                 startIndex,
3702                                 requestedNumberOfCharacters,
3703                                 mImpl->mModel->mHorizontalAlignment,
3704                                 lines,
3705                                 mImpl->mModel->mAlignmentOffset,
3706                                 mImpl->mLayoutDirection,
3707                                 mImpl->mModel->mMatchSystemLanguageDirection );
3708
3709     viewUpdated = true;
3710   }
3711 #if defined(DEBUG_ENABLED)
3712   std::string currentText;
3713   GetText( currentText );
3714   DALI_LOG_INFO( gLogFilter, Debug::Concise, "Controller::DoRelayout [%p] mImpl->mIsTextDirectionRTL[%s] [%s]\n", this, (mImpl->mIsTextDirectionRTL)?"true":"false",  currentText.c_str() );
3715 #endif
3716   DALI_LOG_INFO( gLogFilter, Debug::Verbose, "<--Controller::DoRelayout, view updated %s\n", ( viewUpdated ? "true" : "false" ) );
3717   return viewUpdated;
3718 }
3719
3720 void Controller::CalculateVerticalOffset( const Size& controlSize )
3721 {
3722   Size layoutSize = mImpl->mModel->mVisualModel->GetLayoutSize();
3723
3724   if( fabsf( layoutSize.height ) < Math::MACHINE_EPSILON_1000 )
3725   {
3726     // Get the line height of the default font.
3727     layoutSize.height = mImpl->GetDefaultFontLineHeight();
3728   }
3729
3730   switch( mImpl->mModel->mVerticalAlignment )
3731   {
3732     case VerticalAlignment::TOP:
3733     {
3734       mImpl->mModel->mScrollPosition.y = 0.f;
3735       break;
3736     }
3737     case VerticalAlignment::CENTER:
3738     {
3739       mImpl->mModel->mScrollPosition.y = floorf( 0.5f * ( controlSize.height - layoutSize.height ) ); // try to avoid pixel alignment.
3740       break;
3741     }
3742     case VerticalAlignment::BOTTOM:
3743     {
3744       mImpl->mModel->mScrollPosition.y = controlSize.height - layoutSize.height;
3745       break;
3746     }
3747   }
3748 }
3749
3750 // private : Events.
3751
3752 void Controller::ProcessModifyEvents()
3753 {
3754   Vector<ModifyEvent>& events = mImpl->mModifyEvents;
3755
3756   if( 0u == events.Count() )
3757   {
3758     // Nothing to do.
3759     return;
3760   }
3761
3762   for( Vector<ModifyEvent>::ConstIterator it = events.Begin(),
3763          endIt = events.End();
3764        it != endIt;
3765        ++it )
3766   {
3767     const ModifyEvent& event = *it;
3768
3769     if( ModifyEvent::TEXT_REPLACED == event.type )
3770     {
3771       // A (single) replace event should come first, otherwise we wasted time processing NOOP events
3772       DALI_ASSERT_DEBUG( it == events.Begin() && "Unexpected TEXT_REPLACED event" );
3773
3774       TextReplacedEvent();
3775     }
3776     else if( ModifyEvent::TEXT_INSERTED == event.type )
3777     {
3778       TextInsertedEvent();
3779     }
3780     else if( ModifyEvent::TEXT_DELETED == event.type )
3781     {
3782       // Placeholder-text cannot be deleted
3783       if( !mImpl->IsShowingPlaceholderText() )
3784       {
3785         TextDeletedEvent();
3786       }
3787     }
3788   }
3789
3790   if( NULL != mImpl->mEventData )
3791   {
3792     // When the text is being modified, delay cursor blinking
3793     mImpl->mEventData->mDecorator->DelayCursorBlink();
3794
3795     // Update selection position after modifying the text
3796     mImpl->mEventData->mLeftSelectionPosition = mImpl->mEventData->mPrimaryCursorPosition;
3797     mImpl->mEventData->mRightSelectionPosition = mImpl->mEventData->mPrimaryCursorPosition;
3798   }
3799
3800   // Discard temporary text
3801   events.Clear();
3802 }
3803
3804 void Controller::TextReplacedEvent()
3805 {
3806   // The natural size needs to be re-calculated.
3807   mImpl->mRecalculateNaturalSize = true;
3808
3809   // The text direction needs to be updated.
3810   mImpl->mUpdateTextDirection = true;
3811
3812   // Apply modifications to the model
3813   mImpl->mOperationsPending = ALL_OPERATIONS;
3814 }
3815
3816 void Controller::TextInsertedEvent()
3817 {
3818   DALI_ASSERT_DEBUG( NULL != mImpl->mEventData && "Unexpected TextInsertedEvent" );
3819
3820   if( NULL == mImpl->mEventData )
3821   {
3822     return;
3823   }
3824
3825   mImpl->mEventData->mCheckScrollAmount = true;
3826
3827   // The natural size needs to be re-calculated.
3828   mImpl->mRecalculateNaturalSize = true;
3829
3830   // The text direction needs to be updated.
3831   mImpl->mUpdateTextDirection = true;
3832
3833   // Apply modifications to the model; TODO - Optimize this
3834   mImpl->mOperationsPending = ALL_OPERATIONS;
3835 }
3836
3837 void Controller::TextDeletedEvent()
3838 {
3839   DALI_ASSERT_DEBUG( NULL != mImpl->mEventData && "Unexpected TextDeletedEvent" );
3840
3841   if( NULL == mImpl->mEventData )
3842   {
3843     return;
3844   }
3845
3846   mImpl->mEventData->mCheckScrollAmount = true;
3847
3848   // The natural size needs to be re-calculated.
3849   mImpl->mRecalculateNaturalSize = true;
3850
3851   // The text direction needs to be updated.
3852   mImpl->mUpdateTextDirection = true;
3853
3854   // Apply modifications to the model; TODO - Optimize this
3855   mImpl->mOperationsPending = ALL_OPERATIONS;
3856 }
3857
3858 void Controller::SelectEvent( float x, float y, bool selectAll )
3859 {
3860   DALI_LOG_INFO( gLogFilter, Debug::Verbose, "Controller::SelectEvent\n" );
3861
3862   if( NULL != mImpl->mEventData )
3863   {
3864     if( selectAll )
3865     {
3866       Event event( Event::SELECT_ALL );
3867       mImpl->mEventData->mEventQueue.push_back( event );
3868     }
3869     else
3870     {
3871       Event event( Event::SELECT );
3872       event.p2.mFloat = x;
3873       event.p3.mFloat = y;
3874       mImpl->mEventData->mEventQueue.push_back( event );
3875     }
3876
3877     mImpl->mEventData->mCheckScrollAmount = true;
3878     mImpl->mEventData->mIsLeftHandleSelected = true;
3879     mImpl->mEventData->mIsRightHandleSelected = true;
3880     mImpl->RequestRelayout();
3881   }
3882 }
3883
3884 bool Controller::DeleteEvent( int keyCode )
3885 {
3886   DALI_LOG_INFO( gLogFilter, Debug::Verbose, "Controller::KeyEvent %p KeyCode : %d \n", this, keyCode );
3887
3888   bool removed = false;
3889
3890   if( NULL == mImpl->mEventData )
3891   {
3892     return removed;
3893   }
3894
3895   // InputMethodContext is no longer handling key-events
3896   mImpl->ClearPreEditFlag();
3897
3898   if( EventData::SELECTING == mImpl->mEventData->mState )
3899   {
3900     removed = RemoveSelectedText();
3901   }
3902   else if( ( mImpl->mEventData->mPrimaryCursorPosition > 0 ) && ( keyCode == Dali::DALI_KEY_BACKSPACE) )
3903   {
3904     // Remove the character before the current cursor position
3905     removed = RemoveText( -1,
3906                           1,
3907                           UPDATE_INPUT_STYLE );
3908   }
3909   else if( keyCode == Dali::DevelKey::DALI_KEY_DELETE )
3910   {
3911     // Remove the character after the current cursor position
3912     removed = RemoveText( 0,
3913                           1,
3914                           UPDATE_INPUT_STYLE );
3915   }
3916
3917   if( removed )
3918   {
3919     if( ( 0u != mImpl->mModel->mLogicalModel->mText.Count() ) ||
3920         !mImpl->IsPlaceholderAvailable() )
3921     {
3922       mImpl->QueueModifyEvent( ModifyEvent::TEXT_DELETED );
3923     }
3924     else
3925     {
3926       ShowPlaceholderText();
3927     }
3928     mImpl->mEventData->mUpdateCursorPosition = true;
3929     mImpl->mEventData->mScrollAfterDelete = true;
3930   }
3931
3932   return removed;
3933 }
3934
3935 // private : Helpers.
3936
3937 void Controller::ResetText()
3938 {
3939   // Reset buffers.
3940   mImpl->mModel->mLogicalModel->mText.Clear();
3941
3942   // We have cleared everything including the placeholder-text
3943   mImpl->PlaceholderCleared();
3944
3945   mImpl->mTextUpdateInfo.mCharacterIndex = 0u;
3946   mImpl->mTextUpdateInfo.mNumberOfCharactersToRemove = mImpl->mTextUpdateInfo.mPreviousNumberOfCharacters;
3947   mImpl->mTextUpdateInfo.mNumberOfCharactersToAdd = 0u;
3948
3949   // Clear any previous text.
3950   mImpl->mTextUpdateInfo.mClearAll = true;
3951
3952   // The natural size needs to be re-calculated.
3953   mImpl->mRecalculateNaturalSize = true;
3954
3955   // The text direction needs to be updated.
3956   mImpl->mUpdateTextDirection = true;
3957
3958   // Apply modifications to the model
3959   mImpl->mOperationsPending = ALL_OPERATIONS;
3960 }
3961
3962 void Controller::ShowPlaceholderText()
3963 {
3964   if( mImpl->IsPlaceholderAvailable() )
3965   {
3966     DALI_ASSERT_DEBUG( mImpl->mEventData && "No placeholder text available" );
3967
3968     if( NULL == mImpl->mEventData )
3969     {
3970       return;
3971     }
3972
3973     mImpl->mEventData->mIsShowingPlaceholderText = true;
3974
3975     // Disable handles when showing place-holder text
3976     mImpl->mEventData->mDecorator->SetHandleActive( GRAB_HANDLE, false );
3977     mImpl->mEventData->mDecorator->SetHandleActive( LEFT_SELECTION_HANDLE, false );
3978     mImpl->mEventData->mDecorator->SetHandleActive( RIGHT_SELECTION_HANDLE, false );
3979
3980     const char* text( NULL );
3981     size_t size( 0 );
3982
3983     // TODO - Switch Placeholder text when changing state
3984     if( ( EventData::INACTIVE != mImpl->mEventData->mState ) &&
3985         ( 0u != mImpl->mEventData->mPlaceholderTextActive.c_str() ) )
3986     {
3987       text = mImpl->mEventData->mPlaceholderTextActive.c_str();
3988       size = mImpl->mEventData->mPlaceholderTextActive.size();
3989     }
3990     else
3991     {
3992       text = mImpl->mEventData->mPlaceholderTextInactive.c_str();
3993       size = mImpl->mEventData->mPlaceholderTextInactive.size();
3994     }
3995
3996     mImpl->mTextUpdateInfo.mCharacterIndex = 0u;
3997     mImpl->mTextUpdateInfo.mNumberOfCharactersToRemove = mImpl->mTextUpdateInfo.mPreviousNumberOfCharacters;
3998
3999     // Reset model for showing placeholder.
4000     mImpl->mModel->mLogicalModel->mText.Clear();
4001     mImpl->mModel->mVisualModel->SetTextColor( mImpl->mEventData->mPlaceholderTextColor );
4002
4003     // Convert text into UTF-32
4004     Vector<Character>& utf32Characters = mImpl->mModel->mLogicalModel->mText;
4005     utf32Characters.Resize( size );
4006
4007     // This is a bit horrible but std::string returns a (signed) char*
4008     const uint8_t* utf8 = reinterpret_cast<const uint8_t*>( text );
4009
4010     // Transform a text array encoded in utf8 into an array encoded in utf32.
4011     // It returns the actual number of characters.
4012     const Length characterCount = Utf8ToUtf32( utf8, size, utf32Characters.Begin() );
4013     utf32Characters.Resize( characterCount );
4014
4015     // The characters to be added.
4016     mImpl->mTextUpdateInfo.mNumberOfCharactersToAdd = characterCount;
4017
4018     // Reset the cursor position
4019     mImpl->mEventData->mPrimaryCursorPosition = 0;
4020
4021     // The natural size needs to be re-calculated.
4022     mImpl->mRecalculateNaturalSize = true;
4023
4024     // The text direction needs to be updated.
4025     mImpl->mUpdateTextDirection = true;
4026
4027     // Apply modifications to the model
4028     mImpl->mOperationsPending = ALL_OPERATIONS;
4029
4030     // Update the rest of the model during size negotiation
4031     mImpl->QueueModifyEvent( ModifyEvent::TEXT_REPLACED );
4032   }
4033 }
4034
4035 void Controller::ClearFontData()
4036 {
4037   if( mImpl->mFontDefaults )
4038   {
4039     mImpl->mFontDefaults->mFontId = 0u; // Remove old font ID
4040   }
4041
4042   // Set flags to update the model.
4043   mImpl->mTextUpdateInfo.mCharacterIndex = 0u;
4044   mImpl->mTextUpdateInfo.mNumberOfCharactersToRemove = mImpl->mTextUpdateInfo.mPreviousNumberOfCharacters;
4045   mImpl->mTextUpdateInfo.mNumberOfCharactersToAdd = mImpl->mModel->mLogicalModel->mText.Count();
4046
4047   mImpl->mTextUpdateInfo.mClearAll = true;
4048   mImpl->mTextUpdateInfo.mFullRelayoutNeeded = true;
4049   mImpl->mRecalculateNaturalSize = true;
4050
4051   mImpl->mOperationsPending = static_cast<OperationsMask>( mImpl->mOperationsPending |
4052                                                            VALIDATE_FONTS            |
4053                                                            SHAPE_TEXT                |
4054                                                            BIDI_INFO                 |
4055                                                            GET_GLYPH_METRICS         |
4056                                                            LAYOUT                    |
4057                                                            UPDATE_LAYOUT_SIZE        |
4058                                                            REORDER                   |
4059                                                            ALIGN );
4060 }
4061
4062 void Controller::ClearStyleData()
4063 {
4064   mImpl->mModel->mLogicalModel->mColorRuns.Clear();
4065   mImpl->mModel->mLogicalModel->ClearFontDescriptionRuns();
4066 }
4067
4068 void Controller::ResetCursorPosition( CharacterIndex cursorIndex )
4069 {
4070   // Reset the cursor position
4071   if( NULL != mImpl->mEventData )
4072   {
4073     mImpl->mEventData->mPrimaryCursorPosition = cursorIndex;
4074
4075     // Update the cursor if it's in editing mode.
4076     if( EventData::IsEditingState( mImpl->mEventData->mState )  )
4077     {
4078       mImpl->mEventData->mUpdateCursorPosition = true;
4079     }
4080   }
4081 }
4082
4083 void Controller::ResetScrollPosition()
4084 {
4085   if( NULL != mImpl->mEventData )
4086   {
4087     // Reset the scroll position.
4088     mImpl->mModel->mScrollPosition = Vector2::ZERO;
4089     mImpl->mEventData->mScrollAfterUpdatePosition = true;
4090   }
4091 }
4092
4093 void Controller::SetControlInterface( ControlInterface* controlInterface )
4094 {
4095   mImpl->mControlInterface = controlInterface;
4096 }
4097
4098 bool Controller::ShouldClearFocusOnEscape() const
4099 {
4100   return mImpl->mShouldClearFocusOnEscape;
4101 }
4102
4103 // private : Private contructors & copy operator.
4104
4105 Controller::Controller()
4106 : mImpl( NULL )
4107 {
4108   mImpl = new Controller::Impl( NULL, NULL );
4109 }
4110
4111 Controller::Controller( ControlInterface* controlInterface )
4112 {
4113   mImpl = new Controller::Impl( controlInterface, NULL );
4114 }
4115
4116 Controller::Controller( ControlInterface* controlInterface,
4117                         EditableControlInterface* editableControlInterface )
4118 {
4119   mImpl = new Controller::Impl( controlInterface,
4120                                 editableControlInterface );
4121 }
4122
4123 // The copy constructor and operator are left unimplemented.
4124
4125 // protected : Destructor.
4126
4127 Controller::~Controller()
4128 {
4129   delete mImpl;
4130 }
4131
4132 } // namespace Text
4133
4134 } // namespace Toolkit
4135
4136 } // namespace Dali