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