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