[Tizen] Checked if mInputStyle has changed.
[platform/core/uifw/dali-toolkit.git] / dali-toolkit / internal / text / text-controller.cpp
1 /*
2  * Copyright (c) 2018 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     mImpl->RequestRelayout();
365   }
366 }
367
368 bool Controller::IsMultiLineEnabled() const
369 {
370   return Layout::Engine::MULTI_LINE_BOX == mImpl->mLayoutEngine.GetLayout();
371 }
372
373 void Controller::SetHorizontalAlignment( Text::HorizontalAlignment::Type alignment )
374 {
375   if( alignment != mImpl->mModel->mHorizontalAlignment )
376   {
377     // Set the alignment.
378     mImpl->mModel->mHorizontalAlignment = alignment;
379
380     // Set the flag to redo the alignment operation.
381     mImpl->mOperationsPending = static_cast<OperationsMask>( mImpl->mOperationsPending | ALIGN );
382
383     mImpl->RequestRelayout();
384   }
385 }
386
387 Text::HorizontalAlignment::Type Controller::GetHorizontalAlignment() const
388 {
389   return mImpl->mModel->mHorizontalAlignment;
390 }
391
392 void Controller::SetVerticalAlignment( VerticalAlignment::Type alignment )
393 {
394   if( alignment != mImpl->mModel->mVerticalAlignment )
395   {
396     // Set the alignment.
397     mImpl->mModel->mVerticalAlignment = alignment;
398
399     mImpl->mOperationsPending = static_cast<OperationsMask>( mImpl->mOperationsPending | ALIGN );
400
401     mImpl->RequestRelayout();
402   }
403 }
404
405 VerticalAlignment::Type Controller::GetVerticalAlignment() const
406 {
407   return mImpl->mModel->mVerticalAlignment;
408 }
409
410 bool Controller::IsIgnoreSpacesAfterText() const
411 {
412   return mImpl->mModel->mIgnoreSpacesAfterText;
413 }
414
415 void Controller::SetIgnoreSpacesAfterText( bool ignore )
416 {
417   mImpl->mModel->mIgnoreSpacesAfterText = ignore;
418 }
419
420 bool Controller::IsMatchSystemLanguageDirection() const
421 {
422   return mImpl->mModel->mMatchSystemLanguageDirection;
423 }
424
425 void Controller::SetMatchSystemLanguageDirection( bool match )
426 {
427   mImpl->mModel->mMatchSystemLanguageDirection = match;
428 }
429
430 void Controller::SetLayoutDirection( Dali::LayoutDirection::Type layoutDirection )
431 {
432   mImpl->mLayoutDirection = layoutDirection;
433 }
434
435
436 void Controller::SetLineWrapMode( Text::LineWrap::Mode lineWrapMode )
437 {
438   if( lineWrapMode != mImpl->mModel->mLineWrapMode )
439   {
440     // Set the text wrap mode.
441     mImpl->mModel->mLineWrapMode = lineWrapMode;
442
443
444     // Update Text layout for applying wrap mode
445     mImpl->mOperationsPending = static_cast<OperationsMask>( mImpl->mOperationsPending |
446                                                              ALIGN                     |
447                                                              LAYOUT                    |
448                                                              UPDATE_LAYOUT_SIZE        |
449                                                              REORDER                   );
450     mImpl->mTextUpdateInfo.mCharacterIndex = 0u;
451     mImpl->mTextUpdateInfo.mNumberOfCharactersToRemove = mImpl->mTextUpdateInfo.mPreviousNumberOfCharacters;
452     mImpl->mTextUpdateInfo.mNumberOfCharactersToAdd = mImpl->mModel->mLogicalModel->mText.Count();
453
454     // Request relayout
455     mImpl->RequestRelayout();
456   }
457 }
458
459 Text::LineWrap::Mode Controller::GetLineWrapMode() const
460 {
461   return mImpl->mModel->mLineWrapMode;
462 }
463
464 void Controller::SetTextElideEnabled( bool enabled )
465 {
466   mImpl->mModel->mElideEnabled = enabled;
467 }
468
469 bool Controller::IsTextElideEnabled() const
470 {
471   return mImpl->mModel->mElideEnabled;
472 }
473
474 void Controller::SetPlaceholderTextElideEnabled( bool enabled )
475 {
476   mImpl->mEventData->mIsPlaceholderElideEnabled = enabled;
477   mImpl->mEventData->mPlaceholderEllipsisFlag = true;
478
479   // Update placeholder if there is no text
480   if( mImpl->IsShowingPlaceholderText() ||
481       ( 0u == mImpl->mModel->mLogicalModel->mText.Count() ) )
482   {
483     ShowPlaceholderText();
484   }
485 }
486
487 bool Controller::IsPlaceholderTextElideEnabled() const
488 {
489   return mImpl->mEventData->mIsPlaceholderElideEnabled;
490 }
491
492 void Controller::SetSelectionEnabled( bool enabled )
493 {
494   mImpl->mEventData->mSelectionEnabled = enabled;
495 }
496
497 bool Controller::IsSelectionEnabled() const
498 {
499   return mImpl->mEventData->mSelectionEnabled;
500 }
501
502 void Controller::SetShiftSelectionEnabled( bool enabled )
503 {
504   mImpl->mEventData->mShiftSelectionFlag = enabled;
505 }
506
507 bool Controller::IsShiftSelectionEnabled() const
508 {
509   return mImpl->mEventData->mShiftSelectionFlag;
510 }
511
512 void Controller::SetGrabHandleEnabled( bool enabled )
513 {
514   mImpl->mEventData->mGrabHandleEnabled = enabled;
515 }
516
517 bool Controller::IsGrabHandleEnabled() const
518 {
519   return mImpl->mEventData->mGrabHandleEnabled;
520 }
521
522 // public : Update
523
524 void Controller::SetText( const std::string& text )
525 {
526   DALI_LOG_INFO( gLogFilter, Debug::Verbose, "Controller::SetText\n" );
527
528   // Reset keyboard as text changed
529   mImpl->ResetInputMethodContext();
530
531   // Remove the previously set text and style.
532   ResetText();
533
534   // Remove the style.
535   ClearStyleData();
536
537   CharacterIndex lastCursorIndex = 0u;
538
539   if( NULL != mImpl->mEventData )
540   {
541     // If popup shown then hide it by switching to Editing state
542     if( ( EventData::SELECTING == mImpl->mEventData->mState )          ||
543         ( EventData::EDITING_WITH_POPUP == mImpl->mEventData->mState ) ||
544         ( EventData::EDITING_WITH_GRAB_HANDLE == mImpl->mEventData->mState ) ||
545         ( EventData::EDITING_WITH_PASTE_POPUP == mImpl->mEventData->mState ) )
546     {
547       mImpl->ChangeState( EventData::EDITING );
548     }
549   }
550
551   if( !text.empty() )
552   {
553     mImpl->mModel->mVisualModel->SetTextColor( mImpl->mTextColor );
554
555     MarkupProcessData markupProcessData( mImpl->mModel->mLogicalModel->mColorRuns,
556                                          mImpl->mModel->mLogicalModel->mFontDescriptionRuns );
557
558     Length textSize = 0u;
559     const uint8_t* utf8 = NULL;
560     if( mImpl->mMarkupProcessorEnabled )
561     {
562       ProcessMarkupString( text, markupProcessData );
563       textSize = markupProcessData.markupProcessedText.size();
564
565       // This is a bit horrible but std::string returns a (signed) char*
566       utf8 = reinterpret_cast<const uint8_t*>( markupProcessData.markupProcessedText.c_str() );
567     }
568     else
569     {
570       textSize = text.size();
571
572       // This is a bit horrible but std::string returns a (signed) char*
573       utf8 = reinterpret_cast<const uint8_t*>( text.c_str() );
574     }
575
576     const Length maxTextLength = 32768u; // 1024 * 32;
577     if( textSize > maxTextLength )
578     {
579       DALI_LOG_WARNING( "The text size is too large(%d), limit the length to 32,768u\n", textSize );
580       textSize = maxTextLength;
581     }
582
583     //  Convert text into UTF-32
584     Vector<Character>& utf32Characters = mImpl->mModel->mLogicalModel->mText;
585     utf32Characters.Resize( textSize );
586
587     // Transform a text array encoded in utf8 into an array encoded in utf32.
588     // It returns the actual number of characters.
589     Length characterCount = Utf8ToUtf32( utf8, textSize, utf32Characters.Begin() );
590     utf32Characters.Resize( characterCount );
591
592     DALI_ASSERT_DEBUG( textSize >= characterCount && "Invalid UTF32 conversion length" );
593     DALI_LOG_INFO( gLogFilter, Debug::Verbose, "Controller::SetText %p UTF8 size %d, UTF32 size %d\n", this, textSize, mImpl->mModel->mLogicalModel->mText.Count() );
594
595     // The characters to be added.
596     mImpl->mTextUpdateInfo.mNumberOfCharactersToAdd = mImpl->mModel->mLogicalModel->mText.Count();
597
598     // To reset the cursor position
599     lastCursorIndex = characterCount;
600
601     // Update the rest of the model during size negotiation
602     mImpl->QueueModifyEvent( ModifyEvent::TEXT_REPLACED );
603
604     // The natural size needs to be re-calculated.
605     mImpl->mRecalculateNaturalSize = true;
606
607     // The text direction needs to be updated.
608     mImpl->mUpdateTextDirection = true;
609
610     // Apply modifications to the model
611     mImpl->mOperationsPending = ALL_OPERATIONS;
612   }
613   else
614   {
615     ShowPlaceholderText();
616   }
617
618   // Resets the cursor position.
619   ResetCursorPosition( lastCursorIndex );
620
621   // Scrolls the text to make the cursor visible.
622   ResetScrollPosition();
623
624   mImpl->RequestRelayout();
625
626   if( NULL != mImpl->mEventData )
627   {
628     // Cancel previously queued events
629     mImpl->mEventData->mEventQueue.clear();
630   }
631
632   // Do this last since it provides callbacks into application code.
633   if( NULL != mImpl->mEditableControlInterface )
634   {
635     mImpl->mEditableControlInterface->TextChanged();
636   }
637 }
638
639 void Controller::GetText( std::string& text ) const
640 {
641   if( !mImpl->IsShowingPlaceholderText() )
642   {
643     // Retrieves the text string.
644     mImpl->GetText( 0u, text );
645   }
646   else
647   {
648     DALI_LOG_INFO( gLogFilter, Debug::Verbose, "Controller::GetText %p empty (but showing placeholder)\n", this );
649   }
650 }
651
652 void Controller::SetPlaceholderText( PlaceholderType type, const std::string& text )
653 {
654   if( NULL != mImpl->mEventData )
655   {
656     if( PLACEHOLDER_TYPE_INACTIVE == type )
657     {
658       mImpl->mEventData->mPlaceholderTextInactive = text;
659     }
660     else
661     {
662       mImpl->mEventData->mPlaceholderTextActive = text;
663     }
664
665     // Update placeholder if there is no text
666     if( mImpl->IsShowingPlaceholderText() ||
667         ( 0u == mImpl->mModel->mLogicalModel->mText.Count() ) )
668     {
669       ShowPlaceholderText();
670     }
671   }
672 }
673
674 void Controller::GetPlaceholderText( PlaceholderType type, std::string& text ) const
675 {
676   if( NULL != mImpl->mEventData )
677   {
678     if( PLACEHOLDER_TYPE_INACTIVE == type )
679     {
680       text = mImpl->mEventData->mPlaceholderTextInactive;
681     }
682     else
683     {
684       text = mImpl->mEventData->mPlaceholderTextActive;
685     }
686   }
687 }
688
689 void Controller::UpdateAfterFontChange( const std::string& newDefaultFont )
690 {
691   DALI_LOG_INFO( gLogFilter, Debug::Verbose, "Controller::UpdateAfterFontChange\n");
692
693   if( !mImpl->mFontDefaults->familyDefined ) // If user defined font then should not update when system font changes
694   {
695     DALI_LOG_INFO( gLogFilter, Debug::Concise, "Controller::UpdateAfterFontChange newDefaultFont(%s)\n", newDefaultFont.c_str() );
696     mImpl->mFontDefaults->mFontDescription.family = newDefaultFont;
697
698     ClearFontData();
699
700     mImpl->RequestRelayout();
701   }
702 }
703
704 // public : Default style & Input style
705
706 void Controller::SetDefaultFontFamily( const std::string& defaultFontFamily )
707 {
708   if( NULL == mImpl->mFontDefaults )
709   {
710     mImpl->mFontDefaults = new FontDefaults();
711   }
712
713   mImpl->mFontDefaults->mFontDescription.family = defaultFontFamily;
714   DALI_LOG_INFO( gLogFilter, Debug::General, "Controller::SetDefaultFontFamily %s\n", defaultFontFamily.c_str());
715   mImpl->mFontDefaults->familyDefined = !defaultFontFamily.empty();
716
717   // Clear the font-specific data
718   ClearFontData();
719
720   mImpl->RequestRelayout();
721 }
722
723 const std::string& Controller::GetDefaultFontFamily() const
724 {
725   if( NULL != mImpl->mFontDefaults )
726   {
727     return mImpl->mFontDefaults->mFontDescription.family;
728   }
729
730   return EMPTY_STRING;
731 }
732
733 void Controller::SetPlaceholderFontFamily( const std::string& placeholderTextFontFamily )
734 {
735   if( NULL != mImpl->mEventData )
736   {
737     if( NULL == mImpl->mEventData->mPlaceholderFont )
738     {
739       mImpl->mEventData->mPlaceholderFont = new FontDefaults();
740     }
741
742     mImpl->mEventData->mPlaceholderFont->mFontDescription.family = placeholderTextFontFamily;
743     DALI_LOG_INFO( gLogFilter, Debug::General, "Controller::SetPlaceholderFontFamily %s\n", placeholderTextFontFamily.c_str());
744     mImpl->mEventData->mPlaceholderFont->familyDefined = !placeholderTextFontFamily.empty();
745
746     mImpl->RequestRelayout();
747   }
748 }
749
750 const std::string& Controller::GetPlaceholderFontFamily() const
751 {
752   if( ( NULL != mImpl->mEventData ) && ( NULL != mImpl->mEventData->mPlaceholderFont ) )
753   {
754     return mImpl->mEventData->mPlaceholderFont->mFontDescription.family;
755   }
756
757   return EMPTY_STRING;
758 }
759
760 void Controller::SetDefaultFontWeight( FontWeight weight )
761 {
762   if( NULL == mImpl->mFontDefaults )
763   {
764     mImpl->mFontDefaults = new FontDefaults();
765   }
766
767   mImpl->mFontDefaults->mFontDescription.weight = weight;
768   mImpl->mFontDefaults->weightDefined = true;
769
770   // Clear the font-specific data
771   ClearFontData();
772
773   mImpl->RequestRelayout();
774 }
775
776 bool Controller::IsDefaultFontWeightDefined() const
777 {
778   if( NULL != mImpl->mFontDefaults )
779   {
780     return mImpl->mFontDefaults->weightDefined;
781   }
782
783   return false;
784 }
785
786 FontWeight Controller::GetDefaultFontWeight() const
787 {
788   if( NULL != mImpl->mFontDefaults )
789   {
790     return mImpl->mFontDefaults->mFontDescription.weight;
791   }
792
793   return TextAbstraction::FontWeight::NORMAL;
794 }
795
796 void Controller::SetPlaceholderTextFontWeight( FontWeight weight )
797 {
798   if( NULL != mImpl->mEventData )
799   {
800     if( NULL == mImpl->mEventData->mPlaceholderFont )
801     {
802       mImpl->mEventData->mPlaceholderFont = new FontDefaults();
803     }
804
805     mImpl->mEventData->mPlaceholderFont->mFontDescription.weight = weight;
806     mImpl->mEventData->mPlaceholderFont->weightDefined = true;
807
808     mImpl->RequestRelayout();
809   }
810 }
811
812 bool Controller::IsPlaceholderTextFontWeightDefined() const
813 {
814   if( ( NULL != mImpl->mEventData ) && ( NULL != mImpl->mEventData->mPlaceholderFont ) )
815   {
816     return mImpl->mEventData->mPlaceholderFont->weightDefined;
817   }
818   return false;
819 }
820
821 FontWeight Controller::GetPlaceholderTextFontWeight() const
822 {
823   if( ( NULL != mImpl->mEventData ) && ( NULL != mImpl->mEventData->mPlaceholderFont ) )
824   {
825     return mImpl->mEventData->mPlaceholderFont->mFontDescription.weight;
826   }
827
828   return TextAbstraction::FontWeight::NORMAL;
829 }
830
831 void Controller::SetDefaultFontWidth( FontWidth width )
832 {
833   if( NULL == mImpl->mFontDefaults )
834   {
835     mImpl->mFontDefaults = new FontDefaults();
836   }
837
838   mImpl->mFontDefaults->mFontDescription.width = width;
839   mImpl->mFontDefaults->widthDefined = true;
840
841   // Clear the font-specific data
842   ClearFontData();
843
844   mImpl->RequestRelayout();
845 }
846
847 bool Controller::IsDefaultFontWidthDefined() const
848 {
849   if( NULL != mImpl->mFontDefaults )
850   {
851     return mImpl->mFontDefaults->widthDefined;
852   }
853
854   return false;
855 }
856
857 FontWidth Controller::GetDefaultFontWidth() const
858 {
859   if( NULL != mImpl->mFontDefaults )
860   {
861     return mImpl->mFontDefaults->mFontDescription.width;
862   }
863
864   return TextAbstraction::FontWidth::NORMAL;
865 }
866
867 void Controller::SetPlaceholderTextFontWidth( FontWidth width )
868 {
869   if( NULL != mImpl->mEventData )
870   {
871     if( NULL == mImpl->mEventData->mPlaceholderFont )
872     {
873       mImpl->mEventData->mPlaceholderFont = new FontDefaults();
874     }
875
876     mImpl->mEventData->mPlaceholderFont->mFontDescription.width = width;
877     mImpl->mEventData->mPlaceholderFont->widthDefined = true;
878
879     mImpl->RequestRelayout();
880   }
881 }
882
883 bool Controller::IsPlaceholderTextFontWidthDefined() const
884 {
885   if( ( NULL != mImpl->mEventData ) && ( NULL != mImpl->mEventData->mPlaceholderFont ) )
886   {
887     return mImpl->mEventData->mPlaceholderFont->widthDefined;
888   }
889   return false;
890 }
891
892 FontWidth Controller::GetPlaceholderTextFontWidth() const
893 {
894   if( ( NULL != mImpl->mEventData ) && ( NULL != mImpl->mEventData->mPlaceholderFont ) )
895   {
896     return mImpl->mEventData->mPlaceholderFont->mFontDescription.width;
897   }
898
899   return TextAbstraction::FontWidth::NORMAL;
900 }
901
902 void Controller::SetDefaultFontSlant( FontSlant slant )
903 {
904   if( NULL == mImpl->mFontDefaults )
905   {
906     mImpl->mFontDefaults = new FontDefaults();
907   }
908
909   mImpl->mFontDefaults->mFontDescription.slant = slant;
910   mImpl->mFontDefaults->slantDefined = true;
911
912   // Clear the font-specific data
913   ClearFontData();
914
915   mImpl->RequestRelayout();
916 }
917
918 bool Controller::IsDefaultFontSlantDefined() const
919 {
920   if( NULL != mImpl->mFontDefaults )
921   {
922     return mImpl->mFontDefaults->slantDefined;
923   }
924   return false;
925 }
926
927 FontSlant Controller::GetDefaultFontSlant() const
928 {
929   if( NULL != mImpl->mFontDefaults )
930   {
931     return mImpl->mFontDefaults->mFontDescription.slant;
932   }
933
934   return TextAbstraction::FontSlant::NORMAL;
935 }
936
937 void Controller::SetPlaceholderTextFontSlant( FontSlant slant )
938 {
939   if( NULL != mImpl->mEventData )
940   {
941     if( NULL == mImpl->mEventData->mPlaceholderFont )
942     {
943       mImpl->mEventData->mPlaceholderFont = new FontDefaults();
944     }
945
946     mImpl->mEventData->mPlaceholderFont->mFontDescription.slant = slant;
947     mImpl->mEventData->mPlaceholderFont->slantDefined = true;
948
949     mImpl->RequestRelayout();
950   }
951 }
952
953 bool Controller::IsPlaceholderTextFontSlantDefined() const
954 {
955   if( ( NULL != mImpl->mEventData ) && ( NULL != mImpl->mEventData->mPlaceholderFont ) )
956   {
957     return mImpl->mEventData->mPlaceholderFont->slantDefined;
958   }
959   return false;
960 }
961
962 FontSlant Controller::GetPlaceholderTextFontSlant() const
963 {
964   if( ( NULL != mImpl->mEventData ) && ( NULL != mImpl->mEventData->mPlaceholderFont ) )
965   {
966     return mImpl->mEventData->mPlaceholderFont->mFontDescription.slant;
967   }
968
969   return TextAbstraction::FontSlant::NORMAL;
970 }
971
972 void Controller::SetDefaultFontSize( float fontSize, FontSizeType type )
973 {
974   if( NULL == mImpl->mFontDefaults )
975   {
976     mImpl->mFontDefaults = new FontDefaults();
977   }
978
979   switch( type )
980   {
981     case POINT_SIZE:
982     {
983       mImpl->mFontDefaults->mDefaultPointSize = fontSize;
984       mImpl->mFontDefaults->sizeDefined = true;
985       break;
986     }
987     case PIXEL_SIZE:
988     {
989       // Point size = Pixel size * 72.f / DPI
990       unsigned int horizontalDpi = 0u;
991       unsigned int verticalDpi = 0u;
992       TextAbstraction::FontClient fontClient = TextAbstraction::FontClient::Get();
993       fontClient.GetDpi( horizontalDpi, verticalDpi );
994
995       mImpl->mFontDefaults->mDefaultPointSize = ( fontSize * 72.f ) / static_cast< float >( horizontalDpi );
996       mImpl->mFontDefaults->sizeDefined = true;
997       break;
998     }
999   }
1000
1001   // Clear the font-specific data
1002   ClearFontData();
1003
1004   mImpl->RequestRelayout();
1005 }
1006
1007 float Controller::GetDefaultFontSize( FontSizeType type ) const
1008 {
1009   float value = 0.0f;
1010   if( NULL != mImpl->mFontDefaults )
1011   {
1012     switch( type )
1013     {
1014       case POINT_SIZE:
1015       {
1016         value = mImpl->mFontDefaults->mDefaultPointSize;
1017         break;
1018       }
1019       case PIXEL_SIZE:
1020       {
1021         // Pixel size = Point size * DPI / 72.f
1022         unsigned int horizontalDpi = 0u;
1023         unsigned int verticalDpi = 0u;
1024         TextAbstraction::FontClient fontClient = TextAbstraction::FontClient::Get();
1025         fontClient.GetDpi( horizontalDpi, verticalDpi );
1026
1027         value = mImpl->mFontDefaults->mDefaultPointSize * static_cast< float >( horizontalDpi ) / 72.f;
1028         break;
1029       }
1030     }
1031     return value;
1032   }
1033
1034   return value;
1035 }
1036
1037 void Controller::SetPlaceholderTextFontSize( float fontSize, FontSizeType type )
1038 {
1039   if( NULL != mImpl->mEventData )
1040   {
1041     if( NULL == mImpl->mEventData->mPlaceholderFont )
1042     {
1043       mImpl->mEventData->mPlaceholderFont = new FontDefaults();
1044     }
1045
1046     switch( type )
1047     {
1048       case POINT_SIZE:
1049       {
1050         mImpl->mEventData->mPlaceholderFont->mDefaultPointSize = fontSize;
1051         mImpl->mEventData->mPlaceholderFont->sizeDefined = true;
1052         mImpl->mEventData->mIsPlaceholderPixelSize = false; // Font size flag
1053         break;
1054       }
1055       case PIXEL_SIZE:
1056       {
1057         // Point size = Pixel size * 72.f / DPI
1058         unsigned int horizontalDpi = 0u;
1059         unsigned int verticalDpi = 0u;
1060         TextAbstraction::FontClient fontClient = TextAbstraction::FontClient::Get();
1061         fontClient.GetDpi( horizontalDpi, verticalDpi );
1062
1063         mImpl->mEventData->mPlaceholderFont->mDefaultPointSize = ( fontSize * 72.f ) / static_cast< float >( horizontalDpi );
1064         mImpl->mEventData->mPlaceholderFont->sizeDefined = true;
1065         mImpl->mEventData->mIsPlaceholderPixelSize = true; // Font size flag
1066         break;
1067       }
1068     }
1069
1070     mImpl->RequestRelayout();
1071   }
1072 }
1073
1074 float Controller::GetPlaceholderTextFontSize( FontSizeType type ) const
1075 {
1076   float value = 0.0f;
1077   if( NULL != mImpl->mEventData )
1078   {
1079     switch( type )
1080     {
1081       case POINT_SIZE:
1082       {
1083         if( NULL != mImpl->mEventData->mPlaceholderFont )
1084         {
1085           value = mImpl->mEventData->mPlaceholderFont->mDefaultPointSize;
1086         }
1087         else
1088         {
1089           // If the placeholder text font size is not set, then return the default font size.
1090           value = GetDefaultFontSize( POINT_SIZE );
1091         }
1092         break;
1093       }
1094       case PIXEL_SIZE:
1095       {
1096         if( NULL != mImpl->mEventData->mPlaceholderFont )
1097         {
1098           // Pixel size = Point size * DPI / 72.f
1099           unsigned int horizontalDpi = 0u;
1100           unsigned int verticalDpi = 0u;
1101           TextAbstraction::FontClient fontClient = TextAbstraction::FontClient::Get();
1102           fontClient.GetDpi( horizontalDpi, verticalDpi );
1103
1104           value = mImpl->mEventData->mPlaceholderFont->mDefaultPointSize * static_cast< float >( horizontalDpi ) / 72.f;
1105         }
1106         else
1107         {
1108           // If the placeholder text font size is not set, then return the default font size.
1109           value = GetDefaultFontSize( PIXEL_SIZE );
1110         }
1111         break;
1112       }
1113     }
1114     return value;
1115   }
1116
1117   return value;
1118 }
1119
1120 void Controller::SetDefaultColor( const Vector4& color )
1121 {
1122   mImpl->mTextColor = color;
1123
1124   if( !mImpl->IsShowingPlaceholderText() )
1125   {
1126     mImpl->mModel->mVisualModel->SetTextColor( color );
1127
1128     mImpl->RequestRelayout();
1129   }
1130 }
1131
1132 const Vector4& Controller::GetDefaultColor() const
1133 {
1134   return mImpl->mTextColor;
1135 }
1136
1137 void Controller::SetPlaceholderTextColor( const Vector4& textColor )
1138 {
1139   if( NULL != mImpl->mEventData )
1140   {
1141     mImpl->mEventData->mPlaceholderTextColor = textColor;
1142   }
1143
1144   if( mImpl->IsShowingPlaceholderText() )
1145   {
1146     mImpl->mModel->mVisualModel->SetTextColor( textColor );
1147     mImpl->RequestRelayout();
1148   }
1149 }
1150
1151 const Vector4& Controller::GetPlaceholderTextColor() const
1152 {
1153   if( NULL != mImpl->mEventData )
1154   {
1155     return mImpl->mEventData->mPlaceholderTextColor;
1156   }
1157
1158   return Color::BLACK;
1159 }
1160
1161 void Controller::SetShadowOffset( const Vector2& shadowOffset )
1162 {
1163   mImpl->mModel->mVisualModel->SetShadowOffset( shadowOffset );
1164
1165   mImpl->RequestRelayout();
1166 }
1167
1168 const Vector2& Controller::GetShadowOffset() const
1169 {
1170   return mImpl->mModel->mVisualModel->GetShadowOffset();
1171 }
1172
1173 void Controller::SetShadowColor( const Vector4& shadowColor )
1174 {
1175   mImpl->mModel->mVisualModel->SetShadowColor( shadowColor );
1176
1177   mImpl->RequestRelayout();
1178 }
1179
1180 const Vector4& Controller::GetShadowColor() const
1181 {
1182   return mImpl->mModel->mVisualModel->GetShadowColor();
1183 }
1184
1185 void Controller::SetShadowBlurRadius( const float& shadowBlurRadius )
1186 {
1187   if ( fabsf( GetShadowBlurRadius() - shadowBlurRadius ) > Math::MACHINE_EPSILON_1 )
1188   {
1189     mImpl->mModel->mVisualModel->SetShadowBlurRadius( shadowBlurRadius );
1190
1191     mImpl->RequestRelayout();
1192   }
1193 }
1194
1195 const float& Controller::GetShadowBlurRadius() const
1196 {
1197   return mImpl->mModel->mVisualModel->GetShadowBlurRadius();
1198 }
1199
1200 void Controller::SetUnderlineColor( const Vector4& color )
1201 {
1202   mImpl->mModel->mVisualModel->SetUnderlineColor( color );
1203
1204   mImpl->RequestRelayout();
1205 }
1206
1207 const Vector4& Controller::GetUnderlineColor() const
1208 {
1209   return mImpl->mModel->mVisualModel->GetUnderlineColor();
1210 }
1211
1212 void Controller::SetUnderlineEnabled( bool enabled )
1213 {
1214   mImpl->mModel->mVisualModel->SetUnderlineEnabled( enabled );
1215
1216   mImpl->RequestRelayout();
1217 }
1218
1219 bool Controller::IsUnderlineEnabled() const
1220 {
1221   return mImpl->mModel->mVisualModel->IsUnderlineEnabled();
1222 }
1223
1224 void Controller::SetUnderlineHeight( float height )
1225 {
1226   mImpl->mModel->mVisualModel->SetUnderlineHeight( height );
1227
1228   mImpl->RequestRelayout();
1229 }
1230
1231 float Controller::GetUnderlineHeight() const
1232 {
1233   return mImpl->mModel->mVisualModel->GetUnderlineHeight();
1234 }
1235
1236 void Controller::SetOutlineColor( const Vector4& color )
1237 {
1238   mImpl->mModel->mVisualModel->SetOutlineColor( color );
1239
1240   mImpl->RequestRelayout();
1241 }
1242
1243 const Vector4& Controller::GetOutlineColor() const
1244 {
1245   return mImpl->mModel->mVisualModel->GetOutlineColor();
1246 }
1247
1248 void Controller::SetOutlineWidth( unsigned int width )
1249 {
1250   mImpl->mModel->mVisualModel->SetOutlineWidth( width );
1251
1252   mImpl->RequestRelayout();
1253 }
1254
1255 unsigned int Controller::GetOutlineWidth() const
1256 {
1257   return mImpl->mModel->mVisualModel->GetOutlineWidth();
1258 }
1259
1260 void Controller::SetBackgroundColor( const Vector4& color )
1261 {
1262   mImpl->mModel->mVisualModel->SetBackgroundColor( color );
1263
1264   mImpl->RequestRelayout();
1265 }
1266
1267 const Vector4& Controller::GetBackgroundColor() const
1268 {
1269   return mImpl->mModel->mVisualModel->GetBackgroundColor();
1270 }
1271
1272 void Controller::SetBackgroundEnabled( bool enabled )
1273 {
1274   mImpl->mModel->mVisualModel->SetBackgroundEnabled( enabled );
1275
1276   mImpl->RequestRelayout();
1277 }
1278
1279 bool Controller::IsBackgroundEnabled() const
1280 {
1281   return mImpl->mModel->mVisualModel->IsBackgroundEnabled();
1282 }
1283
1284 void Controller::SetDefaultEmbossProperties( const std::string& embossProperties )
1285 {
1286   if( NULL == mImpl->mEmbossDefaults )
1287   {
1288     mImpl->mEmbossDefaults = new EmbossDefaults();
1289   }
1290
1291   mImpl->mEmbossDefaults->properties = embossProperties;
1292 }
1293
1294 const std::string& Controller::GetDefaultEmbossProperties() const
1295 {
1296   if( NULL != mImpl->mEmbossDefaults )
1297   {
1298     return mImpl->mEmbossDefaults->properties;
1299   }
1300
1301   return EMPTY_STRING;
1302 }
1303
1304 void Controller::SetDefaultOutlineProperties( const std::string& outlineProperties )
1305 {
1306   if( NULL == mImpl->mOutlineDefaults )
1307   {
1308     mImpl->mOutlineDefaults = new OutlineDefaults();
1309   }
1310
1311   mImpl->mOutlineDefaults->properties = outlineProperties;
1312 }
1313
1314 const std::string& Controller::GetDefaultOutlineProperties() const
1315 {
1316   if( NULL != mImpl->mOutlineDefaults )
1317   {
1318     return mImpl->mOutlineDefaults->properties;
1319   }
1320
1321   return EMPTY_STRING;
1322 }
1323
1324 bool Controller::SetDefaultLineSpacing( float lineSpacing )
1325 {
1326   if( std::abs(lineSpacing - mImpl->mLayoutEngine.GetDefaultLineSpacing()) > Math::MACHINE_EPSILON_1000 )
1327   {
1328     mImpl->mLayoutEngine.SetDefaultLineSpacing(lineSpacing);
1329     mImpl->mRecalculateNaturalSize = true;
1330     return true;
1331   }
1332   return false;
1333 }
1334
1335 float Controller::GetDefaultLineSpacing() const
1336 {
1337   return mImpl->mLayoutEngine.GetDefaultLineSpacing();
1338 }
1339
1340 void Controller::SetInputColor( const Vector4& color )
1341 {
1342   if( NULL != mImpl->mEventData )
1343   {
1344     mImpl->mEventData->mInputStyle.textColor = color;
1345     mImpl->mEventData->mInputStyle.isDefaultColor = false;
1346
1347     if( EventData::SELECTING == mImpl->mEventData->mState )
1348     {
1349       const bool handlesCrossed = mImpl->mEventData->mLeftSelectionPosition > mImpl->mEventData->mRightSelectionPosition;
1350
1351       // Get start and end position of selection
1352       const CharacterIndex startOfSelectedText = handlesCrossed ? mImpl->mEventData->mRightSelectionPosition : mImpl->mEventData->mLeftSelectionPosition;
1353       const Length lengthOfSelectedText = ( handlesCrossed ? mImpl->mEventData->mLeftSelectionPosition : mImpl->mEventData->mRightSelectionPosition ) - startOfSelectedText;
1354
1355       // Add the color run.
1356       const VectorBase::SizeType numberOfRuns = mImpl->mModel->mLogicalModel->mColorRuns.Count();
1357       mImpl->mModel->mLogicalModel->mColorRuns.Resize( numberOfRuns + 1u );
1358
1359       ColorRun& colorRun = *( mImpl->mModel->mLogicalModel->mColorRuns.Begin() + numberOfRuns );
1360       colorRun.color = color;
1361       colorRun.characterRun.characterIndex = startOfSelectedText;
1362       colorRun.characterRun.numberOfCharacters = lengthOfSelectedText;
1363
1364       // Request to relayout.
1365       mImpl->mOperationsPending = static_cast<OperationsMask>( mImpl->mOperationsPending | COLOR );
1366       mImpl->RequestRelayout();
1367
1368       mImpl->mTextUpdateInfo.mCharacterIndex = startOfSelectedText;
1369       mImpl->mTextUpdateInfo.mNumberOfCharactersToRemove = lengthOfSelectedText;
1370       mImpl->mTextUpdateInfo.mNumberOfCharactersToAdd = lengthOfSelectedText;
1371     }
1372   }
1373 }
1374
1375 const Vector4& Controller::GetInputColor() const
1376 {
1377   if( NULL != mImpl->mEventData )
1378   {
1379     return mImpl->mEventData->mInputStyle.textColor;
1380   }
1381
1382   // Return the default text's color if there is no EventData.
1383   return mImpl->mTextColor;
1384
1385 }
1386
1387 void Controller::SetInputFontFamily( const std::string& fontFamily )
1388 {
1389   if( NULL != mImpl->mEventData )
1390   {
1391     mImpl->mEventData->mInputStyle.familyName = fontFamily;
1392     mImpl->mEventData->mInputStyle.isFamilyDefined = true;
1393
1394     if( EventData::SELECTING == mImpl->mEventData->mState )
1395     {
1396       CharacterIndex startOfSelectedText = 0u;
1397       Length lengthOfSelectedText = 0u;
1398       FontDescriptionRun& fontDescriptionRun = UpdateSelectionFontStyleRun( mImpl->mEventData,
1399                                                                             mImpl->mModel->mLogicalModel,
1400                                                                             startOfSelectedText,
1401                                                                             lengthOfSelectedText );
1402
1403       fontDescriptionRun.familyLength = fontFamily.size();
1404       fontDescriptionRun.familyName = new char[fontDescriptionRun.familyLength];
1405       memcpy( fontDescriptionRun.familyName, fontFamily.c_str(), fontDescriptionRun.familyLength );
1406       fontDescriptionRun.familyDefined = true;
1407
1408       // The memory allocated for the font family name is freed when the font description is removed from the logical model.
1409
1410       // Request to relayout.
1411       mImpl->mOperationsPending = static_cast<OperationsMask>( mImpl->mOperationsPending |
1412                                                                VALIDATE_FONTS            |
1413                                                                SHAPE_TEXT                |
1414                                                                GET_GLYPH_METRICS         |
1415                                                                LAYOUT                    |
1416                                                                UPDATE_LAYOUT_SIZE        |
1417                                                                REORDER                   |
1418                                                                ALIGN );
1419       mImpl->mRecalculateNaturalSize = true;
1420       mImpl->RequestRelayout();
1421
1422       mImpl->mTextUpdateInfo.mCharacterIndex = startOfSelectedText;
1423       mImpl->mTextUpdateInfo.mNumberOfCharactersToRemove = lengthOfSelectedText;
1424       mImpl->mTextUpdateInfo.mNumberOfCharactersToAdd = lengthOfSelectedText;
1425
1426       // As the font changes, recalculate the handle positions is needed.
1427       mImpl->mEventData->mUpdateLeftSelectionPosition = true;
1428       mImpl->mEventData->mUpdateRightSelectionPosition = true;
1429       mImpl->mEventData->mUpdateHighlightBox = true;
1430       mImpl->mEventData->mScrollAfterUpdatePosition = true;
1431     }
1432   }
1433 }
1434
1435 const std::string& Controller::GetInputFontFamily() const
1436 {
1437   if( NULL != mImpl->mEventData )
1438   {
1439     return mImpl->mEventData->mInputStyle.familyName;
1440   }
1441
1442   // Return the default font's family if there is no EventData.
1443   return GetDefaultFontFamily();
1444 }
1445
1446 void Controller::SetInputFontWeight( FontWeight weight )
1447 {
1448   if( NULL != mImpl->mEventData )
1449   {
1450     mImpl->mEventData->mInputStyle.weight = weight;
1451     mImpl->mEventData->mInputStyle.isWeightDefined = true;
1452
1453     if( EventData::SELECTING == mImpl->mEventData->mState )
1454     {
1455       CharacterIndex startOfSelectedText = 0u;
1456       Length lengthOfSelectedText = 0u;
1457       FontDescriptionRun& fontDescriptionRun = UpdateSelectionFontStyleRun( mImpl->mEventData,
1458                                                                             mImpl->mModel->mLogicalModel,
1459                                                                             startOfSelectedText,
1460                                                                             lengthOfSelectedText );
1461
1462       fontDescriptionRun.weight = weight;
1463       fontDescriptionRun.weightDefined = true;
1464
1465       // Request to relayout.
1466       mImpl->mOperationsPending = static_cast<OperationsMask>( mImpl->mOperationsPending |
1467                                                                VALIDATE_FONTS            |
1468                                                                SHAPE_TEXT                |
1469                                                                GET_GLYPH_METRICS         |
1470                                                                LAYOUT                    |
1471                                                                UPDATE_LAYOUT_SIZE        |
1472                                                                REORDER                   |
1473                                                                ALIGN );
1474       mImpl->mRecalculateNaturalSize = true;
1475       mImpl->RequestRelayout();
1476
1477       mImpl->mTextUpdateInfo.mCharacterIndex = startOfSelectedText;
1478       mImpl->mTextUpdateInfo.mNumberOfCharactersToRemove = lengthOfSelectedText;
1479       mImpl->mTextUpdateInfo.mNumberOfCharactersToAdd = lengthOfSelectedText;
1480
1481       // As the font might change, recalculate the handle positions is needed.
1482       mImpl->mEventData->mUpdateLeftSelectionPosition = true;
1483       mImpl->mEventData->mUpdateRightSelectionPosition = true;
1484       mImpl->mEventData->mUpdateHighlightBox = true;
1485       mImpl->mEventData->mScrollAfterUpdatePosition = true;
1486     }
1487   }
1488 }
1489
1490 bool Controller::IsInputFontWeightDefined() const
1491 {
1492   bool defined = false;
1493
1494   if( NULL != mImpl->mEventData )
1495   {
1496     defined = mImpl->mEventData->mInputStyle.isWeightDefined;
1497   }
1498
1499   return defined;
1500 }
1501
1502 FontWeight Controller::GetInputFontWeight() const
1503 {
1504   if( NULL != mImpl->mEventData )
1505   {
1506     return mImpl->mEventData->mInputStyle.weight;
1507   }
1508
1509   return GetDefaultFontWeight();
1510 }
1511
1512 void Controller::SetInputFontWidth( FontWidth width )
1513 {
1514   if( NULL != mImpl->mEventData )
1515   {
1516     mImpl->mEventData->mInputStyle.width = width;
1517     mImpl->mEventData->mInputStyle.isWidthDefined = true;
1518
1519     if( EventData::SELECTING == mImpl->mEventData->mState )
1520     {
1521       CharacterIndex startOfSelectedText = 0u;
1522       Length lengthOfSelectedText = 0u;
1523       FontDescriptionRun& fontDescriptionRun = UpdateSelectionFontStyleRun( mImpl->mEventData,
1524                                                                             mImpl->mModel->mLogicalModel,
1525                                                                             startOfSelectedText,
1526                                                                             lengthOfSelectedText );
1527
1528       fontDescriptionRun.width = width;
1529       fontDescriptionRun.widthDefined = true;
1530
1531       // Request to relayout.
1532       mImpl->mOperationsPending = static_cast<OperationsMask>( mImpl->mOperationsPending |
1533                                                                VALIDATE_FONTS            |
1534                                                                SHAPE_TEXT                |
1535                                                                GET_GLYPH_METRICS         |
1536                                                                LAYOUT                    |
1537                                                                UPDATE_LAYOUT_SIZE        |
1538                                                                REORDER                   |
1539                                                                ALIGN );
1540       mImpl->mRecalculateNaturalSize = true;
1541       mImpl->RequestRelayout();
1542
1543       mImpl->mTextUpdateInfo.mCharacterIndex = startOfSelectedText;
1544       mImpl->mTextUpdateInfo.mNumberOfCharactersToRemove = lengthOfSelectedText;
1545       mImpl->mTextUpdateInfo.mNumberOfCharactersToAdd = lengthOfSelectedText;
1546
1547       // As the font might change, recalculate the handle positions is needed.
1548       mImpl->mEventData->mUpdateLeftSelectionPosition = true;
1549       mImpl->mEventData->mUpdateRightSelectionPosition = true;
1550       mImpl->mEventData->mUpdateHighlightBox = true;
1551       mImpl->mEventData->mScrollAfterUpdatePosition = true;
1552     }
1553   }
1554 }
1555
1556 bool Controller::IsInputFontWidthDefined() const
1557 {
1558   bool defined = false;
1559
1560   if( NULL != mImpl->mEventData )
1561   {
1562     defined = mImpl->mEventData->mInputStyle.isWidthDefined;
1563   }
1564
1565   return defined;
1566 }
1567
1568 FontWidth Controller::GetInputFontWidth() const
1569 {
1570   if( NULL != mImpl->mEventData )
1571   {
1572     return mImpl->mEventData->mInputStyle.width;
1573   }
1574
1575   return GetDefaultFontWidth();
1576 }
1577
1578 void Controller::SetInputFontSlant( FontSlant slant )
1579 {
1580   if( NULL != mImpl->mEventData )
1581   {
1582     mImpl->mEventData->mInputStyle.slant = slant;
1583     mImpl->mEventData->mInputStyle.isSlantDefined = true;
1584
1585     if( EventData::SELECTING == mImpl->mEventData->mState )
1586     {
1587       CharacterIndex startOfSelectedText = 0u;
1588       Length lengthOfSelectedText = 0u;
1589       FontDescriptionRun& fontDescriptionRun = UpdateSelectionFontStyleRun( mImpl->mEventData,
1590                                                                             mImpl->mModel->mLogicalModel,
1591                                                                             startOfSelectedText,
1592                                                                             lengthOfSelectedText );
1593
1594       fontDescriptionRun.slant = slant;
1595       fontDescriptionRun.slantDefined = true;
1596
1597       // Request to relayout.
1598       mImpl->mOperationsPending = static_cast<OperationsMask>( mImpl->mOperationsPending |
1599                                                                VALIDATE_FONTS            |
1600                                                                SHAPE_TEXT                |
1601                                                                GET_GLYPH_METRICS         |
1602                                                                LAYOUT                    |
1603                                                                UPDATE_LAYOUT_SIZE        |
1604                                                                REORDER                   |
1605                                                                ALIGN );
1606       mImpl->mRecalculateNaturalSize = true;
1607       mImpl->RequestRelayout();
1608
1609       mImpl->mTextUpdateInfo.mCharacterIndex = startOfSelectedText;
1610       mImpl->mTextUpdateInfo.mNumberOfCharactersToRemove = lengthOfSelectedText;
1611       mImpl->mTextUpdateInfo.mNumberOfCharactersToAdd = lengthOfSelectedText;
1612
1613       // As the font might change, recalculate the handle positions is needed.
1614       mImpl->mEventData->mUpdateLeftSelectionPosition = true;
1615       mImpl->mEventData->mUpdateRightSelectionPosition = true;
1616       mImpl->mEventData->mUpdateHighlightBox = true;
1617       mImpl->mEventData->mScrollAfterUpdatePosition = true;
1618     }
1619   }
1620 }
1621
1622 bool Controller::IsInputFontSlantDefined() const
1623 {
1624   bool defined = false;
1625
1626   if( NULL != mImpl->mEventData )
1627   {
1628     defined = mImpl->mEventData->mInputStyle.isSlantDefined;
1629   }
1630
1631   return defined;
1632 }
1633
1634 FontSlant Controller::GetInputFontSlant() const
1635 {
1636   if( NULL != mImpl->mEventData )
1637   {
1638     return mImpl->mEventData->mInputStyle.slant;
1639   }
1640
1641   return GetDefaultFontSlant();
1642 }
1643
1644 void Controller::SetInputFontPointSize( float size )
1645 {
1646   if( NULL != mImpl->mEventData )
1647   {
1648     mImpl->mEventData->mInputStyle.size = size;
1649     mImpl->mEventData->mInputStyle.isSizeDefined = true;
1650
1651     if( EventData::SELECTING == mImpl->mEventData->mState )
1652     {
1653       CharacterIndex startOfSelectedText = 0u;
1654       Length lengthOfSelectedText = 0u;
1655       FontDescriptionRun& fontDescriptionRun = UpdateSelectionFontStyleRun( mImpl->mEventData,
1656                                                                             mImpl->mModel->mLogicalModel,
1657                                                                             startOfSelectedText,
1658                                                                             lengthOfSelectedText );
1659
1660       fontDescriptionRun.size = static_cast<PointSize26Dot6>( size * 64.f );
1661       fontDescriptionRun.sizeDefined = true;
1662
1663       // Request to relayout.
1664       mImpl->mOperationsPending = static_cast<OperationsMask>( mImpl->mOperationsPending |
1665                                                                VALIDATE_FONTS            |
1666                                                                SHAPE_TEXT                |
1667                                                                GET_GLYPH_METRICS         |
1668                                                                LAYOUT                    |
1669                                                                UPDATE_LAYOUT_SIZE        |
1670                                                                REORDER                   |
1671                                                                ALIGN );
1672       mImpl->mRecalculateNaturalSize = true;
1673       mImpl->RequestRelayout();
1674
1675       mImpl->mTextUpdateInfo.mCharacterIndex = startOfSelectedText;
1676       mImpl->mTextUpdateInfo.mNumberOfCharactersToRemove = lengthOfSelectedText;
1677       mImpl->mTextUpdateInfo.mNumberOfCharactersToAdd = lengthOfSelectedText;
1678
1679       // As the font might change, recalculate the handle positions is needed.
1680       mImpl->mEventData->mUpdateLeftSelectionPosition = true;
1681       mImpl->mEventData->mUpdateRightSelectionPosition = true;
1682       mImpl->mEventData->mUpdateHighlightBox = true;
1683       mImpl->mEventData->mScrollAfterUpdatePosition = true;
1684     }
1685   }
1686 }
1687
1688 float Controller::GetInputFontPointSize() const
1689 {
1690   if( NULL != mImpl->mEventData )
1691   {
1692     return mImpl->mEventData->mInputStyle.size;
1693   }
1694
1695   // Return the default font's point size if there is no EventData.
1696   return GetDefaultFontSize( Text::Controller::POINT_SIZE );
1697 }
1698
1699 void Controller::SetInputLineSpacing( float lineSpacing )
1700 {
1701   if( NULL != mImpl->mEventData )
1702   {
1703     mImpl->mEventData->mInputStyle.lineSpacing = lineSpacing;
1704     mImpl->mEventData->mInputStyle.isLineSpacingDefined = true;
1705   }
1706 }
1707
1708 float Controller::GetInputLineSpacing() const
1709 {
1710   if( NULL != mImpl->mEventData )
1711   {
1712     return mImpl->mEventData->mInputStyle.lineSpacing;
1713   }
1714
1715   return 0.f;
1716 }
1717
1718 void Controller::SetInputShadowProperties( const std::string& shadowProperties )
1719 {
1720   if( NULL != mImpl->mEventData )
1721   {
1722     mImpl->mEventData->mInputStyle.shadowProperties = shadowProperties;
1723   }
1724 }
1725
1726 const std::string& Controller::GetInputShadowProperties() const
1727 {
1728   if( NULL != mImpl->mEventData )
1729   {
1730     return mImpl->mEventData->mInputStyle.shadowProperties;
1731   }
1732
1733   return EMPTY_STRING;
1734 }
1735
1736 void Controller::SetInputUnderlineProperties( const std::string& underlineProperties )
1737 {
1738   if( NULL != mImpl->mEventData )
1739   {
1740     mImpl->mEventData->mInputStyle.underlineProperties = underlineProperties;
1741   }
1742 }
1743
1744 const std::string& Controller::GetInputUnderlineProperties() const
1745 {
1746   if( NULL != mImpl->mEventData )
1747   {
1748     return mImpl->mEventData->mInputStyle.underlineProperties;
1749   }
1750
1751   return EMPTY_STRING;
1752 }
1753
1754 void Controller::SetInputEmbossProperties( const std::string& embossProperties )
1755 {
1756   if( NULL != mImpl->mEventData )
1757   {
1758     mImpl->mEventData->mInputStyle.embossProperties = embossProperties;
1759   }
1760 }
1761
1762 const std::string& Controller::GetInputEmbossProperties() const
1763 {
1764   if( NULL != mImpl->mEventData )
1765   {
1766     return mImpl->mEventData->mInputStyle.embossProperties;
1767   }
1768
1769   return GetDefaultEmbossProperties();
1770 }
1771
1772 void Controller::SetInputOutlineProperties( const std::string& outlineProperties )
1773 {
1774   if( NULL != mImpl->mEventData )
1775   {
1776     mImpl->mEventData->mInputStyle.outlineProperties = outlineProperties;
1777   }
1778 }
1779
1780 const std::string& Controller::GetInputOutlineProperties() const
1781 {
1782   if( NULL != mImpl->mEventData )
1783   {
1784     return mImpl->mEventData->mInputStyle.outlineProperties;
1785   }
1786
1787   return GetDefaultOutlineProperties();
1788 }
1789
1790 void Controller::SetInputModePassword( bool passwordInput )
1791 {
1792   if( NULL != mImpl->mEventData )
1793   {
1794     mImpl->mEventData->mPasswordInput = passwordInput;
1795   }
1796 }
1797
1798 bool Controller::IsInputModePassword()
1799 {
1800   if( NULL != mImpl->mEventData )
1801   {
1802     return mImpl->mEventData->mPasswordInput;
1803   }
1804   return false;
1805 }
1806
1807 void Controller::SetNoTextDoubleTapAction( NoTextTap::Action action )
1808 {
1809   if( NULL != mImpl->mEventData )
1810   {
1811     mImpl->mEventData->mDoubleTapAction = action;
1812   }
1813 }
1814
1815 Controller::NoTextTap::Action Controller::GetNoTextDoubleTapAction() const
1816 {
1817   NoTextTap::Action action = NoTextTap::NO_ACTION;
1818
1819   if( NULL != mImpl->mEventData )
1820   {
1821     action = mImpl->mEventData->mDoubleTapAction;
1822   }
1823
1824   return action;
1825 }
1826
1827 void Controller::SetNoTextLongPressAction( NoTextTap::Action action )
1828 {
1829   if( NULL != mImpl->mEventData )
1830   {
1831     mImpl->mEventData->mLongPressAction = action;
1832   }
1833 }
1834
1835 Controller::NoTextTap::Action Controller::GetNoTextLongPressAction() const
1836 {
1837   NoTextTap::Action action = NoTextTap::NO_ACTION;
1838
1839   if( NULL != mImpl->mEventData )
1840   {
1841     action = mImpl->mEventData->mLongPressAction;
1842   }
1843
1844   return action;
1845 }
1846
1847 bool Controller::IsUnderlineSetByString()
1848 {
1849   return mImpl->mUnderlineSetByString;
1850 }
1851
1852 void Controller::UnderlineSetByString( bool setByString )
1853 {
1854   mImpl->mUnderlineSetByString = setByString;
1855 }
1856
1857 bool Controller::IsShadowSetByString()
1858 {
1859   return mImpl->mShadowSetByString;
1860 }
1861
1862 void Controller::ShadowSetByString( bool setByString )
1863 {
1864   mImpl->mShadowSetByString = setByString;
1865 }
1866
1867 bool Controller::IsOutlineSetByString()
1868 {
1869   return mImpl->mOutlineSetByString;
1870 }
1871
1872 void Controller::OutlineSetByString( bool setByString )
1873 {
1874   mImpl->mOutlineSetByString = setByString;
1875 }
1876
1877 bool Controller::IsFontStyleSetByString()
1878 {
1879   return mImpl->mFontStyleSetByString;
1880 }
1881
1882 void Controller::FontStyleSetByString( bool setByString )
1883 {
1884   mImpl->mFontStyleSetByString = setByString;
1885 }
1886
1887 // public : Queries & retrieves.
1888
1889 Layout::Engine& Controller::GetLayoutEngine()
1890 {
1891   return mImpl->mLayoutEngine;
1892 }
1893
1894 View& Controller::GetView()
1895 {
1896   return mImpl->mView;
1897 }
1898
1899 Vector3 Controller::GetNaturalSize()
1900 {
1901   DALI_LOG_INFO( gLogFilter, Debug::Verbose, "-->Controller::GetNaturalSize\n" );
1902   Vector3 naturalSize;
1903
1904   // Make sure the model is up-to-date before layouting
1905   ProcessModifyEvents();
1906
1907   if( mImpl->mRecalculateNaturalSize )
1908   {
1909     // Operations that can be done only once until the text changes.
1910     const OperationsMask onlyOnceOperations = static_cast<OperationsMask>( CONVERT_TO_UTF32  |
1911                                                                            GET_SCRIPTS       |
1912                                                                            VALIDATE_FONTS    |
1913                                                                            GET_LINE_BREAKS   |
1914                                                                            GET_WORD_BREAKS   |
1915                                                                            BIDI_INFO         |
1916                                                                            SHAPE_TEXT        |
1917                                                                            GET_GLYPH_METRICS );
1918
1919     // Set the update info to relayout the whole text.
1920     mImpl->mTextUpdateInfo.mParagraphCharacterIndex = 0u;
1921     mImpl->mTextUpdateInfo.mRequestedNumberOfCharacters = mImpl->mModel->mLogicalModel->mText.Count();
1922
1923     // Make sure the model is up-to-date before layouting
1924     mImpl->UpdateModel( onlyOnceOperations );
1925
1926     // Layout the text for the new width.
1927     mImpl->mOperationsPending = static_cast<OperationsMask>( mImpl->mOperationsPending | LAYOUT | REORDER );
1928
1929     // Store the actual control's size to restore later.
1930     const Size actualControlSize = mImpl->mModel->mVisualModel->mControlSize;
1931
1932     DoRelayout( Size( MAX_FLOAT, MAX_FLOAT ),
1933                 static_cast<OperationsMask>( onlyOnceOperations |
1934                                              LAYOUT | REORDER ),
1935                 naturalSize.GetVectorXY() );
1936
1937     // Do not do again the only once operations.
1938     mImpl->mOperationsPending = static_cast<OperationsMask>( mImpl->mOperationsPending & ~onlyOnceOperations );
1939
1940     // Do the size related operations again.
1941     const OperationsMask sizeOperations =  static_cast<OperationsMask>( LAYOUT |
1942                                                                         ALIGN  |
1943                                                                         REORDER );
1944     mImpl->mOperationsPending = static_cast<OperationsMask>( mImpl->mOperationsPending | sizeOperations );
1945
1946     // Stores the natural size to avoid recalculate it again
1947     // unless the text/style changes.
1948     mImpl->mModel->mVisualModel->SetNaturalSize( naturalSize.GetVectorXY() );
1949
1950     mImpl->mRecalculateNaturalSize = false;
1951
1952     // Clear the update info. This info will be set the next time the text is updated.
1953     mImpl->mTextUpdateInfo.Clear();
1954     mImpl->mTextUpdateInfo.mClearAll = true;
1955
1956     // Restore the actual control's size.
1957     mImpl->mModel->mVisualModel->mControlSize = actualControlSize;
1958
1959     DALI_LOG_INFO( gLogFilter, Debug::Verbose, "<--Controller::GetNaturalSize calculated %f,%f,%f\n", naturalSize.x, naturalSize.y, naturalSize.z );
1960   }
1961   else
1962   {
1963     naturalSize = mImpl->mModel->mVisualModel->GetNaturalSize();
1964
1965     DALI_LOG_INFO( gLogFilter, Debug::Verbose, "<--Controller::GetNaturalSize cached %f,%f,%f\n", naturalSize.x, naturalSize.y, naturalSize.z );
1966   }
1967
1968   naturalSize.x = ConvertToEven( naturalSize.x );
1969   naturalSize.y = ConvertToEven( naturalSize.y );
1970
1971   return naturalSize;
1972 }
1973
1974 float Controller::GetHeightForWidth( float width )
1975 {
1976   DALI_LOG_INFO( gLogFilter, Debug::Verbose, "-->Controller::GetHeightForWidth %p width %f\n", this, width );
1977   // Make sure the model is up-to-date before layouting
1978   ProcessModifyEvents();
1979
1980   Size layoutSize;
1981   if( fabsf( width - mImpl->mModel->mVisualModel->mControlSize.width ) > Math::MACHINE_EPSILON_1000 ||
1982                                                          mImpl->mTextUpdateInfo.mFullRelayoutNeeded ||
1983                                                          mImpl->mTextUpdateInfo.mClearAll            )
1984   {
1985     // Operations that can be done only once until the text changes.
1986     const OperationsMask onlyOnceOperations = static_cast<OperationsMask>( CONVERT_TO_UTF32  |
1987                                                                            GET_SCRIPTS       |
1988                                                                            VALIDATE_FONTS    |
1989                                                                            GET_LINE_BREAKS   |
1990                                                                            GET_WORD_BREAKS   |
1991                                                                            BIDI_INFO         |
1992                                                                            SHAPE_TEXT        |
1993                                                                            GET_GLYPH_METRICS );
1994
1995     // Set the update info to relayout the whole text.
1996     mImpl->mTextUpdateInfo.mParagraphCharacterIndex = 0u;
1997     mImpl->mTextUpdateInfo.mRequestedNumberOfCharacters = mImpl->mModel->mLogicalModel->mText.Count();
1998
1999     // Make sure the model is up-to-date before layouting
2000     mImpl->UpdateModel( onlyOnceOperations );
2001
2002
2003     // Layout the text for the new width.
2004     mImpl->mOperationsPending = static_cast<OperationsMask>( mImpl->mOperationsPending | LAYOUT );
2005
2006     // Store the actual control's width.
2007     const float actualControlWidth = mImpl->mModel->mVisualModel->mControlSize.width;
2008
2009     DoRelayout( Size( width, MAX_FLOAT ),
2010                 static_cast<OperationsMask>( onlyOnceOperations |
2011                                              LAYOUT ),
2012                 layoutSize );
2013
2014     // Do not do again the only once operations.
2015     mImpl->mOperationsPending = static_cast<OperationsMask>( mImpl->mOperationsPending & ~onlyOnceOperations );
2016
2017     // Do the size related operations again.
2018     const OperationsMask sizeOperations =  static_cast<OperationsMask>( LAYOUT |
2019                                                                         ALIGN  |
2020                                                                         REORDER );
2021
2022     mImpl->mOperationsPending = static_cast<OperationsMask>( mImpl->mOperationsPending | sizeOperations );
2023
2024     // Clear the update info. This info will be set the next time the text is updated.
2025     mImpl->mTextUpdateInfo.Clear();
2026     mImpl->mTextUpdateInfo.mClearAll = true;
2027
2028     // Restore the actual control's width.
2029     mImpl->mModel->mVisualModel->mControlSize.width = actualControlWidth;
2030
2031     DALI_LOG_INFO( gLogFilter, Debug::Verbose, "<--Controller::GetHeightForWidth calculated %f\n", layoutSize.height );
2032   }
2033   else
2034   {
2035     layoutSize = mImpl->mModel->mVisualModel->GetLayoutSize();
2036     DALI_LOG_INFO( gLogFilter, Debug::Verbose, "<--Controller::GetHeightForWidth cached %f\n", layoutSize.height );
2037   }
2038
2039   return layoutSize.height;
2040 }
2041
2042 int Controller::GetLineCount( float width )
2043 {
2044   GetHeightForWidth( width );
2045   int numberofLines = mImpl->mModel->GetNumberOfLines();
2046   return numberofLines;
2047 }
2048
2049 const ModelInterface* const Controller::GetTextModel() const
2050 {
2051   return mImpl->mModel.Get();
2052 }
2053
2054 float Controller::GetScrollAmountByUserInput()
2055 {
2056   float scrollAmount = 0.0f;
2057
2058   if (NULL != mImpl->mEventData && mImpl->mEventData->mCheckScrollAmount)
2059   {
2060     scrollAmount = mImpl->mModel->mScrollPosition.y -  mImpl->mModel->mScrollPositionLast.y;
2061     mImpl->mEventData->mCheckScrollAmount = false;
2062   }
2063   return scrollAmount;
2064 }
2065
2066 bool Controller::GetTextScrollInfo( float& scrollPosition, float& controlHeight, float& layoutHeight )
2067 {
2068   const Vector2& layout = mImpl->mModel->mVisualModel->GetLayoutSize();
2069   bool isScrolled;
2070
2071   controlHeight = mImpl->mModel->mVisualModel->mControlSize.height;
2072   layoutHeight = layout.height;
2073   scrollPosition = mImpl->mModel->mScrollPosition.y;
2074   isScrolled = !Equals( mImpl->mModel->mScrollPosition.y, mImpl->mModel->mScrollPositionLast.y, Math::MACHINE_EPSILON_1 );
2075   return isScrolled;
2076 }
2077
2078 void Controller::SetHiddenInputOption(const Property::Map& options )
2079 {
2080   if( NULL == mImpl->mHiddenInput )
2081   {
2082     mImpl->mHiddenInput = new HiddenText( this );
2083   }
2084   mImpl->mHiddenInput->SetProperties(options);
2085 }
2086
2087 void Controller::GetHiddenInputOption(Property::Map& options )
2088 {
2089   if( NULL != mImpl->mHiddenInput )
2090   {
2091     mImpl->mHiddenInput->GetProperties(options);
2092   }
2093 }
2094
2095 void Controller::SetPlaceholderProperty( const Property::Map& map )
2096 {
2097   const Property::Map::SizeType count = map.Count();
2098
2099   for( Property::Map::SizeType position = 0; position < count; ++position )
2100   {
2101     KeyValuePair keyValue = map.GetKeyValue( position );
2102     Property::Key& key = keyValue.first;
2103     Property::Value& value = keyValue.second;
2104
2105     if( key == Toolkit::Text::PlaceHolder::Property::TEXT  || key == PLACEHOLDER_TEXT )
2106     {
2107       std::string text = "";
2108       value.Get( text );
2109       SetPlaceholderText( Controller::PLACEHOLDER_TYPE_INACTIVE, text );
2110     }
2111     else if( key == Toolkit::Text::PlaceHolder::Property::TEXT_FOCUSED || key == PLACEHOLDER_TEXT_FOCUSED )
2112     {
2113       std::string text = "";
2114       value.Get( text );
2115       SetPlaceholderText( Controller::PLACEHOLDER_TYPE_ACTIVE, text );
2116     }
2117     else if( key == Toolkit::Text::PlaceHolder::Property::COLOR || key == PLACEHOLDER_COLOR )
2118     {
2119       Vector4 textColor;
2120       value.Get( textColor );
2121       if( GetPlaceholderTextColor() != textColor )
2122       {
2123         SetPlaceholderTextColor( textColor );
2124       }
2125     }
2126     else if( key == Toolkit::Text::PlaceHolder::Property::FONT_FAMILY || key == PLACEHOLDER_FONT_FAMILY )
2127     {
2128       std::string fontFamily = "";
2129       value.Get( fontFamily );
2130       SetPlaceholderFontFamily( fontFamily );
2131     }
2132     else if( key == Toolkit::Text::PlaceHolder::Property::FONT_STYLE || key == PLACEHOLDER_FONT_STYLE )
2133     {
2134       SetFontStyleProperty( this, value, Text::FontStyle::PLACEHOLDER );
2135     }
2136     else if( key == Toolkit::Text::PlaceHolder::Property::POINT_SIZE || key == PLACEHOLDER_POINT_SIZE )
2137     {
2138       float pointSize;
2139       value.Get( pointSize );
2140       if( !Equals( GetPlaceholderTextFontSize( Text::Controller::POINT_SIZE ), pointSize ) )
2141       {
2142         SetPlaceholderTextFontSize( pointSize, Text::Controller::POINT_SIZE );
2143       }
2144     }
2145     else if( key == Toolkit::Text::PlaceHolder::Property::PIXEL_SIZE || key == PLACEHOLDER_PIXEL_SIZE )
2146     {
2147       float pixelSize;
2148       value.Get( pixelSize );
2149       if( !Equals( GetPlaceholderTextFontSize( Text::Controller::PIXEL_SIZE ), pixelSize ) )
2150       {
2151         SetPlaceholderTextFontSize( pixelSize, Text::Controller::PIXEL_SIZE );
2152       }
2153     }
2154     else if( key == Toolkit::Text::PlaceHolder::Property::ELLIPSIS || key == PLACEHOLDER_ELLIPSIS )
2155     {
2156       bool ellipsis;
2157       value.Get( ellipsis );
2158       SetPlaceholderTextElideEnabled( ellipsis );
2159     }
2160   }
2161 }
2162
2163 void Controller::GetPlaceholderProperty( Property::Map& map )
2164 {
2165   if( NULL != mImpl->mEventData )
2166   {
2167     if( !mImpl->mEventData->mPlaceholderTextActive.empty() )
2168     {
2169       map[ Text::PlaceHolder::Property::TEXT_FOCUSED ] = mImpl->mEventData->mPlaceholderTextActive;
2170     }
2171     if( !mImpl->mEventData->mPlaceholderTextInactive.empty() )
2172     {
2173       map[ Text::PlaceHolder::Property::TEXT ] = mImpl->mEventData->mPlaceholderTextInactive;
2174     }
2175
2176     map[ Text::PlaceHolder::Property::COLOR ] = mImpl->mEventData->mPlaceholderTextColor;
2177     map[ Text::PlaceHolder::Property::FONT_FAMILY ] = GetPlaceholderFontFamily();
2178
2179     Property::Value fontStyleMapGet;
2180     GetFontStyleProperty( this, fontStyleMapGet, Text::FontStyle::PLACEHOLDER );
2181     map[ Text::PlaceHolder::Property::FONT_STYLE ] = fontStyleMapGet;
2182
2183     // Choose font size : POINT_SIZE or PIXEL_SIZE
2184     if( !mImpl->mEventData->mIsPlaceholderPixelSize )
2185     {
2186       map[ Text::PlaceHolder::Property::POINT_SIZE ] = GetPlaceholderTextFontSize( Text::Controller::POINT_SIZE );
2187     }
2188     else
2189     {
2190       map[ Text::PlaceHolder::Property::PIXEL_SIZE ] = GetPlaceholderTextFontSize( Text::Controller::PIXEL_SIZE );
2191     }
2192
2193     if( mImpl->mEventData->mPlaceholderEllipsisFlag )
2194     {
2195       map[ Text::PlaceHolder::Property::ELLIPSIS ] = IsPlaceholderTextElideEnabled();
2196     }
2197   }
2198 }
2199
2200 Toolkit::DevelText::TextDirection::Type Controller::GetTextDirection()
2201 {
2202   // Make sure the model is up-to-date before layouting
2203   ProcessModifyEvents();
2204
2205   if ( mImpl->mUpdateTextDirection )
2206   {
2207     // Operations that can be done only once until the text changes.
2208     const OperationsMask onlyOnceOperations = static_cast<OperationsMask>( CONVERT_TO_UTF32  |
2209                                                                            GET_SCRIPTS       |
2210                                                                            VALIDATE_FONTS    |
2211                                                                            GET_LINE_BREAKS   |
2212                                                                            GET_WORD_BREAKS   |
2213                                                                            BIDI_INFO         |
2214                                                                            SHAPE_TEXT        |
2215                                                                            GET_GLYPH_METRICS );
2216
2217     // Set the update info to relayout the whole text.
2218     mImpl->mTextUpdateInfo.mParagraphCharacterIndex = 0u;
2219     mImpl->mTextUpdateInfo.mRequestedNumberOfCharacters = mImpl->mModel->mLogicalModel->mText.Count();
2220
2221     // Make sure the model is up-to-date before layouting
2222     mImpl->UpdateModel( onlyOnceOperations );
2223
2224     Vector3 naturalSize;
2225     DoRelayout( Size( MAX_FLOAT, MAX_FLOAT ),
2226                 static_cast<OperationsMask>( onlyOnceOperations |
2227                                              LAYOUT | REORDER | UPDATE_DIRECTION ),
2228                 naturalSize.GetVectorXY() );
2229
2230     // Do not do again the only once operations.
2231     mImpl->mOperationsPending = static_cast<OperationsMask>( mImpl->mOperationsPending & ~onlyOnceOperations );
2232
2233     // Clear the update info. This info will be set the next time the text is updated.
2234     mImpl->mTextUpdateInfo.Clear();
2235
2236     mImpl->mUpdateTextDirection = false;
2237   }
2238
2239   return mImpl->mIsTextDirectionRTL ? Toolkit::DevelText::TextDirection::RIGHT_TO_LEFT : Toolkit::DevelText::TextDirection::LEFT_TO_RIGHT;
2240 }
2241
2242 Toolkit::DevelText::VerticalLineAlignment::Type Controller::GetVerticalLineAlignment() const
2243 {
2244   return mImpl->mModel->GetVerticalLineAlignment();
2245 }
2246
2247 void Controller::SetVerticalLineAlignment( Toolkit::DevelText::VerticalLineAlignment::Type alignment )
2248 {
2249   mImpl->mModel->mVerticalLineAlignment = alignment;
2250 }
2251
2252 // public : Relayout.
2253
2254 Controller::UpdateTextType Controller::Relayout( const Size& size, Dali::LayoutDirection::Type layoutDirection )
2255 {
2256   DALI_LOG_INFO( gLogFilter, Debug::Verbose, "-->Controller::Relayout %p size %f,%f, autoScroll[%s]\n", this, size.width, size.height, mImpl->mIsAutoScrollEnabled ?"true":"false"  );
2257
2258   UpdateTextType updateTextType = NONE_UPDATED;
2259
2260
2261   if( ( size.width < Math::MACHINE_EPSILON_1000 ) || ( size.height < Math::MACHINE_EPSILON_1000 ) )
2262   {
2263     if( 0u != mImpl->mModel->mVisualModel->mGlyphPositions.Count() )
2264     {
2265       mImpl->mModel->mVisualModel->mGlyphPositions.Clear();
2266       updateTextType = MODEL_UPDATED;
2267     }
2268
2269     // Clear the update info. This info will be set the next time the text is updated.
2270     mImpl->mTextUpdateInfo.Clear();
2271
2272     // Not worth to relayout if width or height is equal to zero.
2273     DALI_LOG_INFO( gLogFilter, Debug::Verbose, "<--Controller::Relayout (skipped)\n" );
2274
2275     return updateTextType;
2276   }
2277
2278   // Whether a new size has been set.
2279   const bool newSize = ( size != mImpl->mModel->mVisualModel->mControlSize );
2280
2281   if( newSize )
2282   {
2283     DALI_LOG_INFO( gLogFilter, Debug::Verbose, "new size (previous size %f,%f)\n", mImpl->mModel->mVisualModel->mControlSize.width, mImpl->mModel->mVisualModel->mControlSize.height );
2284
2285     if( ( 0 == mImpl->mTextUpdateInfo.mNumberOfCharactersToAdd ) &&
2286         ( 0 == mImpl->mTextUpdateInfo.mPreviousNumberOfCharacters ) &&
2287         ( ( mImpl->mModel->mVisualModel->mControlSize.width < Math::MACHINE_EPSILON_1000 ) || ( mImpl->mModel->mVisualModel->mControlSize.height < Math::MACHINE_EPSILON_1000 ) ) )
2288     {
2289       mImpl->mTextUpdateInfo.mNumberOfCharactersToAdd = mImpl->mModel->mLogicalModel->mText.Count();
2290     }
2291
2292     // Layout operations that need to be done if the size changes.
2293     mImpl->mOperationsPending = static_cast<OperationsMask>( mImpl->mOperationsPending |
2294                                                              LAYOUT                    |
2295                                                              ALIGN                     |
2296                                                              UPDATE_LAYOUT_SIZE        |
2297                                                              REORDER );
2298     // Set the update info to relayout the whole text.
2299     mImpl->mTextUpdateInfo.mFullRelayoutNeeded = true;
2300     mImpl->mTextUpdateInfo.mCharacterIndex = 0u;
2301
2302     // Store the size used to layout the text.
2303     mImpl->mModel->mVisualModel->mControlSize = size;
2304   }
2305
2306   // Whether there are modify events.
2307   if( 0u != mImpl->mModifyEvents.Count() )
2308   {
2309     // Style operations that need to be done if the text is modified.
2310     mImpl->mOperationsPending = static_cast<OperationsMask>( mImpl->mOperationsPending |
2311                                                              COLOR );
2312   }
2313
2314   // Set the update info to elide the text.
2315   if( mImpl->mModel->mElideEnabled ||
2316       ( ( NULL != mImpl->mEventData ) && mImpl->mEventData->mIsPlaceholderElideEnabled ) )
2317   {
2318     // Update Text layout for applying elided
2319     mImpl->mOperationsPending = static_cast<OperationsMask>( mImpl->mOperationsPending |
2320                                                              ALIGN                     |
2321                                                              LAYOUT                    |
2322                                                              UPDATE_LAYOUT_SIZE        |
2323                                                              REORDER );
2324     mImpl->mTextUpdateInfo.mFullRelayoutNeeded = true;
2325     mImpl->mTextUpdateInfo.mCharacterIndex = 0u;
2326   }
2327
2328   if( mImpl->mModel->mMatchSystemLanguageDirection  && mImpl->mLayoutDirection != layoutDirection )
2329   {
2330     // Clear the update info. This info will be set the next time the text is updated.
2331     mImpl->mTextUpdateInfo.mClearAll = true;
2332     // Apply modifications to the model
2333     mImpl->mOperationsPending = static_cast<OperationsMask>( mImpl->mOperationsPending |
2334                                                              GET_GLYPH_METRICS         |
2335                                                              SHAPE_TEXT                |
2336                                                              UPDATE_DIRECTION          |
2337                                                              LAYOUT                    |
2338                                                              BIDI_INFO                 |
2339                                                              REORDER );
2340     mImpl->mLayoutDirection = layoutDirection;
2341   }
2342
2343   // Make sure the model is up-to-date before layouting.
2344   ProcessModifyEvents();
2345   bool updated = mImpl->UpdateModel( mImpl->mOperationsPending );
2346
2347   // Layout the text.
2348   Size layoutSize;
2349   updated = DoRelayout( size,
2350                         mImpl->mOperationsPending,
2351                         layoutSize ) || updated;
2352
2353   if( updated )
2354   {
2355     updateTextType = MODEL_UPDATED;
2356   }
2357
2358   // Do not re-do any operation until something changes.
2359   mImpl->mOperationsPending = NO_OPERATION;
2360   mImpl->mModel->mScrollPositionLast = mImpl->mModel->mScrollPosition;
2361
2362   // Whether the text control is editable
2363   const bool isEditable = NULL != mImpl->mEventData;
2364
2365   // Keep the current offset as it will be used to update the decorator's positions (if the size changes).
2366   Vector2 offset;
2367   if( newSize && isEditable )
2368   {
2369     offset = mImpl->mModel->mScrollPosition;
2370   }
2371
2372   if( !isEditable || !IsMultiLineEnabled() )
2373   {
2374     // After doing the text layout, the vertical offset to place the actor in the desired position can be calculated.
2375     CalculateVerticalOffset( size );
2376   }
2377
2378   if( isEditable )
2379   {
2380     if( newSize )
2381     {
2382       // If there is a new size, the scroll position needs to be clamped.
2383       mImpl->ClampHorizontalScroll( layoutSize );
2384
2385       // Update the decorator's positions is needed if there is a new size.
2386       mImpl->mEventData->mDecorator->UpdatePositions( mImpl->mModel->mScrollPosition - offset );
2387     }
2388
2389     // Move the cursor, grab handle etc.
2390     if( mImpl->ProcessInputEvents() )
2391     {
2392       updateTextType = static_cast<UpdateTextType>( updateTextType | DECORATOR_UPDATED );
2393     }
2394   }
2395
2396   // Clear the update info. This info will be set the next time the text is updated.
2397   mImpl->mTextUpdateInfo.Clear();
2398   DALI_LOG_INFO( gLogFilter, Debug::Verbose, "<--Controller::Relayout\n" );
2399
2400   return updateTextType;
2401 }
2402
2403 void Controller::RequestRelayout()
2404 {
2405   mImpl->RequestRelayout();
2406 }
2407
2408 // public : Input style change signals.
2409
2410 bool Controller::IsInputStyleChangedSignalsQueueEmpty()
2411 {
2412   return ( NULL == mImpl->mEventData ) || ( 0u == mImpl->mEventData->mInputStyleChangedQueue.Count() );
2413 }
2414
2415 void Controller::ProcessInputStyleChangedSignals()
2416 {
2417   if( NULL == mImpl->mEventData )
2418   {
2419     // Nothing to do.
2420     return;
2421   }
2422
2423   for( Vector<InputStyle::Mask>::ConstIterator it = mImpl->mEventData->mInputStyleChangedQueue.Begin(),
2424          endIt = mImpl->mEventData->mInputStyleChangedQueue.End();
2425        it != endIt;
2426        ++it )
2427   {
2428     const InputStyle::Mask mask = *it;
2429
2430     if( NULL != mImpl->mEditableControlInterface )
2431     {
2432       // Emit the input style changed signal.
2433       mImpl->mEditableControlInterface->InputStyleChanged( mask );
2434     }
2435   }
2436
2437   mImpl->mEventData->mInputStyleChangedQueue.Clear();
2438 }
2439
2440 // public : Text-input Event Queuing.
2441
2442 void Controller::KeyboardFocusGainEvent()
2443 {
2444   DALI_ASSERT_DEBUG( mImpl->mEventData && "Unexpected KeyboardFocusGainEvent" );
2445
2446   if( NULL != mImpl->mEventData )
2447   {
2448     if( ( EventData::INACTIVE == mImpl->mEventData->mState ) ||
2449         ( EventData::INTERRUPTED == mImpl->mEventData->mState ) )
2450     {
2451       mImpl->ChangeState( EventData::EDITING );
2452       mImpl->mEventData->mUpdateCursorPosition = true; //If editing started without tap event, cursor update must be triggered.
2453       mImpl->mEventData->mUpdateInputStyle = true;
2454       mImpl->mEventData->mScrollAfterUpdatePosition = true;
2455     }
2456     mImpl->NotifyInputMethodContextMultiLineStatus();
2457     if( mImpl->IsShowingPlaceholderText() )
2458     {
2459       // Show alternative placeholder-text when editing
2460       ShowPlaceholderText();
2461     }
2462
2463     mImpl->RequestRelayout();
2464   }
2465 }
2466
2467 void Controller::KeyboardFocusLostEvent()
2468 {
2469   DALI_ASSERT_DEBUG( mImpl->mEventData && "Unexpected KeyboardFocusLostEvent" );
2470
2471   if( NULL != mImpl->mEventData )
2472   {
2473     if( EventData::INTERRUPTED != mImpl->mEventData->mState )
2474     {
2475       mImpl->ChangeState( EventData::INACTIVE );
2476
2477       if( !mImpl->IsShowingRealText() )
2478       {
2479         // Revert to regular placeholder-text when not editing
2480         ShowPlaceholderText();
2481       }
2482     }
2483   }
2484   mImpl->RequestRelayout();
2485 }
2486
2487 bool Controller::KeyEvent( const Dali::KeyEvent& keyEvent )
2488 {
2489   DALI_ASSERT_DEBUG( mImpl->mEventData && "Unexpected KeyEvent" );
2490
2491   bool textChanged = false;
2492   bool relayoutNeeded = false;
2493
2494   if( ( NULL != mImpl->mEventData ) &&
2495       ( keyEvent.state == KeyEvent::Down ) )
2496   {
2497     int keyCode = keyEvent.keyCode;
2498     const std::string& keyString = keyEvent.keyPressed;
2499     const std::string keyName = keyEvent.keyPressedName;
2500
2501     const bool isNullKey = ( 0 == keyCode ) && ( keyString.empty() );
2502
2503     // Pre-process to separate modifying events from non-modifying input events.
2504     if( isNullKey )
2505     {
2506       // In some platforms arrive key events with no key code.
2507       // Do nothing.
2508       return false;
2509     }
2510     else if( Dali::DALI_KEY_ESCAPE == keyCode || Dali::DALI_KEY_BACK == keyCode  || Dali::DALI_KEY_SEARCH == keyCode )
2511     {
2512       // Do nothing
2513       return false;
2514     }
2515     else if( ( Dali::DALI_KEY_CURSOR_LEFT  == keyCode ) ||
2516              ( Dali::DALI_KEY_CURSOR_RIGHT == keyCode ) ||
2517              ( Dali::DALI_KEY_CURSOR_UP    == keyCode ) ||
2518              ( Dali::DALI_KEY_CURSOR_DOWN  == keyCode ) )
2519     {
2520       // If don't have any text, do nothing.
2521       if( !mImpl->mTextUpdateInfo.mPreviousNumberOfCharacters )
2522       {
2523         return false;
2524       }
2525
2526       uint32_t cursorPosition = mImpl->mEventData->mPrimaryCursorPosition;
2527       uint32_t numberOfCharacters = mImpl->mTextUpdateInfo.mPreviousNumberOfCharacters;
2528       uint32_t cursorLine = mImpl->mModel->mVisualModel->GetLineOfCharacter( cursorPosition );
2529       uint32_t numberOfLines = mImpl->mModel->GetNumberOfLines();
2530
2531       // Logic to determine whether this text control will lose focus or not.
2532       if( ( Dali::DALI_KEY_CURSOR_LEFT == keyCode && 0 == cursorPosition && !keyEvent.IsShiftModifier() ) ||
2533           ( Dali::DALI_KEY_CURSOR_RIGHT == keyCode && numberOfCharacters == cursorPosition && !keyEvent.IsShiftModifier() ) ||
2534           ( Dali::DALI_KEY_CURSOR_DOWN == keyCode && cursorLine == numberOfLines -1 ) ||
2535           ( Dali::DALI_KEY_CURSOR_DOWN == keyCode && numberOfCharacters == cursorPosition && cursorLine -1 == numberOfLines -1 ) ||
2536           ( Dali::DALI_KEY_CURSOR_UP == keyCode && cursorLine == 0 ) ||
2537           ( Dali::DALI_KEY_CURSOR_UP == keyCode && numberOfCharacters == cursorPosition && cursorLine == 1 ) )
2538       {
2539         // Release the active highlight.
2540         if( mImpl->mEventData->mState == EventData::SELECTING )
2541         {
2542           mImpl->ChangeState( EventData::EDITING );
2543
2544           // Update selection position.
2545           mImpl->mEventData->mLeftSelectionPosition = mImpl->mEventData->mPrimaryCursorPosition;
2546           mImpl->mEventData->mRightSelectionPosition = mImpl->mEventData->mPrimaryCursorPosition;
2547           mImpl->mEventData->mUpdateCursorPosition = true;
2548           mImpl->RequestRelayout();
2549         }
2550         return false;
2551       }
2552
2553       mImpl->mEventData->mCheckScrollAmount = true;
2554       Event event( Event::CURSOR_KEY_EVENT );
2555       event.p1.mInt = keyCode;
2556       event.p2.mBool = keyEvent.IsShiftModifier();
2557       mImpl->mEventData->mEventQueue.push_back( event );
2558
2559       // Will request for relayout.
2560       relayoutNeeded = true;
2561     }
2562     else if ( Dali::DevelKey::DALI_KEY_CONTROL_LEFT == keyCode || Dali::DevelKey::DALI_KEY_CONTROL_RIGHT == keyCode )
2563     {
2564       // Left or Right Control key event is received before Ctrl-C/V/X key event is received
2565       // If not handle it here, any selected text will be deleted
2566
2567       // Do nothing
2568       return false;
2569     }
2570     else if ( keyEvent.IsCtrlModifier() )
2571     {
2572       bool consumed = false;
2573       if (keyName == KEY_C_NAME)
2574       {
2575         // Ctrl-C to copy the selected text
2576         TextPopupButtonTouched( Toolkit::TextSelectionPopup::COPY );
2577         consumed = true;
2578       }
2579       else if (keyName == KEY_V_NAME)
2580       {
2581         // Ctrl-V to paste the copied text
2582         TextPopupButtonTouched( Toolkit::TextSelectionPopup::PASTE );
2583         consumed = true;
2584       }
2585       else if (keyName == KEY_X_NAME)
2586       {
2587         // Ctrl-X to cut the selected text
2588         TextPopupButtonTouched( Toolkit::TextSelectionPopup::CUT );
2589         consumed = true;
2590       }
2591       return consumed;
2592     }
2593     else if( ( Dali::DALI_KEY_BACKSPACE == keyCode ) ||
2594              ( Dali::DevelKey::DALI_KEY_DELETE == keyCode ) )
2595     {
2596       textChanged = DeleteEvent( keyCode );
2597
2598       // Will request for relayout.
2599       relayoutNeeded = true;
2600     }
2601     else if( IsKey( keyEvent, Dali::DALI_KEY_POWER ) ||
2602              IsKey( keyEvent, Dali::DALI_KEY_MENU ) ||
2603              IsKey( keyEvent, Dali::DALI_KEY_HOME ) )
2604     {
2605       // Power key/Menu/Home key behaviour does not allow edit mode to resume.
2606       mImpl->ChangeState( EventData::INACTIVE );
2607
2608       // Will request for relayout.
2609       relayoutNeeded = true;
2610
2611       // This branch avoids calling the InsertText() method of the 'else' branch which can delete selected text.
2612     }
2613     else if( Dali::DALI_KEY_SHIFT_LEFT == keyCode )
2614     {
2615       // DALI_KEY_SHIFT_LEFT is the key code for the Left Shift. It's sent (by the InputMethodContext?) when the predictive text is enabled
2616       // and a character is typed after the type of a upper case latin character.
2617
2618       // Do nothing.
2619       return false;
2620     }
2621     else if( ( Dali::DALI_KEY_VOLUME_UP == keyCode ) || ( Dali::DALI_KEY_VOLUME_DOWN == keyCode ) )
2622     {
2623       // This branch avoids calling the InsertText() method of the 'else' branch which can delete selected text.
2624       // Do nothing.
2625       return false;
2626     }
2627     else
2628     {
2629       DALI_LOG_INFO( gLogFilter, Debug::Verbose, "Controller::KeyEvent %p keyString %s\n", this, keyString.c_str() );
2630
2631       // InputMethodContext is no longer handling key-events
2632       mImpl->ClearPreEditFlag();
2633
2634       InsertText( keyString, COMMIT );
2635       textChanged = true;
2636
2637       // Will request for relayout.
2638       relayoutNeeded = true;
2639     }
2640
2641     if ( ( mImpl->mEventData->mState != EventData::INTERRUPTED ) &&
2642          ( mImpl->mEventData->mState != EventData::INACTIVE ) &&
2643          ( !isNullKey ) &&
2644          ( Dali::DALI_KEY_SHIFT_LEFT != keyCode ) &&
2645          ( Dali::DALI_KEY_VOLUME_UP != keyCode ) &&
2646          ( Dali::DALI_KEY_VOLUME_DOWN != keyCode ) )
2647     {
2648       // Should not change the state if the key is the shift send by the InputMethodContext.
2649       // Otherwise, when the state is SELECTING the text controller can't send the right
2650       // surrounding info to the InputMethodContext.
2651       mImpl->ChangeState( EventData::EDITING );
2652
2653       // Will request for relayout.
2654       relayoutNeeded = true;
2655     }
2656
2657     if( relayoutNeeded )
2658     {
2659       mImpl->RequestRelayout();
2660     }
2661   }
2662
2663   if( textChanged &&
2664       ( NULL != mImpl->mEditableControlInterface ) )
2665   {
2666     // Do this last since it provides callbacks into application code
2667     mImpl->mEditableControlInterface->TextChanged();
2668   }
2669
2670   return true;
2671 }
2672
2673 void Controller::TapEvent( unsigned int tapCount, float x, float y )
2674 {
2675   DALI_ASSERT_DEBUG( mImpl->mEventData && "Unexpected TapEvent" );
2676
2677   if( NULL != mImpl->mEventData )
2678   {
2679     DALI_LOG_INFO( gLogFilter, Debug::Concise, "TapEvent state:%d \n", mImpl->mEventData->mState );
2680     EventData::State state( mImpl->mEventData->mState );
2681     bool relayoutNeeded( false );   // to avoid unnecessary relayouts when tapping an empty text-field
2682
2683     if( mImpl->IsClipboardVisible() )
2684     {
2685       if( EventData::INACTIVE == state || EventData::EDITING == state)
2686       {
2687         mImpl->ChangeState( EventData::EDITING_WITH_GRAB_HANDLE );
2688       }
2689       relayoutNeeded = true;
2690     }
2691     else if( 1u == tapCount )
2692     {
2693       if( EventData::EDITING_WITH_POPUP == state || EventData::EDITING_WITH_PASTE_POPUP == state )
2694       {
2695         mImpl->ChangeState( EventData::EDITING_WITH_GRAB_HANDLE );  // If Popup shown hide it here so can be shown again if required.
2696       }
2697
2698       if( mImpl->IsShowingRealText() && ( EventData::INACTIVE != state ) )
2699       {
2700         mImpl->ChangeState( EventData::EDITING_WITH_GRAB_HANDLE );
2701         relayoutNeeded = true;
2702       }
2703       else
2704       {
2705         if( mImpl->IsShowingPlaceholderText() && !mImpl->IsFocusedPlaceholderAvailable() )
2706         {
2707           // Hide placeholder text
2708           ResetText();
2709         }
2710
2711         if( EventData::INACTIVE == state )
2712         {
2713           mImpl->ChangeState( EventData::EDITING );
2714         }
2715         else if( !mImpl->IsClipboardEmpty() )
2716         {
2717           mImpl->ChangeState( EventData::EDITING_WITH_POPUP );
2718         }
2719         relayoutNeeded = true;
2720       }
2721     }
2722     else if( 2u == tapCount )
2723     {
2724       if( mImpl->mEventData->mSelectionEnabled &&
2725           mImpl->IsShowingRealText() )
2726       {
2727         relayoutNeeded = true;
2728         mImpl->mEventData->mIsLeftHandleSelected = true;
2729         mImpl->mEventData->mIsRightHandleSelected = true;
2730       }
2731     }
2732
2733     // Handles & cursors must be repositioned after Relayout() i.e. after the Model has been updated
2734     if( relayoutNeeded )
2735     {
2736       Event event( Event::TAP_EVENT );
2737       event.p1.mUint = tapCount;
2738       event.p2.mFloat = x;
2739       event.p3.mFloat = y;
2740       mImpl->mEventData->mEventQueue.push_back( event );
2741
2742       mImpl->RequestRelayout();
2743     }
2744   }
2745
2746   // Reset keyboard as tap event has occurred.
2747   mImpl->ResetInputMethodContext();
2748 }
2749
2750 void Controller::PanEvent( Gesture::State state, const Vector2& displacement )
2751 {
2752   DALI_ASSERT_DEBUG( mImpl->mEventData && "Unexpected PanEvent" );
2753
2754   if( NULL != mImpl->mEventData )
2755   {
2756     Event event( Event::PAN_EVENT );
2757     event.p1.mInt = state;
2758     event.p2.mFloat = displacement.x;
2759     event.p3.mFloat = displacement.y;
2760     mImpl->mEventData->mEventQueue.push_back( event );
2761
2762     mImpl->RequestRelayout();
2763   }
2764 }
2765
2766 void Controller::LongPressEvent( Gesture::State state, float x, float y  )
2767 {
2768   DALI_ASSERT_DEBUG( mImpl->mEventData && "Unexpected LongPressEvent" );
2769
2770   if( ( state == Gesture::Started ) &&
2771       ( NULL != mImpl->mEventData ) )
2772   {
2773     // The 1st long-press on inactive text-field is treated as tap
2774     if( EventData::INACTIVE == mImpl->mEventData->mState )
2775     {
2776       mImpl->ChangeState( EventData::EDITING );
2777
2778       Event event( Event::TAP_EVENT );
2779       event.p1.mUint = 1;
2780       event.p2.mFloat = x;
2781       event.p3.mFloat = y;
2782       mImpl->mEventData->mEventQueue.push_back( event );
2783
2784       mImpl->RequestRelayout();
2785     }
2786     else if( !mImpl->IsShowingRealText() )
2787     {
2788       Event event( Event::LONG_PRESS_EVENT );
2789       event.p1.mInt = state;
2790       event.p2.mFloat = x;
2791       event.p3.mFloat = y;
2792       mImpl->mEventData->mEventQueue.push_back( event );
2793       mImpl->RequestRelayout();
2794     }
2795     else if( !mImpl->IsClipboardVisible() )
2796     {
2797       // Reset the InputMethodContext to commit the pre-edit before selecting the text.
2798       mImpl->ResetInputMethodContext();
2799
2800       Event event( Event::LONG_PRESS_EVENT );
2801       event.p1.mInt = state;
2802       event.p2.mFloat = x;
2803       event.p3.mFloat = y;
2804       mImpl->mEventData->mEventQueue.push_back( event );
2805       mImpl->RequestRelayout();
2806
2807       mImpl->mEventData->mIsLeftHandleSelected = true;
2808       mImpl->mEventData->mIsRightHandleSelected = true;
2809     }
2810   }
2811 }
2812
2813 InputMethodContext::CallbackData Controller::OnInputMethodContextEvent( InputMethodContext& inputMethodContext, const InputMethodContext::EventData& inputMethodContextEvent )
2814 {
2815   // Whether the text needs to be relaid-out.
2816   bool requestRelayout = false;
2817
2818   // Whether to retrieve the text and cursor position to be sent to the InputMethodContext.
2819   bool retrieveText = false;
2820   bool retrieveCursor = false;
2821
2822   switch( inputMethodContextEvent.eventName )
2823   {
2824     case InputMethodContext::COMMIT:
2825     {
2826       InsertText( inputMethodContextEvent.predictiveString, Text::Controller::COMMIT );
2827       requestRelayout = true;
2828       retrieveCursor = true;
2829       break;
2830     }
2831     case InputMethodContext::PRE_EDIT:
2832     {
2833       InsertText( inputMethodContextEvent.predictiveString, Text::Controller::PRE_EDIT );
2834       requestRelayout = true;
2835       retrieveCursor = true;
2836       break;
2837     }
2838     case InputMethodContext::DELETE_SURROUNDING:
2839     {
2840       const bool textDeleted = RemoveText( inputMethodContextEvent.cursorOffset,
2841                                            inputMethodContextEvent.numberOfChars,
2842                                            DONT_UPDATE_INPUT_STYLE );
2843
2844       if( textDeleted )
2845       {
2846         if( ( 0u != mImpl->mModel->mLogicalModel->mText.Count() ) ||
2847             !mImpl->IsPlaceholderAvailable() )
2848         {
2849           mImpl->QueueModifyEvent( ModifyEvent::TEXT_DELETED );
2850         }
2851         else
2852         {
2853           ShowPlaceholderText();
2854         }
2855         mImpl->mEventData->mUpdateCursorPosition = true;
2856         mImpl->mEventData->mScrollAfterDelete = true;
2857
2858         requestRelayout = true;
2859       }
2860       break;
2861     }
2862     case InputMethodContext::GET_SURROUNDING:
2863     {
2864       retrieveText = true;
2865       retrieveCursor = true;
2866       break;
2867     }
2868     case InputMethodContext::PRIVATE_COMMAND:
2869     {
2870       // PRIVATECOMMAND event is just for getting the private command message
2871       retrieveText = true;
2872       retrieveCursor = true;
2873       break;
2874     }
2875     case InputMethodContext::VOID:
2876     {
2877       // do nothing
2878       break;
2879     }
2880   } // end switch
2881
2882   if( requestRelayout )
2883   {
2884     mImpl->mOperationsPending = ALL_OPERATIONS;
2885     mImpl->RequestRelayout();
2886   }
2887
2888   std::string text;
2889   CharacterIndex cursorPosition = 0u;
2890   Length numberOfWhiteSpaces = 0u;
2891
2892   if( retrieveCursor )
2893   {
2894     numberOfWhiteSpaces = mImpl->GetNumberOfWhiteSpaces( 0u );
2895
2896     cursorPosition = mImpl->GetLogicalCursorPosition();
2897
2898     if( cursorPosition < numberOfWhiteSpaces )
2899     {
2900       cursorPosition = 0u;
2901     }
2902     else
2903     {
2904       cursorPosition -= numberOfWhiteSpaces;
2905     }
2906   }
2907
2908   if( retrieveText )
2909   {
2910     if( !mImpl->IsShowingPlaceholderText() )
2911     {
2912       // Retrieves the normal text string.
2913       mImpl->GetText( numberOfWhiteSpaces, text );
2914     }
2915     else
2916     {
2917       // When the current text is Placeholder Text, the surrounding text should be empty string.
2918       // It means DALi should send empty string ("") to IME.
2919       text = "";
2920     }
2921   }
2922
2923   InputMethodContext::CallbackData callbackData( ( retrieveText || retrieveCursor ), cursorPosition, text, false );
2924
2925   if( requestRelayout &&
2926       ( NULL != mImpl->mEditableControlInterface ) )
2927   {
2928     // Do this last since it provides callbacks into application code
2929     mImpl->mEditableControlInterface->TextChanged();
2930   }
2931
2932   return callbackData;
2933 }
2934
2935 void Controller::PasteClipboardItemEvent()
2936 {
2937   // Retrieve the clipboard contents first
2938   ClipboardEventNotifier notifier( ClipboardEventNotifier::Get() );
2939   std::string stringToPaste( notifier.GetContent() );
2940
2941   // Commit the current pre-edit text; the contents of the clipboard should be appended
2942   mImpl->ResetInputMethodContext();
2943
2944   // Temporary disable hiding clipboard
2945   mImpl->SetClipboardHideEnable( false );
2946
2947   // Paste
2948   PasteText( stringToPaste );
2949
2950   mImpl->SetClipboardHideEnable( true );
2951 }
2952
2953 // protected : Inherit from Text::Decorator::ControllerInterface.
2954
2955 void Controller::GetTargetSize( Vector2& targetSize )
2956 {
2957   targetSize = mImpl->mModel->mVisualModel->mControlSize;
2958 }
2959
2960 void Controller::AddDecoration( Actor& actor, bool needsClipping )
2961 {
2962   if( NULL != mImpl->mEditableControlInterface )
2963   {
2964     mImpl->mEditableControlInterface->AddDecoration( actor, needsClipping );
2965   }
2966 }
2967
2968 void Controller::DecorationEvent( HandleType handleType, HandleState state, float x, float y )
2969 {
2970   DALI_ASSERT_DEBUG( mImpl->mEventData && "Unexpected DecorationEvent" );
2971
2972   if( NULL != mImpl->mEventData )
2973   {
2974     switch( handleType )
2975     {
2976       case GRAB_HANDLE:
2977       {
2978         Event event( Event::GRAB_HANDLE_EVENT );
2979         event.p1.mUint  = state;
2980         event.p2.mFloat = x;
2981         event.p3.mFloat = y;
2982
2983         mImpl->mEventData->mEventQueue.push_back( event );
2984         break;
2985       }
2986       case LEFT_SELECTION_HANDLE:
2987       {
2988         Event event( Event::LEFT_SELECTION_HANDLE_EVENT );
2989         event.p1.mUint  = state;
2990         event.p2.mFloat = x;
2991         event.p3.mFloat = y;
2992
2993         mImpl->mEventData->mEventQueue.push_back( event );
2994         break;
2995       }
2996       case RIGHT_SELECTION_HANDLE:
2997       {
2998         Event event( Event::RIGHT_SELECTION_HANDLE_EVENT );
2999         event.p1.mUint  = state;
3000         event.p2.mFloat = x;
3001         event.p3.mFloat = y;
3002
3003         mImpl->mEventData->mEventQueue.push_back( event );
3004         break;
3005       }
3006       case LEFT_SELECTION_HANDLE_MARKER:
3007       case RIGHT_SELECTION_HANDLE_MARKER:
3008       {
3009         // Markers do not move the handles.
3010         break;
3011       }
3012       case HANDLE_TYPE_COUNT:
3013       {
3014         DALI_ASSERT_DEBUG( !"Controller::HandleEvent. Unexpected handle type" );
3015       }
3016     }
3017
3018     mImpl->RequestRelayout();
3019   }
3020 }
3021
3022 // protected : Inherit from TextSelectionPopup::TextPopupButtonCallbackInterface.
3023
3024 void Controller::TextPopupButtonTouched( Dali::Toolkit::TextSelectionPopup::Buttons button )
3025 {
3026   if( NULL == mImpl->mEventData )
3027   {
3028     return;
3029   }
3030
3031   switch( button )
3032   {
3033     case Toolkit::TextSelectionPopup::CUT:
3034     {
3035       mImpl->SendSelectionToClipboard( true ); // Synchronous call to modify text
3036       mImpl->mOperationsPending = ALL_OPERATIONS;
3037
3038       if( ( 0u != mImpl->mModel->mLogicalModel->mText.Count() ) ||
3039           !mImpl->IsPlaceholderAvailable() )
3040       {
3041         mImpl->QueueModifyEvent( ModifyEvent::TEXT_DELETED );
3042       }
3043       else
3044       {
3045         ShowPlaceholderText();
3046       }
3047
3048       mImpl->mEventData->mUpdateCursorPosition = true;
3049       mImpl->mEventData->mScrollAfterDelete = true;
3050
3051       mImpl->RequestRelayout();
3052
3053       if( NULL != mImpl->mEditableControlInterface )
3054       {
3055         mImpl->mEditableControlInterface->TextChanged();
3056       }
3057       break;
3058     }
3059     case Toolkit::TextSelectionPopup::COPY:
3060     {
3061       mImpl->SendSelectionToClipboard( false ); // Text not modified
3062
3063       mImpl->mEventData->mUpdateCursorPosition = true;
3064
3065       mImpl->RequestRelayout(); // Cursor, Handles, Selection Highlight, Popup
3066       break;
3067     }
3068     case Toolkit::TextSelectionPopup::PASTE:
3069     {
3070       mImpl->RequestGetTextFromClipboard(); // Request clipboard service to retrieve an item
3071       break;
3072     }
3073     case Toolkit::TextSelectionPopup::SELECT:
3074     {
3075       const Vector2& currentCursorPosition = mImpl->mEventData->mDecorator->GetPosition( PRIMARY_CURSOR );
3076
3077       if( mImpl->mEventData->mSelectionEnabled )
3078       {
3079         // Creates a SELECT event.
3080         SelectEvent( currentCursorPosition.x, currentCursorPosition.y, false );
3081       }
3082       break;
3083     }
3084     case Toolkit::TextSelectionPopup::SELECT_ALL:
3085     {
3086       // Creates a SELECT_ALL event
3087       SelectEvent( 0.f, 0.f, true );
3088       break;
3089     }
3090     case Toolkit::TextSelectionPopup::CLIPBOARD:
3091     {
3092       mImpl->ShowClipboard();
3093       break;
3094     }
3095     case Toolkit::TextSelectionPopup::NONE:
3096     {
3097       // Nothing to do.
3098       break;
3099     }
3100   }
3101 }
3102
3103 void Controller::DisplayTimeExpired()
3104 {
3105   mImpl->mEventData->mUpdateCursorPosition = true;
3106   // Apply modifications to the model
3107   mImpl->mOperationsPending = ALL_OPERATIONS;
3108
3109   mImpl->RequestRelayout();
3110 }
3111
3112 // private : Update.
3113
3114 void Controller::InsertText( const std::string& text, Controller::InsertType type )
3115 {
3116   bool removedPrevious = false;
3117   bool removedSelected = false;
3118   bool maxLengthReached = false;
3119
3120   DALI_ASSERT_DEBUG( NULL != mImpl->mEventData && "Unexpected InsertText" )
3121
3122   if( NULL == mImpl->mEventData )
3123   {
3124     return;
3125   }
3126
3127   DALI_LOG_INFO( gLogFilter, Debug::Verbose, "Controller::InsertText %p %s (%s) mPrimaryCursorPosition %d mPreEditFlag %d mPreEditStartPosition %d mPreEditLength %d\n",
3128                  this, text.c_str(), (COMMIT == type ? "COMMIT" : "PRE_EDIT"),
3129                  mImpl->mEventData->mPrimaryCursorPosition, mImpl->mEventData->mPreEditFlag, mImpl->mEventData->mPreEditStartPosition, mImpl->mEventData->mPreEditLength );
3130
3131   // TODO: At the moment the underline runs are only for pre-edit.
3132   mImpl->mModel->mVisualModel->mUnderlineRuns.Clear();
3133
3134   // Remove the previous InputMethodContext pre-edit.
3135   if( mImpl->mEventData->mPreEditFlag && ( 0u != mImpl->mEventData->mPreEditLength ) )
3136   {
3137     removedPrevious = RemoveText( -static_cast<int>( mImpl->mEventData->mPrimaryCursorPosition - mImpl->mEventData->mPreEditStartPosition ),
3138                                   mImpl->mEventData->mPreEditLength,
3139                                   DONT_UPDATE_INPUT_STYLE );
3140
3141     mImpl->mEventData->mPrimaryCursorPosition = mImpl->mEventData->mPreEditStartPosition;
3142     mImpl->mEventData->mPreEditLength = 0u;
3143   }
3144   else
3145   {
3146     // Remove the previous Selection.
3147     removedSelected = RemoveSelectedText();
3148
3149   }
3150
3151   Vector<Character> utf32Characters;
3152   Length characterCount = 0u;
3153
3154   if( !text.empty() )
3155   {
3156     //  Convert text into UTF-32
3157     utf32Characters.Resize( text.size() );
3158
3159     // This is a bit horrible but std::string returns a (signed) char*
3160     const uint8_t* utf8 = reinterpret_cast<const uint8_t*>( text.c_str() );
3161
3162     // Transform a text array encoded in utf8 into an array encoded in utf32.
3163     // It returns the actual number of characters.
3164     characterCount = Utf8ToUtf32( utf8, text.size(), utf32Characters.Begin() );
3165     utf32Characters.Resize( characterCount );
3166
3167     DALI_ASSERT_DEBUG( text.size() >= utf32Characters.Count() && "Invalid UTF32 conversion length" );
3168     DALI_LOG_INFO( gLogFilter, Debug::Verbose, "UTF8 size %d, UTF32 size %d\n", text.size(), utf32Characters.Count() );
3169   }
3170
3171   if( 0u != utf32Characters.Count() ) // Check if Utf8ToUtf32 conversion succeeded
3172   {
3173     // The placeholder text is no longer needed
3174     if( mImpl->IsShowingPlaceholderText() )
3175     {
3176       ResetText();
3177     }
3178
3179     mImpl->ChangeState( EventData::EDITING );
3180
3181     // Handle the InputMethodContext (predicitive text) state changes
3182     if( COMMIT == type )
3183     {
3184       // InputMethodContext is no longer handling key-events
3185       mImpl->ClearPreEditFlag();
3186     }
3187     else // PRE_EDIT
3188     {
3189       if( !mImpl->mEventData->mPreEditFlag )
3190       {
3191         DALI_LOG_INFO( gLogFilter, Debug::Verbose, "Entered PreEdit state\n" );
3192
3193         // Record the start of the pre-edit text
3194         mImpl->mEventData->mPreEditStartPosition = mImpl->mEventData->mPrimaryCursorPosition;
3195       }
3196
3197       mImpl->mEventData->mPreEditLength = utf32Characters.Count();
3198       mImpl->mEventData->mPreEditFlag = true;
3199
3200       DALI_LOG_INFO( gLogFilter, Debug::Verbose, "mPreEditStartPosition %d mPreEditLength %d\n", mImpl->mEventData->mPreEditStartPosition, mImpl->mEventData->mPreEditLength );
3201     }
3202
3203     const Length numberOfCharactersInModel = mImpl->mModel->mLogicalModel->mText.Count();
3204
3205     // Restrict new text to fit within Maximum characters setting.
3206     Length maxSizeOfNewText = std::min( ( mImpl->mMaximumNumberOfCharacters - numberOfCharactersInModel ), characterCount );
3207     maxLengthReached = ( characterCount > maxSizeOfNewText );
3208
3209     // The cursor position.
3210     CharacterIndex& cursorIndex = mImpl->mEventData->mPrimaryCursorPosition;
3211
3212     // Update the text's style.
3213
3214     // Updates the text style runs by adding characters.
3215     mImpl->mModel->mLogicalModel->UpdateTextStyleRuns( cursorIndex, maxSizeOfNewText );
3216
3217     // Get the character index from the cursor index.
3218     const CharacterIndex styleIndex = ( cursorIndex > 0u ) ? cursorIndex - 1u : 0u;
3219
3220     // Retrieve the text's style for the given index.
3221     InputStyle style;
3222     mImpl->RetrieveDefaultInputStyle( style );
3223     mImpl->mModel->mLogicalModel->RetrieveStyle( styleIndex, style );
3224
3225     // Whether to add a new text color run.
3226     const bool addColorRun = ( style.textColor != mImpl->mEventData->mInputStyle.textColor ) && !mImpl->mEventData->mInputStyle.isDefaultColor;
3227
3228     // Whether to add a new font run.
3229     const bool addFontNameRun = ( style.familyName != mImpl->mEventData->mInputStyle.familyName ) && mImpl->mEventData->mInputStyle.isFamilyDefined;
3230     const bool addFontWeightRun = ( style.weight != mImpl->mEventData->mInputStyle.weight ) && mImpl->mEventData->mInputStyle.isWeightDefined;
3231     const bool addFontWidthRun = ( style.width != mImpl->mEventData->mInputStyle.width ) && mImpl->mEventData->mInputStyle.isWidthDefined;
3232     const bool addFontSlantRun = ( style.slant != mImpl->mEventData->mInputStyle.slant ) && mImpl->mEventData->mInputStyle.isSlantDefined;
3233     const bool addFontSizeRun = ( style.size != mImpl->mEventData->mInputStyle.size ) && mImpl->mEventData->mInputStyle.isSizeDefined ;
3234
3235     // Add style runs.
3236     if( addColorRun )
3237     {
3238       const VectorBase::SizeType numberOfRuns = mImpl->mModel->mLogicalModel->mColorRuns.Count();
3239       mImpl->mModel->mLogicalModel->mColorRuns.Resize( numberOfRuns + 1u );
3240
3241       ColorRun& colorRun = *( mImpl->mModel->mLogicalModel->mColorRuns.Begin() + numberOfRuns );
3242       colorRun.color = mImpl->mEventData->mInputStyle.textColor;
3243       colorRun.characterRun.characterIndex = cursorIndex;
3244       colorRun.characterRun.numberOfCharacters = maxSizeOfNewText;
3245     }
3246
3247     if( addFontNameRun   ||
3248         addFontWeightRun ||
3249         addFontWidthRun  ||
3250         addFontSlantRun  ||
3251         addFontSizeRun )
3252     {
3253       const VectorBase::SizeType numberOfRuns = mImpl->mModel->mLogicalModel->mFontDescriptionRuns.Count();
3254       mImpl->mModel->mLogicalModel->mFontDescriptionRuns.Resize( numberOfRuns + 1u );
3255
3256       FontDescriptionRun& fontDescriptionRun = *( mImpl->mModel->mLogicalModel->mFontDescriptionRuns.Begin() + numberOfRuns );
3257
3258       if( addFontNameRun )
3259       {
3260         fontDescriptionRun.familyLength = mImpl->mEventData->mInputStyle.familyName.size();
3261         fontDescriptionRun.familyName = new char[fontDescriptionRun.familyLength];
3262         memcpy( fontDescriptionRun.familyName, mImpl->mEventData->mInputStyle.familyName.c_str(), fontDescriptionRun.familyLength );
3263         fontDescriptionRun.familyDefined = true;
3264
3265         // The memory allocated for the font family name is freed when the font description is removed from the logical model.
3266       }
3267
3268       if( addFontWeightRun )
3269       {
3270         fontDescriptionRun.weight = mImpl->mEventData->mInputStyle.weight;
3271         fontDescriptionRun.weightDefined = true;
3272       }
3273
3274       if( addFontWidthRun )
3275       {
3276         fontDescriptionRun.width = mImpl->mEventData->mInputStyle.width;
3277         fontDescriptionRun.widthDefined = true;
3278       }
3279
3280       if( addFontSlantRun )
3281       {
3282         fontDescriptionRun.slant = mImpl->mEventData->mInputStyle.slant;
3283         fontDescriptionRun.slantDefined = true;
3284       }
3285
3286       if( addFontSizeRun )
3287       {
3288         fontDescriptionRun.size = static_cast<PointSize26Dot6>( mImpl->mEventData->mInputStyle.size * 64.f );
3289         fontDescriptionRun.sizeDefined = true;
3290       }
3291
3292       fontDescriptionRun.characterRun.characterIndex = cursorIndex;
3293       fontDescriptionRun.characterRun.numberOfCharacters = maxSizeOfNewText;
3294     }
3295
3296     // Insert at current cursor position.
3297     Vector<Character>& modifyText = mImpl->mModel->mLogicalModel->mText;
3298
3299     if( cursorIndex < numberOfCharactersInModel )
3300     {
3301       modifyText.Insert( modifyText.Begin() + cursorIndex, utf32Characters.Begin(), utf32Characters.Begin() + maxSizeOfNewText );
3302     }
3303     else
3304     {
3305       modifyText.Insert( modifyText.End(), utf32Characters.Begin(), utf32Characters.Begin() + maxSizeOfNewText );
3306     }
3307
3308     // Mark the first paragraph to be updated.
3309     if( Layout::Engine::SINGLE_LINE_BOX == mImpl->mLayoutEngine.GetLayout() )
3310     {
3311       mImpl->mTextUpdateInfo.mCharacterIndex = 0;
3312       mImpl->mTextUpdateInfo.mNumberOfCharactersToRemove = mImpl->mTextUpdateInfo.mPreviousNumberOfCharacters;
3313       mImpl->mTextUpdateInfo.mNumberOfCharactersToAdd = numberOfCharactersInModel + maxSizeOfNewText;
3314       mImpl->mTextUpdateInfo.mClearAll = true;
3315     }
3316     else
3317     {
3318       mImpl->mTextUpdateInfo.mCharacterIndex = std::min( cursorIndex, mImpl->mTextUpdateInfo.mCharacterIndex );
3319       mImpl->mTextUpdateInfo.mNumberOfCharactersToAdd += maxSizeOfNewText;
3320     }
3321
3322     // Update the cursor index.
3323     cursorIndex += maxSizeOfNewText;
3324
3325     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 );
3326   }
3327
3328   if( ( 0u == mImpl->mModel->mLogicalModel->mText.Count() ) &&
3329       mImpl->IsPlaceholderAvailable() )
3330   {
3331     // Show place-holder if empty after removing the pre-edit text
3332     ShowPlaceholderText();
3333     mImpl->mEventData->mUpdateCursorPosition = true;
3334     mImpl->ClearPreEditFlag();
3335   }
3336   else if( removedPrevious ||
3337            removedSelected ||
3338            ( 0 != utf32Characters.Count() ) )
3339   {
3340     // Queue an inserted event
3341     mImpl->QueueModifyEvent( ModifyEvent::TEXT_INSERTED );
3342
3343     mImpl->mEventData->mUpdateCursorPosition = true;
3344     if( removedSelected )
3345     {
3346       mImpl->mEventData->mScrollAfterDelete = true;
3347     }
3348     else
3349     {
3350       mImpl->mEventData->mScrollAfterUpdatePosition = true;
3351     }
3352   }
3353
3354   if( maxLengthReached )
3355   {
3356     DALI_LOG_INFO( gLogFilter, Debug::Verbose, "MaxLengthReached (%d)\n", mImpl->mModel->mLogicalModel->mText.Count() );
3357
3358     mImpl->ResetInputMethodContext();
3359
3360     if( NULL != mImpl->mEditableControlInterface )
3361     {
3362       // Do this last since it provides callbacks into application code
3363       mImpl->mEditableControlInterface->MaxLengthReached();
3364     }
3365   }
3366 }
3367
3368 void Controller::PasteText( const std::string& stringToPaste )
3369 {
3370   InsertText( stringToPaste, Text::Controller::COMMIT );
3371   mImpl->ChangeState( EventData::EDITING );
3372   mImpl->RequestRelayout();
3373
3374   if( NULL != mImpl->mEditableControlInterface )
3375   {
3376     // Do this last since it provides callbacks into application code
3377     mImpl->mEditableControlInterface->TextChanged();
3378   }
3379 }
3380
3381 bool Controller::RemoveText( int cursorOffset,
3382                              int numberOfCharacters,
3383                              UpdateInputStyleType type )
3384 {
3385   bool removed = false;
3386
3387   if( NULL == mImpl->mEventData )
3388   {
3389     return removed;
3390   }
3391
3392   DALI_LOG_INFO( gLogFilter, Debug::General, "Controller::RemoveText %p mText.Count() %d cursor %d cursorOffset %d numberOfCharacters %d\n",
3393                  this, mImpl->mModel->mLogicalModel->mText.Count(), mImpl->mEventData->mPrimaryCursorPosition, cursorOffset, numberOfCharacters );
3394
3395   if( !mImpl->IsShowingPlaceholderText() )
3396   {
3397     // Delete at current cursor position
3398     Vector<Character>& currentText = mImpl->mModel->mLogicalModel->mText;
3399     CharacterIndex& oldCursorIndex = mImpl->mEventData->mPrimaryCursorPosition;
3400
3401     CharacterIndex cursorIndex = 0;
3402
3403     // Validate the cursor position & number of characters
3404     if( ( static_cast< int >( mImpl->mEventData->mPrimaryCursorPosition ) + cursorOffset ) >= 0 )
3405     {
3406       cursorIndex = mImpl->mEventData->mPrimaryCursorPosition + cursorOffset;
3407     }
3408
3409     if( ( cursorIndex + numberOfCharacters ) > currentText.Count() )
3410     {
3411       numberOfCharacters = currentText.Count() - cursorIndex;
3412     }
3413
3414     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.
3415         ( ( cursorIndex + numberOfCharacters ) <= mImpl->mTextUpdateInfo.mPreviousNumberOfCharacters ) )
3416     {
3417       // Mark the paragraphs to be updated.
3418       if( Layout::Engine::SINGLE_LINE_BOX == mImpl->mLayoutEngine.GetLayout() )
3419       {
3420         mImpl->mTextUpdateInfo.mCharacterIndex = 0;
3421         mImpl->mTextUpdateInfo.mNumberOfCharactersToRemove = mImpl->mTextUpdateInfo.mPreviousNumberOfCharacters;
3422         mImpl->mTextUpdateInfo.mNumberOfCharactersToAdd = mImpl->mTextUpdateInfo.mPreviousNumberOfCharacters - numberOfCharacters;
3423         mImpl->mTextUpdateInfo.mClearAll = true;
3424       }
3425       else
3426       {
3427         mImpl->mTextUpdateInfo.mCharacterIndex = std::min( cursorIndex, mImpl->mTextUpdateInfo.mCharacterIndex );
3428         mImpl->mTextUpdateInfo.mNumberOfCharactersToRemove += numberOfCharacters;
3429       }
3430
3431       // Update the input style and remove the text's style before removing the text.
3432
3433       if( UPDATE_INPUT_STYLE == type )
3434       {
3435         // Keep a copy of the current input style.
3436         InputStyle currentInputStyle;
3437         currentInputStyle.Copy( mImpl->mEventData->mInputStyle );
3438
3439         // Set first the default input style.
3440         mImpl->RetrieveDefaultInputStyle( mImpl->mEventData->mInputStyle );
3441
3442         // Update the input style.
3443         mImpl->mModel->mLogicalModel->RetrieveStyle( cursorIndex, mImpl->mEventData->mInputStyle );
3444
3445         // Compare if the input style has changed.
3446         const bool hasInputStyleChanged = !currentInputStyle.Equal( mImpl->mEventData->mInputStyle );
3447
3448         if( hasInputStyleChanged )
3449         {
3450           const InputStyle::Mask styleChangedMask = currentInputStyle.GetInputStyleChangeMask( mImpl->mEventData->mInputStyle );
3451           // Queue the input style changed signal.
3452           mImpl->mEventData->mInputStyleChangedQueue.PushBack( styleChangedMask );
3453         }
3454       }
3455
3456       // Updates the text style runs by removing characters. Runs with no characters are removed.
3457       mImpl->mModel->mLogicalModel->UpdateTextStyleRuns( cursorIndex, -numberOfCharacters );
3458
3459       // Remove the characters.
3460       Vector<Character>::Iterator first = currentText.Begin() + cursorIndex;
3461       Vector<Character>::Iterator last  = first + numberOfCharacters;
3462
3463       currentText.Erase( first, last );
3464
3465       // Cursor position retreat
3466       oldCursorIndex = cursorIndex;
3467
3468       mImpl->mEventData->mScrollAfterDelete = true;
3469
3470       DALI_LOG_INFO( gLogFilter, Debug::General, "Controller::RemoveText %p removed %d\n", this, numberOfCharacters );
3471       removed = true;
3472     }
3473   }
3474
3475   return removed;
3476 }
3477
3478 bool Controller::RemoveSelectedText()
3479 {
3480   bool textRemoved( false );
3481
3482   if( EventData::SELECTING == mImpl->mEventData->mState )
3483   {
3484     std::string removedString;
3485     mImpl->RetrieveSelection( removedString, true );
3486
3487     if( !removedString.empty() )
3488     {
3489       textRemoved = true;
3490       mImpl->ChangeState( EventData::EDITING );
3491     }
3492   }
3493
3494   return textRemoved;
3495 }
3496
3497 // private : Relayout.
3498
3499 bool Controller::DoRelayout( const Size& size,
3500                              OperationsMask operationsRequired,
3501                              Size& layoutSize )
3502 {
3503   DALI_LOG_INFO( gLogFilter, Debug::Verbose, "-->Controller::DoRelayout %p size %f,%f\n", this, size.width, size.height );
3504   bool viewUpdated( false );
3505
3506   // Calculate the operations to be done.
3507   const OperationsMask operations = static_cast<OperationsMask>( mImpl->mOperationsPending & operationsRequired );
3508
3509   const CharacterIndex startIndex = mImpl->mTextUpdateInfo.mParagraphCharacterIndex;
3510   const Length requestedNumberOfCharacters = mImpl->mTextUpdateInfo.mRequestedNumberOfCharacters;
3511
3512   // Get the current layout size.
3513   layoutSize = mImpl->mModel->mVisualModel->GetLayoutSize();
3514
3515   if( NO_OPERATION != ( LAYOUT & operations ) )
3516   {
3517     DALI_LOG_INFO( gLogFilter, Debug::Verbose, "-->Controller::DoRelayout LAYOUT & operations\n");
3518
3519     // Some vectors with data needed to layout and reorder may be void
3520     // after the first time the text has been laid out.
3521     // Fill the vectors again.
3522
3523     // Calculate the number of glyphs to layout.
3524     const Vector<GlyphIndex>& charactersToGlyph = mImpl->mModel->mVisualModel->mCharactersToGlyph;
3525     const Vector<Length>& glyphsPerCharacter = mImpl->mModel->mVisualModel->mGlyphsPerCharacter;
3526     const GlyphIndex* const charactersToGlyphBuffer = charactersToGlyph.Begin();
3527     const Length* const glyphsPerCharacterBuffer = glyphsPerCharacter.Begin();
3528
3529     const CharacterIndex lastIndex = startIndex + ( ( requestedNumberOfCharacters > 0u ) ? requestedNumberOfCharacters - 1u : 0u );
3530     const GlyphIndex startGlyphIndex = mImpl->mTextUpdateInfo.mStartGlyphIndex;
3531
3532     // Make sure the index is not out of bound
3533     if ( charactersToGlyph.Count() != glyphsPerCharacter.Count() ||
3534          requestedNumberOfCharacters > charactersToGlyph.Count() ||
3535          ( lastIndex >= charactersToGlyph.Count() && charactersToGlyph.Count() > 0u ) )
3536     {
3537       std::string currentText;
3538       GetText( currentText );
3539
3540       DALI_LOG_ERROR( "Controller::DoRelayout: Attempting to access invalid buffer\n" );
3541       DALI_LOG_ERROR( "Current text is: %s\n", currentText.c_str() );
3542       DALI_LOG_ERROR( "startIndex: %u, lastIndex: %u, requestedNumberOfCharacters: %u, charactersToGlyph.Count = %lu, glyphsPerCharacter.Count = %lu\n", startIndex, lastIndex, requestedNumberOfCharacters, charactersToGlyph.Count(), glyphsPerCharacter.Count());
3543
3544       return false;
3545     }
3546
3547     const Length numberOfGlyphs = ( requestedNumberOfCharacters > 0u ) ? *( charactersToGlyphBuffer + lastIndex ) + *( glyphsPerCharacterBuffer + lastIndex ) - startGlyphIndex : 0u;
3548     const Length totalNumberOfGlyphs = mImpl->mModel->mVisualModel->mGlyphs.Count();
3549
3550     if( 0u == totalNumberOfGlyphs )
3551     {
3552       if( NO_OPERATION != ( UPDATE_LAYOUT_SIZE & operations ) )
3553       {
3554         mImpl->mModel->mVisualModel->SetLayoutSize( Size::ZERO );
3555       }
3556
3557       // Nothing else to do if there is no glyphs.
3558       DALI_LOG_INFO( gLogFilter, Debug::Verbose, "<--Controller::DoRelayout no glyphs, view updated true\n" );
3559       return true;
3560     }
3561
3562     const Vector<LineBreakInfo>& lineBreakInfo = mImpl->mModel->mLogicalModel->mLineBreakInfo;
3563     const Vector<WordBreakInfo>& wordBreakInfo = mImpl->mModel->mLogicalModel->mWordBreakInfo;
3564     const Vector<CharacterDirection>& characterDirection = mImpl->mModel->mLogicalModel->mCharacterDirections;
3565     const Vector<GlyphInfo>& glyphs = mImpl->mModel->mVisualModel->mGlyphs;
3566     const Vector<CharacterIndex>& glyphsToCharactersMap = mImpl->mModel->mVisualModel->mGlyphsToCharacters;
3567     const Vector<Length>& charactersPerGlyph = mImpl->mModel->mVisualModel->mCharactersPerGlyph;
3568     const Character* const textBuffer = mImpl->mModel->mLogicalModel->mText.Begin();
3569     const float outlineWidth = static_cast<float>( mImpl->mModel->GetOutlineWidth() );
3570
3571     // Set the layout parameters.
3572     Layout::Parameters layoutParameters( size,
3573                                          textBuffer,
3574                                          lineBreakInfo.Begin(),
3575                                          wordBreakInfo.Begin(),
3576                                          ( 0u != characterDirection.Count() ) ? characterDirection.Begin() : NULL,
3577                                          glyphs.Begin(),
3578                                          glyphsToCharactersMap.Begin(),
3579                                          charactersPerGlyph.Begin(),
3580                                          charactersToGlyphBuffer,
3581                                          glyphsPerCharacterBuffer,
3582                                          totalNumberOfGlyphs,
3583                                          mImpl->mModel->mHorizontalAlignment,
3584                                          mImpl->mModel->mLineWrapMode,
3585                                          outlineWidth,
3586                                          mImpl->mModel->mIgnoreSpacesAfterText,
3587                                          mImpl->mModel->mMatchSystemLanguageDirection );
3588
3589     // Resize the vector of positions to have the same size than the vector of glyphs.
3590     Vector<Vector2>& glyphPositions = mImpl->mModel->mVisualModel->mGlyphPositions;
3591     glyphPositions.Resize( totalNumberOfGlyphs );
3592
3593     // Whether the last character is a new paragraph character.
3594     mImpl->mTextUpdateInfo.mIsLastCharacterNewParagraph =  TextAbstraction::IsNewParagraph( *( textBuffer + ( mImpl->mModel->mLogicalModel->mText.Count() - 1u ) ) );
3595     layoutParameters.isLastNewParagraph = mImpl->mTextUpdateInfo.mIsLastCharacterNewParagraph;
3596
3597     // The initial glyph and the number of glyphs to layout.
3598     layoutParameters.startGlyphIndex = startGlyphIndex;
3599     layoutParameters.numberOfGlyphs = numberOfGlyphs;
3600     layoutParameters.startLineIndex = mImpl->mTextUpdateInfo.mStartLineIndex;
3601     layoutParameters.estimatedNumberOfLines = mImpl->mTextUpdateInfo.mEstimatedNumberOfLines;
3602
3603     // Update the ellipsis
3604     bool elideTextEnabled = mImpl->mModel->mElideEnabled;
3605
3606     if( NULL != mImpl->mEventData )
3607     {
3608       if( mImpl->mEventData->mPlaceholderEllipsisFlag && mImpl->IsShowingPlaceholderText() )
3609       {
3610         elideTextEnabled = mImpl->mEventData->mIsPlaceholderElideEnabled;
3611       }
3612       else if( EventData::INACTIVE != mImpl->mEventData->mState )
3613       {
3614         // Disable ellipsis when editing
3615         elideTextEnabled = false;
3616       }
3617
3618       // Reset the scroll position in inactive state
3619       if( elideTextEnabled && ( mImpl->mEventData->mState == EventData::INACTIVE ) )
3620       {
3621         ResetScrollPosition();
3622       }
3623     }
3624
3625     // Update the visual model.
3626     Size newLayoutSize;
3627     viewUpdated = mImpl->mLayoutEngine.LayoutText( layoutParameters,
3628                                                    glyphPositions,
3629                                                    mImpl->mModel->mVisualModel->mLines,
3630                                                    newLayoutSize,
3631                                                    elideTextEnabled );
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