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