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