Merge "Notify multiline hint to IMF context" into devel/master
[platform/core/uifw/dali-toolkit.git] / dali-toolkit / internal / text / text-controller.cpp
1 /*
2  * Copyright (c) 2016 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
28 // INTERNAL INCLUDES
29 #include <dali-toolkit/internal/text/bidirectional-support.h>
30 #include <dali-toolkit/internal/text/character-set-conversion.h>
31 #include <dali-toolkit/internal/text/layouts/layout-parameters.h>
32 #include <dali-toolkit/internal/text/markup-processor.h>
33 #include <dali-toolkit/internal/text/text-controller-impl.h>
34
35 namespace
36 {
37
38 #if defined(DEBUG_ENABLED)
39   Debug::Filter* gLogFilter = Debug::Filter::New(Debug::NoLogging, true, "LOG_TEXT_CONTROLS");
40 #endif
41
42 const float MAX_FLOAT = std::numeric_limits<float>::max();
43
44 const std::string EMPTY_STRING("");
45
46 float ConvertToEven( float value )
47 {
48   int intValue(static_cast<int>( value ));
49   return static_cast<float>(intValue % 2 == 0) ? intValue : (intValue + 1);
50 }
51
52 } // namespace
53
54 namespace Dali
55 {
56
57 namespace Toolkit
58 {
59
60 namespace Text
61 {
62
63 /**
64  * @brief Adds a new font description run for the selected text.
65  *
66  * The new font parameters are added after the call to this method.
67  *
68  * @param[in] eventData The event data pointer.
69  * @param[in] logicalModel The logical model where to add the new font description run.
70  * @param[out] startOfSelectedText Index to the first selected character.
71  * @param[out] lengthOfSelectedText Number of selected characters.
72  */
73 FontDescriptionRun& UpdateSelectionFontStyleRun( EventData* eventData,
74                                                  LogicalModelPtr logicalModel,
75                                                  CharacterIndex& startOfSelectedText,
76                                                  Length& lengthOfSelectedText )
77 {
78   const bool handlesCrossed = eventData->mLeftSelectionPosition > eventData->mRightSelectionPosition;
79
80   // Get start and end position of selection
81   startOfSelectedText = handlesCrossed ? eventData->mRightSelectionPosition : eventData->mLeftSelectionPosition;
82   lengthOfSelectedText = ( handlesCrossed ? eventData->mLeftSelectionPosition : eventData->mRightSelectionPosition ) - startOfSelectedText;
83
84   // Add the font run.
85   const VectorBase::SizeType numberOfRuns = logicalModel->mFontDescriptionRuns.Count();
86   logicalModel->mFontDescriptionRuns.Resize( numberOfRuns + 1u );
87
88   FontDescriptionRun& fontDescriptionRun = *( logicalModel->mFontDescriptionRuns.Begin() + numberOfRuns );
89
90   fontDescriptionRun.characterRun.characterIndex = startOfSelectedText;
91   fontDescriptionRun.characterRun.numberOfCharacters = lengthOfSelectedText;
92
93   // Recalculate the selection highlight as the metrics may have changed.
94   eventData->mUpdateLeftSelectionPosition = true;
95   eventData->mUpdateRightSelectionPosition = true;
96   eventData->mUpdateHighlightBox = true;
97
98   return fontDescriptionRun;
99 }
100
101 ControllerPtr Controller::New( ControlInterface& controlInterface )
102 {
103   return ControllerPtr( new Controller( controlInterface ) );
104 }
105
106 void Controller::EnableTextInput( DecoratorPtr decorator )
107 {
108   if( NULL == mImpl->mEventData )
109   {
110     mImpl->mEventData = new EventData( decorator );
111   }
112 }
113
114 void Controller::SetGlyphType( TextAbstraction::GlyphType glyphType )
115 {
116   // Metrics for bitmap & vector based glyphs are different
117   mImpl->mMetrics->SetGlyphType( glyphType );
118
119   // Clear the font-specific data
120   ClearFontData();
121
122   mImpl->RequestRelayout();
123 }
124
125 void Controller::SetMarkupProcessorEnabled( bool enable )
126 {
127   mImpl->mMarkupProcessorEnabled = enable;
128 }
129
130 bool Controller::IsMarkupProcessorEnabled() const
131 {
132   return mImpl->mMarkupProcessorEnabled;
133 }
134
135 void Controller::SetAutoScrollEnabled( bool enable )
136 {
137   DALI_LOG_INFO( gLogFilter, Debug::General, "Controller::SetAutoScrollEnabled[%s] SingleBox[%s]-> [%p]\n", (enable)?"true":"false", ( mImpl->mLayoutEngine.GetLayout() == LayoutEngine::SINGLE_LINE_BOX)?"true":"false", this );
138
139   if ( mImpl->mLayoutEngine.GetLayout() == LayoutEngine::SINGLE_LINE_BOX )
140   {
141     if ( enable )
142     {
143       DALI_LOG_INFO( gLogFilter, Debug::General, "Controller::SetAutoScrollEnabled for SINGLE_LINE_BOX\n" );
144       mImpl->mOperationsPending = static_cast<OperationsMask>( mImpl->mOperationsPending |
145                                                                LAYOUT                    |
146                                                                ALIGN                     |
147                                                                UPDATE_LAYOUT_SIZE        |
148                                                                UPDATE_DIRECTION          |
149                                                                REORDER );
150
151     }
152     else
153     {
154       DALI_LOG_INFO( gLogFilter, Debug::General, "Controller::SetAutoScrollEnabled Disabling autoscroll\n");
155       mImpl->mOperationsPending = static_cast<OperationsMask>( mImpl->mOperationsPending |
156                                                                LAYOUT                    |
157                                                                ALIGN                     |
158                                                                UPDATE_LAYOUT_SIZE        |
159                                                                REORDER );
160     }
161
162     mImpl->mAutoScrollEnabled = enable;
163     mImpl->RequestRelayout();
164   }
165   else
166   {
167     DALI_LOG_WARNING( "Attempted AutoScrolling on a non SINGLE_LINE_BOX, request ignored\n" );
168     mImpl->mAutoScrollEnabled = false;
169   }
170 }
171
172 bool Controller::IsAutoScrollEnabled() const
173 {
174   DALI_LOG_INFO( gLogFilter, Debug::Verbose, "Controller::IsAutoScrollEnabled[%s]\n", (mImpl->mAutoScrollEnabled)?"true":"false" );
175
176   return mImpl->mAutoScrollEnabled;
177 }
178
179 CharacterDirection Controller::GetAutoScrollDirection() const
180 {
181   return mImpl->mAutoScrollDirectionRTL;
182 }
183
184 float Controller::GetAutoScrollLineAlignment() const
185 {
186   float offset = 0.f;
187
188   if( mImpl->mVisualModel &&
189       ( 0u != mImpl->mVisualModel->mLines.Count() ) )
190   {
191     offset = ( *mImpl->mVisualModel->mLines.Begin() ).alignmentOffset;
192   }
193
194   return offset;
195 }
196
197 void Controller::SetHorizontalScrollEnabled( bool enable )
198 {
199   if( ( NULL != mImpl->mEventData ) &&
200       mImpl->mEventData->mDecorator )
201   {
202     mImpl->mEventData->mDecorator->SetHorizontalScrollEnabled( enable );
203   }
204 }
205
206 bool Controller::IsHorizontalScrollEnabled() const
207 {
208   if( ( NULL != mImpl->mEventData ) &&
209       mImpl->mEventData->mDecorator )
210   {
211     return mImpl->mEventData->mDecorator->IsHorizontalScrollEnabled();
212   }
213
214   return false;
215 }
216
217 void Controller::SetVerticalScrollEnabled( bool enable )
218 {
219   if( ( NULL != mImpl->mEventData ) &&
220       mImpl->mEventData->mDecorator )
221   {
222     if( mImpl->mEventData->mDecorator )
223     {
224       mImpl->mEventData->mDecorator->SetVerticalScrollEnabled( enable );
225     }
226   }
227 }
228
229 bool Controller::IsVerticalScrollEnabled() const
230 {
231   if( ( NULL != mImpl->mEventData ) &&
232       mImpl->mEventData->mDecorator )
233   {
234     return mImpl->mEventData->mDecorator->IsVerticalScrollEnabled();
235   }
236
237   return false;
238 }
239
240 void Controller::SetSmoothHandlePanEnabled( bool enable )
241 {
242   if( ( NULL != mImpl->mEventData ) &&
243       mImpl->mEventData->mDecorator )
244   {
245     mImpl->mEventData->mDecorator->SetSmoothHandlePanEnabled( enable );
246   }
247 }
248
249 bool Controller::IsSmoothHandlePanEnabled() const
250 {
251   if( ( NULL != mImpl->mEventData ) &&
252       mImpl->mEventData->mDecorator )
253   {
254     return mImpl->mEventData->mDecorator->IsSmoothHandlePanEnabled();
255   }
256
257   return false;
258 }
259
260 void Controller::SetText( const std::string& text )
261 {
262   DALI_LOG_INFO( gLogFilter, Debug::Verbose, "Controller::SetText\n" );
263
264   // Reset keyboard as text changed
265   mImpl->ResetImfManager();
266
267   // Remove the previously set text and style.
268   ResetText();
269
270   // Remove the style.
271   ClearStyleData();
272
273   CharacterIndex lastCursorIndex = 0u;
274
275   if( NULL != mImpl->mEventData )
276   {
277     // If popup shown then hide it by switching to Editing state
278     if( ( EventData::SELECTING == mImpl->mEventData->mState )          ||
279         ( EventData::EDITING_WITH_POPUP == mImpl->mEventData->mState ) ||
280         ( EventData::EDITING_WITH_GRAB_HANDLE == mImpl->mEventData->mState ) ||
281         ( EventData::EDITING_WITH_PASTE_POPUP == mImpl->mEventData->mState ) )
282     {
283       mImpl->ChangeState( EventData::EDITING );
284     }
285   }
286
287   if( !text.empty() )
288   {
289     mImpl->mVisualModel->SetTextColor( mImpl->mTextColor );
290
291     MarkupProcessData markupProcessData( mImpl->mLogicalModel->mColorRuns,
292                                          mImpl->mLogicalModel->mFontDescriptionRuns );
293
294     Length textSize = 0u;
295     const uint8_t* utf8 = NULL;
296     if( mImpl->mMarkupProcessorEnabled )
297     {
298       ProcessMarkupString( text, markupProcessData );
299       textSize = markupProcessData.markupProcessedText.size();
300
301       // This is a bit horrible but std::string returns a (signed) char*
302       utf8 = reinterpret_cast<const uint8_t*>( markupProcessData.markupProcessedText.c_str() );
303     }
304     else
305     {
306       textSize = text.size();
307
308       // This is a bit horrible but std::string returns a (signed) char*
309       utf8 = reinterpret_cast<const uint8_t*>( text.c_str() );
310     }
311
312     //  Convert text into UTF-32
313     Vector<Character>& utf32Characters = mImpl->mLogicalModel->mText;
314     utf32Characters.Resize( textSize );
315
316     // Transform a text array encoded in utf8 into an array encoded in utf32.
317     // It returns the actual number of characters.
318     Length characterCount = Utf8ToUtf32( utf8, textSize, utf32Characters.Begin() );
319     utf32Characters.Resize( characterCount );
320
321     DALI_ASSERT_DEBUG( textSize >= characterCount && "Invalid UTF32 conversion length" );
322     DALI_LOG_INFO( gLogFilter, Debug::Verbose, "Controller::SetText %p UTF8 size %d, UTF32 size %d\n", this, textSize, mImpl->mLogicalModel->mText.Count() );
323
324     // The characters to be added.
325     mImpl->mTextUpdateInfo.mNumberOfCharactersToAdd = mImpl->mLogicalModel->mText.Count();
326
327     // To reset the cursor position
328     lastCursorIndex = characterCount;
329
330     // Update the rest of the model during size negotiation
331     mImpl->QueueModifyEvent( ModifyEvent::TEXT_REPLACED );
332
333     // The natural size needs to be re-calculated.
334     mImpl->mRecalculateNaturalSize = true;
335
336     // Apply modifications to the model
337     mImpl->mOperationsPending = ALL_OPERATIONS;
338   }
339   else
340   {
341     ShowPlaceholderText();
342   }
343
344   // Resets the cursor position.
345   ResetCursorPosition( lastCursorIndex );
346
347   // Scrolls the text to make the cursor visible.
348   ResetScrollPosition();
349
350   mImpl->RequestRelayout();
351
352   if( NULL != mImpl->mEventData )
353   {
354     // Cancel previously queued events
355     mImpl->mEventData->mEventQueue.clear();
356   }
357
358   // Do this last since it provides callbacks into application code
359   mImpl->mControlInterface.TextChanged();
360 }
361
362 void Controller::GetText( std::string& text ) const
363 {
364   if( !mImpl->IsShowingPlaceholderText() )
365   {
366     // Retrieves the text string.
367     mImpl->GetText( 0u, text );
368   }
369   else
370   {
371     DALI_LOG_INFO( gLogFilter, Debug::Verbose, "Controller::GetText %p empty (but showing placeholder)\n", this );
372   }
373 }
374
375 void Controller::SetPlaceholderText( PlaceholderType type, const std::string& text )
376 {
377   if( NULL != mImpl->mEventData )
378   {
379     if( PLACEHOLDER_TYPE_INACTIVE == type )
380     {
381       mImpl->mEventData->mPlaceholderTextInactive = text;
382     }
383     else
384     {
385       mImpl->mEventData->mPlaceholderTextActive = text;
386     }
387
388     // Update placeholder if there is no text
389     if( mImpl->IsShowingPlaceholderText() ||
390         ( 0u == mImpl->mLogicalModel->mText.Count() ) )
391     {
392       ShowPlaceholderText();
393     }
394   }
395 }
396
397 void Controller::GetPlaceholderText( PlaceholderType type, std::string& text ) const
398 {
399   if( NULL != mImpl->mEventData )
400   {
401     if( PLACEHOLDER_TYPE_INACTIVE == type )
402     {
403       text = mImpl->mEventData->mPlaceholderTextInactive;
404     }
405     else
406     {
407       text = mImpl->mEventData->mPlaceholderTextActive;
408     }
409   }
410 }
411
412 void Controller::SetMaximumNumberOfCharacters( Length maxCharacters )
413 {
414   mImpl->mMaximumNumberOfCharacters = maxCharacters;
415 }
416
417 int Controller::GetMaximumNumberOfCharacters()
418 {
419   return mImpl->mMaximumNumberOfCharacters;
420 }
421
422 void Controller::SetDefaultFontFamily( const std::string& defaultFontFamily )
423 {
424   if( NULL == mImpl->mFontDefaults )
425   {
426     mImpl->mFontDefaults = new FontDefaults();
427   }
428
429   mImpl->mFontDefaults->mFontDescription.family = defaultFontFamily;
430   DALI_LOG_INFO( gLogFilter, Debug::General, "Controller::SetDefaultFontFamily %s\n", defaultFontFamily.c_str());
431   mImpl->mFontDefaults->familyDefined = !defaultFontFamily.empty();
432
433   // Clear the font-specific data
434   ClearFontData();
435
436   mImpl->RequestRelayout();
437 }
438
439 const std::string& Controller::GetDefaultFontFamily() const
440 {
441   if( NULL != mImpl->mFontDefaults )
442   {
443     return mImpl->mFontDefaults->mFontDescription.family;
444   }
445
446   return EMPTY_STRING;
447 }
448
449 void Controller::SetDefaultFontWeight( FontWeight weight )
450 {
451   if( NULL == mImpl->mFontDefaults )
452   {
453     mImpl->mFontDefaults = new FontDefaults();
454   }
455
456   mImpl->mFontDefaults->mFontDescription.weight = weight;
457   mImpl->mFontDefaults->weightDefined = true;
458
459   // Clear the font-specific data
460   ClearFontData();
461
462   mImpl->RequestRelayout();
463 }
464
465 bool Controller::IsDefaultFontWeightDefined() const
466 {
467   return mImpl->mFontDefaults->weightDefined;
468 }
469
470 FontWeight Controller::GetDefaultFontWeight() const
471 {
472   if( NULL != mImpl->mFontDefaults )
473   {
474     return mImpl->mFontDefaults->mFontDescription.weight;
475   }
476
477   return TextAbstraction::FontWeight::NORMAL;
478 }
479
480 void Controller::SetDefaultFontWidth( FontWidth width )
481 {
482   if( NULL == mImpl->mFontDefaults )
483   {
484     mImpl->mFontDefaults = new FontDefaults();
485   }
486
487   mImpl->mFontDefaults->mFontDescription.width = width;
488   mImpl->mFontDefaults->widthDefined = true;
489
490   // Clear the font-specific data
491   ClearFontData();
492
493   mImpl->RequestRelayout();
494 }
495
496 bool Controller::IsDefaultFontWidthDefined() const
497 {
498   return mImpl->mFontDefaults->widthDefined;
499 }
500
501 FontWidth Controller::GetDefaultFontWidth() const
502 {
503   if( NULL != mImpl->mFontDefaults )
504   {
505     return mImpl->mFontDefaults->mFontDescription.width;
506   }
507
508   return TextAbstraction::FontWidth::NORMAL;
509 }
510
511 void Controller::SetDefaultFontSlant( FontSlant slant )
512 {
513   if( NULL == mImpl->mFontDefaults )
514   {
515     mImpl->mFontDefaults = new FontDefaults();
516   }
517
518   mImpl->mFontDefaults->mFontDescription.slant = slant;
519   mImpl->mFontDefaults->slantDefined = true;
520
521   // Clear the font-specific data
522   ClearFontData();
523
524   mImpl->RequestRelayout();
525 }
526
527 bool Controller::IsDefaultFontSlantDefined() const
528 {
529   return mImpl->mFontDefaults->slantDefined;
530 }
531
532 FontSlant Controller::GetDefaultFontSlant() const
533 {
534   if( NULL != mImpl->mFontDefaults )
535   {
536     return mImpl->mFontDefaults->mFontDescription.slant;
537   }
538
539   return TextAbstraction::FontSlant::NORMAL;
540 }
541
542 void Controller::SetDefaultPointSize( float pointSize )
543 {
544   if( NULL == mImpl->mFontDefaults )
545   {
546     mImpl->mFontDefaults = new FontDefaults();
547   }
548
549   mImpl->mFontDefaults->mDefaultPointSize = pointSize;
550   mImpl->mFontDefaults->sizeDefined = true;
551
552   // Clear the font-specific data
553   ClearFontData();
554
555   mImpl->RequestRelayout();
556 }
557
558 float Controller::GetDefaultPointSize() const
559 {
560   if( NULL != mImpl->mFontDefaults )
561   {
562     return mImpl->mFontDefaults->mDefaultPointSize;
563   }
564
565   return 0.0f;
566 }
567
568 void Controller::UpdateAfterFontChange( const std::string& newDefaultFont )
569 {
570   DALI_LOG_INFO( gLogFilter, Debug::Verbose, "Controller::UpdateAfterFontChange\n");
571
572   if( !mImpl->mFontDefaults->familyDefined ) // If user defined font then should not update when system font changes
573   {
574     DALI_LOG_INFO( gLogFilter, Debug::Concise, "Controller::UpdateAfterFontChange newDefaultFont(%s)\n", newDefaultFont.c_str() );
575     mImpl->mFontDefaults->mFontDescription.family = newDefaultFont;
576
577     ClearFontData();
578
579     mImpl->RequestRelayout();
580   }
581 }
582
583 void Controller::SetTextColor( const Vector4& textColor )
584 {
585   mImpl->mTextColor = textColor;
586
587   if( !mImpl->IsShowingPlaceholderText() )
588   {
589     mImpl->mVisualModel->SetTextColor( textColor );
590
591     mImpl->RequestRelayout();
592   }
593 }
594
595 const Vector4& Controller::GetTextColor() const
596 {
597   return mImpl->mTextColor;
598 }
599
600 bool Controller::RemoveText( int cursorOffset,
601                              int numberOfCharacters,
602                              UpdateInputStyleType type )
603 {
604   bool removed = false;
605
606   if( NULL == mImpl->mEventData )
607   {
608     return removed;
609   }
610
611   DALI_LOG_INFO( gLogFilter, Debug::General, "Controller::RemoveText %p mText.Count() %d cursor %d cursorOffset %d numberOfCharacters %d\n",
612                  this, mImpl->mLogicalModel->mText.Count(), mImpl->mEventData->mPrimaryCursorPosition, cursorOffset, numberOfCharacters );
613
614   if( !mImpl->IsShowingPlaceholderText() )
615   {
616     // Delete at current cursor position
617     Vector<Character>& currentText = mImpl->mLogicalModel->mText;
618     CharacterIndex& oldCursorIndex = mImpl->mEventData->mPrimaryCursorPosition;
619
620     CharacterIndex cursorIndex = oldCursorIndex;
621
622     // Validate the cursor position & number of characters
623     if( static_cast< CharacterIndex >( std::abs( cursorOffset ) ) <= cursorIndex )
624     {
625       cursorIndex = oldCursorIndex + cursorOffset;
626     }
627
628     if( ( cursorIndex + numberOfCharacters ) > currentText.Count() )
629     {
630       numberOfCharacters = currentText.Count() - cursorIndex;
631     }
632
633     if( ( cursorIndex + numberOfCharacters ) <= mImpl->mTextUpdateInfo.mPreviousNumberOfCharacters )
634     {
635       // Mark the paragraphs to be updated.
636       mImpl->mTextUpdateInfo.mCharacterIndex = std::min( cursorIndex, mImpl->mTextUpdateInfo.mCharacterIndex );
637       mImpl->mTextUpdateInfo.mNumberOfCharactersToRemove += numberOfCharacters;
638
639       // Update the input style and remove the text's style before removing the text.
640
641       if( UPDATE_INPUT_STYLE == type )
642       {
643         // Set first the default input style.
644         mImpl->RetrieveDefaultInputStyle( mImpl->mEventData->mInputStyle );
645
646         // Update the input style.
647         mImpl->mLogicalModel->RetrieveStyle( cursorIndex, mImpl->mEventData->mInputStyle );
648       }
649
650       // Updates the text style runs by removing characters. Runs with no characters are removed.
651       mImpl->mLogicalModel->UpdateTextStyleRuns( cursorIndex, -numberOfCharacters );
652
653       // Remove the characters.
654       Vector<Character>::Iterator first = currentText.Begin() + cursorIndex;
655       Vector<Character>::Iterator last  = first + numberOfCharacters;
656
657       currentText.Erase( first, last );
658
659       // Cursor position retreat
660       oldCursorIndex = cursorIndex;
661
662       mImpl->mEventData->mScrollAfterDelete = true;
663
664       DALI_LOG_INFO( gLogFilter, Debug::General, "Controller::RemoveText %p removed %d\n", this, numberOfCharacters );
665       removed = true;
666     }
667   }
668
669   return removed;
670 }
671
672 void Controller::SetPlaceholderTextColor( const Vector4& textColor )
673 {
674   if( NULL != mImpl->mEventData )
675   {
676     mImpl->mEventData->mPlaceholderTextColor = textColor;
677   }
678
679   if( mImpl->IsShowingPlaceholderText() )
680   {
681     mImpl->mVisualModel->SetTextColor( textColor );
682     mImpl->RequestRelayout();
683   }
684 }
685
686 const Vector4& Controller::GetPlaceholderTextColor() const
687 {
688   if( NULL != mImpl->mEventData )
689   {
690     return mImpl->mEventData->mPlaceholderTextColor;
691   }
692
693   return Color::BLACK;
694 }
695
696 void Controller::SetShadowOffset( const Vector2& shadowOffset )
697 {
698   mImpl->mVisualModel->SetShadowOffset( shadowOffset );
699
700   mImpl->RequestRelayout();
701 }
702
703 const Vector2& Controller::GetShadowOffset() const
704 {
705   return mImpl->mVisualModel->GetShadowOffset();
706 }
707
708 void Controller::SetShadowColor( const Vector4& shadowColor )
709 {
710   mImpl->mVisualModel->SetShadowColor( shadowColor );
711
712   mImpl->RequestRelayout();
713 }
714
715 const Vector4& Controller::GetShadowColor() const
716 {
717   return mImpl->mVisualModel->GetShadowColor();
718 }
719
720 void Controller::SetDefaultShadowProperties( const std::string& shadowProperties )
721 {
722   if( NULL == mImpl->mShadowDefaults )
723   {
724     mImpl->mShadowDefaults = new ShadowDefaults();
725   }
726
727   mImpl->mShadowDefaults->properties = shadowProperties;
728 }
729
730 const std::string& Controller::GetDefaultShadowProperties() const
731 {
732   if( NULL != mImpl->mShadowDefaults )
733   {
734     return mImpl->mShadowDefaults->properties;
735   }
736
737   return EMPTY_STRING;
738 }
739
740 void Controller::SetUnderlineColor( const Vector4& color )
741 {
742   mImpl->mVisualModel->SetUnderlineColor( color );
743
744   mImpl->RequestRelayout();
745 }
746
747 const Vector4& Controller::GetUnderlineColor() const
748 {
749   return mImpl->mVisualModel->GetUnderlineColor();
750 }
751
752 void Controller::SetUnderlineEnabled( bool enabled )
753 {
754   mImpl->mVisualModel->SetUnderlineEnabled( enabled );
755
756   mImpl->RequestRelayout();
757 }
758
759 bool Controller::IsUnderlineEnabled() const
760 {
761   return mImpl->mVisualModel->IsUnderlineEnabled();
762 }
763
764 void Controller::SetUnderlineHeight( float height )
765 {
766   mImpl->mVisualModel->SetUnderlineHeight( height );
767
768   mImpl->RequestRelayout();
769 }
770
771 float Controller::GetUnderlineHeight() const
772 {
773   return mImpl->mVisualModel->GetUnderlineHeight();
774 }
775
776 void Controller::SetDefaultUnderlineProperties( const std::string& underlineProperties )
777 {
778   if( NULL == mImpl->mUnderlineDefaults )
779   {
780     mImpl->mUnderlineDefaults = new UnderlineDefaults();
781   }
782
783   mImpl->mUnderlineDefaults->properties = underlineProperties;
784 }
785
786 const std::string& Controller::GetDefaultUnderlineProperties() const
787 {
788   if( NULL != mImpl->mUnderlineDefaults )
789   {
790     return mImpl->mUnderlineDefaults->properties;
791   }
792
793   return EMPTY_STRING;
794 }
795
796 void Controller::SetDefaultEmbossProperties( const std::string& embossProperties )
797 {
798   if( NULL == mImpl->mEmbossDefaults )
799   {
800     mImpl->mEmbossDefaults = new EmbossDefaults();
801   }
802
803   mImpl->mEmbossDefaults->properties = embossProperties;
804 }
805
806 const std::string& Controller::GetDefaultEmbossProperties() const
807 {
808   if( NULL != mImpl->mEmbossDefaults )
809   {
810     return mImpl->mEmbossDefaults->properties;
811   }
812
813   return EMPTY_STRING;
814 }
815
816 void Controller::SetDefaultOutlineProperties( const std::string& outlineProperties )
817 {
818   if( NULL == mImpl->mOutlineDefaults )
819   {
820     mImpl->mOutlineDefaults = new OutlineDefaults();
821   }
822
823   mImpl->mOutlineDefaults->properties = outlineProperties;
824 }
825
826 const std::string& Controller::GetDefaultOutlineProperties() const
827 {
828   if( NULL != mImpl->mOutlineDefaults )
829   {
830     return mImpl->mOutlineDefaults->properties;
831   }
832
833   return EMPTY_STRING;
834 }
835
836 void Controller::SetDefaultLineSpacing( float lineSpacing )
837 {
838   //TODO finish implementation
839   mImpl->mLayoutEngine.SetDefaultLineSpacing( lineSpacing );
840 }
841
842 float Controller::GetDefaultLineSpacing() const
843 {
844   return mImpl->mLayoutEngine.GetDefaultLineSpacing();
845 }
846
847 void Controller::SetInputColor( const Vector4& color )
848 {
849   if( NULL != mImpl->mEventData )
850   {
851     mImpl->mEventData->mInputStyle.textColor = color;
852     mImpl->mEventData->mInputStyle.isDefaultColor = false;
853
854     if( EventData::SELECTING == mImpl->mEventData->mState )
855     {
856       const bool handlesCrossed = mImpl->mEventData->mLeftSelectionPosition > mImpl->mEventData->mRightSelectionPosition;
857
858       // Get start and end position of selection
859       const CharacterIndex startOfSelectedText = handlesCrossed ? mImpl->mEventData->mRightSelectionPosition : mImpl->mEventData->mLeftSelectionPosition;
860       const Length lengthOfSelectedText = ( handlesCrossed ? mImpl->mEventData->mLeftSelectionPosition : mImpl->mEventData->mRightSelectionPosition ) - startOfSelectedText;
861
862       // Add the color run.
863       const VectorBase::SizeType numberOfRuns = mImpl->mLogicalModel->mColorRuns.Count();
864       mImpl->mLogicalModel->mColorRuns.Resize( numberOfRuns + 1u );
865
866       ColorRun& colorRun = *( mImpl->mLogicalModel->mColorRuns.Begin() + numberOfRuns );
867       colorRun.color = color;
868       colorRun.characterRun.characterIndex = startOfSelectedText;
869       colorRun.characterRun.numberOfCharacters = lengthOfSelectedText;
870
871       // Request to relayout.
872       mImpl->mOperationsPending = static_cast<OperationsMask>( mImpl->mOperationsPending | COLOR );
873       mImpl->RequestRelayout();
874
875       mImpl->mTextUpdateInfo.mCharacterIndex = startOfSelectedText;
876       mImpl->mTextUpdateInfo.mNumberOfCharactersToRemove = lengthOfSelectedText;
877       mImpl->mTextUpdateInfo.mNumberOfCharactersToAdd = lengthOfSelectedText;
878     }
879   }
880 }
881
882 const Vector4& Controller::GetInputColor() const
883 {
884   if( NULL != mImpl->mEventData )
885   {
886     return mImpl->mEventData->mInputStyle.textColor;
887   }
888
889   // Return the default text's color if there is no EventData.
890   return mImpl->mTextColor;
891
892 }
893
894 void Controller::SetInputFontFamily( const std::string& fontFamily )
895 {
896   if( NULL != mImpl->mEventData )
897   {
898     mImpl->mEventData->mInputStyle.familyName = fontFamily;
899     mImpl->mEventData->mInputStyle.familyDefined = true;
900
901     if( EventData::SELECTING == mImpl->mEventData->mState )
902     {
903       CharacterIndex startOfSelectedText = 0u;
904       Length lengthOfSelectedText = 0u;
905       FontDescriptionRun& fontDescriptionRun = UpdateSelectionFontStyleRun( mImpl->mEventData,
906                                                                             mImpl->mLogicalModel,
907                                                                             startOfSelectedText,
908                                                                             lengthOfSelectedText );
909
910       fontDescriptionRun.familyLength = fontFamily.size();
911       fontDescriptionRun.familyName = new char[fontDescriptionRun.familyLength];
912       memcpy( fontDescriptionRun.familyName, fontFamily.c_str(), fontDescriptionRun.familyLength );
913       fontDescriptionRun.familyDefined = true;
914
915       // The memory allocated for the font family name is freed when the font description is removed from the logical model.
916
917       // Request to relayout.
918       mImpl->mOperationsPending = static_cast<OperationsMask>( mImpl->mOperationsPending |
919                                                                VALIDATE_FONTS            |
920                                                                SHAPE_TEXT                |
921                                                                GET_GLYPH_METRICS         |
922                                                                LAYOUT                    |
923                                                                UPDATE_LAYOUT_SIZE        |
924                                                                REORDER                   |
925                                                                ALIGN );
926       mImpl->mRecalculateNaturalSize = true;
927       mImpl->RequestRelayout();
928
929       mImpl->mTextUpdateInfo.mCharacterIndex = startOfSelectedText;
930       mImpl->mTextUpdateInfo.mNumberOfCharactersToRemove = lengthOfSelectedText;
931       mImpl->mTextUpdateInfo.mNumberOfCharactersToAdd = lengthOfSelectedText;
932
933       // As the font changes, recalculate the handle positions is needed.
934       mImpl->mEventData->mUpdateLeftSelectionPosition = true;
935       mImpl->mEventData->mUpdateRightSelectionPosition = true;
936       mImpl->mEventData->mUpdateHighlightBox = true;
937       mImpl->mEventData->mScrollAfterUpdatePosition = true;
938     }
939   }
940 }
941
942 const std::string& Controller::GetInputFontFamily() const
943 {
944   if( NULL != mImpl->mEventData )
945   {
946     return mImpl->mEventData->mInputStyle.familyName;
947   }
948
949   // Return the default font's family if there is no EventData.
950   return GetDefaultFontFamily();
951 }
952
953 void Controller::SetInputFontWeight( FontWeight weight )
954 {
955   if( NULL != mImpl->mEventData )
956   {
957     mImpl->mEventData->mInputStyle.weight = weight;
958     mImpl->mEventData->mInputStyle.weightDefined = true;
959
960     if( EventData::SELECTING == mImpl->mEventData->mState )
961     {
962       CharacterIndex startOfSelectedText = 0u;
963       Length lengthOfSelectedText = 0u;
964       FontDescriptionRun& fontDescriptionRun = UpdateSelectionFontStyleRun( mImpl->mEventData,
965                                                                             mImpl->mLogicalModel,
966                                                                             startOfSelectedText,
967                                                                             lengthOfSelectedText );
968
969       fontDescriptionRun.weight = weight;
970       fontDescriptionRun.weightDefined = true;
971
972       // Request to relayout.
973       mImpl->mOperationsPending = static_cast<OperationsMask>( mImpl->mOperationsPending |
974                                                                VALIDATE_FONTS            |
975                                                                SHAPE_TEXT                |
976                                                                GET_GLYPH_METRICS         |
977                                                                LAYOUT                    |
978                                                                UPDATE_LAYOUT_SIZE        |
979                                                                REORDER                   |
980                                                                ALIGN );
981       mImpl->mRecalculateNaturalSize = true;
982       mImpl->RequestRelayout();
983
984       mImpl->mTextUpdateInfo.mCharacterIndex = startOfSelectedText;
985       mImpl->mTextUpdateInfo.mNumberOfCharactersToRemove = lengthOfSelectedText;
986       mImpl->mTextUpdateInfo.mNumberOfCharactersToAdd = lengthOfSelectedText;
987
988       // As the font might change, recalculate the handle positions is needed.
989       mImpl->mEventData->mUpdateLeftSelectionPosition = true;
990       mImpl->mEventData->mUpdateRightSelectionPosition = true;
991       mImpl->mEventData->mUpdateHighlightBox = true;
992       mImpl->mEventData->mScrollAfterUpdatePosition = true;
993     }
994   }
995 }
996
997 bool Controller::IsInputFontWeightDefined() const
998 {
999   bool defined = false;
1000
1001   if( NULL != mImpl->mEventData )
1002   {
1003     defined = mImpl->mEventData->mInputStyle.weightDefined;
1004   }
1005
1006   return defined;
1007 }
1008
1009 FontWeight Controller::GetInputFontWeight() const
1010 {
1011   if( NULL != mImpl->mEventData )
1012   {
1013     return mImpl->mEventData->mInputStyle.weight;
1014   }
1015
1016   return GetDefaultFontWeight();
1017 }
1018
1019 void Controller::SetInputFontWidth( FontWidth width )
1020 {
1021   if( NULL != mImpl->mEventData )
1022   {
1023     mImpl->mEventData->mInputStyle.width = width;
1024     mImpl->mEventData->mInputStyle.widthDefined = true;
1025
1026     if( EventData::SELECTING == mImpl->mEventData->mState )
1027     {
1028       CharacterIndex startOfSelectedText = 0u;
1029       Length lengthOfSelectedText = 0u;
1030       FontDescriptionRun& fontDescriptionRun = UpdateSelectionFontStyleRun( mImpl->mEventData,
1031                                                                             mImpl->mLogicalModel,
1032                                                                             startOfSelectedText,
1033                                                                             lengthOfSelectedText );
1034
1035       fontDescriptionRun.width = width;
1036       fontDescriptionRun.widthDefined = true;
1037
1038       // Request to relayout.
1039       mImpl->mOperationsPending = static_cast<OperationsMask>( mImpl->mOperationsPending |
1040                                                                VALIDATE_FONTS            |
1041                                                                SHAPE_TEXT                |
1042                                                                GET_GLYPH_METRICS         |
1043                                                                LAYOUT                    |
1044                                                                UPDATE_LAYOUT_SIZE        |
1045                                                                REORDER                   |
1046                                                                ALIGN );
1047       mImpl->mRecalculateNaturalSize = true;
1048       mImpl->RequestRelayout();
1049
1050       mImpl->mTextUpdateInfo.mCharacterIndex = startOfSelectedText;
1051       mImpl->mTextUpdateInfo.mNumberOfCharactersToRemove = lengthOfSelectedText;
1052       mImpl->mTextUpdateInfo.mNumberOfCharactersToAdd = lengthOfSelectedText;
1053
1054       // As the font might change, recalculate the handle positions is needed.
1055       mImpl->mEventData->mUpdateLeftSelectionPosition = true;
1056       mImpl->mEventData->mUpdateRightSelectionPosition = true;
1057       mImpl->mEventData->mUpdateHighlightBox = true;
1058       mImpl->mEventData->mScrollAfterUpdatePosition = true;
1059     }
1060   }
1061 }
1062
1063 bool Controller::IsInputFontWidthDefined() const
1064 {
1065   bool defined = false;
1066
1067   if( NULL != mImpl->mEventData )
1068   {
1069     defined = mImpl->mEventData->mInputStyle.widthDefined;
1070   }
1071
1072   return defined;
1073 }
1074
1075 FontWidth Controller::GetInputFontWidth() const
1076 {
1077   if( NULL != mImpl->mEventData )
1078   {
1079     return mImpl->mEventData->mInputStyle.width;
1080   }
1081
1082   return GetDefaultFontWidth();
1083 }
1084
1085 void Controller::SetInputFontSlant( FontSlant slant )
1086 {
1087   if( NULL != mImpl->mEventData )
1088   {
1089     mImpl->mEventData->mInputStyle.slant = slant;
1090     mImpl->mEventData->mInputStyle.slantDefined = true;
1091
1092     if( EventData::SELECTING == mImpl->mEventData->mState )
1093     {
1094       CharacterIndex startOfSelectedText = 0u;
1095       Length lengthOfSelectedText = 0u;
1096       FontDescriptionRun& fontDescriptionRun = UpdateSelectionFontStyleRun( mImpl->mEventData,
1097                                                                             mImpl->mLogicalModel,
1098                                                                             startOfSelectedText,
1099                                                                             lengthOfSelectedText );
1100
1101       fontDescriptionRun.slant = slant;
1102       fontDescriptionRun.slantDefined = true;
1103
1104       // Request to relayout.
1105       mImpl->mOperationsPending = static_cast<OperationsMask>( mImpl->mOperationsPending |
1106                                                                VALIDATE_FONTS            |
1107                                                                SHAPE_TEXT                |
1108                                                                GET_GLYPH_METRICS         |
1109                                                                LAYOUT                    |
1110                                                                UPDATE_LAYOUT_SIZE        |
1111                                                                REORDER                   |
1112                                                                ALIGN );
1113       mImpl->mRecalculateNaturalSize = true;
1114       mImpl->RequestRelayout();
1115
1116       mImpl->mTextUpdateInfo.mCharacterIndex = startOfSelectedText;
1117       mImpl->mTextUpdateInfo.mNumberOfCharactersToRemove = lengthOfSelectedText;
1118       mImpl->mTextUpdateInfo.mNumberOfCharactersToAdd = lengthOfSelectedText;
1119
1120       // As the font might change, recalculate the handle positions is needed.
1121       mImpl->mEventData->mUpdateLeftSelectionPosition = true;
1122       mImpl->mEventData->mUpdateRightSelectionPosition = true;
1123       mImpl->mEventData->mUpdateHighlightBox = true;
1124       mImpl->mEventData->mScrollAfterUpdatePosition = true;
1125     }
1126   }
1127 }
1128
1129 bool Controller::IsInputFontSlantDefined() const
1130 {
1131   bool defined = false;
1132
1133   if( NULL != mImpl->mEventData )
1134   {
1135     defined = mImpl->mEventData->mInputStyle.slantDefined;
1136   }
1137
1138   return defined;
1139 }
1140
1141 FontSlant Controller::GetInputFontSlant() const
1142 {
1143   if( NULL != mImpl->mEventData )
1144   {
1145     return mImpl->mEventData->mInputStyle.slant;
1146   }
1147
1148   return GetDefaultFontSlant();
1149 }
1150
1151 void Controller::SetInputFontPointSize( float size )
1152 {
1153   if( NULL != mImpl->mEventData )
1154   {
1155     mImpl->mEventData->mInputStyle.size = size;
1156
1157     if( EventData::SELECTING == mImpl->mEventData->mState )
1158     {
1159       CharacterIndex startOfSelectedText = 0u;
1160       Length lengthOfSelectedText = 0u;
1161       FontDescriptionRun& fontDescriptionRun = UpdateSelectionFontStyleRun( mImpl->mEventData,
1162                                                                             mImpl->mLogicalModel,
1163                                                                             startOfSelectedText,
1164                                                                             lengthOfSelectedText );
1165
1166       fontDescriptionRun.size = static_cast<PointSize26Dot6>( size * 64.f );
1167       fontDescriptionRun.sizeDefined = true;
1168
1169       // Request to relayout.
1170       mImpl->mOperationsPending = static_cast<OperationsMask>( mImpl->mOperationsPending |
1171                                                                VALIDATE_FONTS            |
1172                                                                SHAPE_TEXT                |
1173                                                                GET_GLYPH_METRICS         |
1174                                                                LAYOUT                    |
1175                                                                UPDATE_LAYOUT_SIZE        |
1176                                                                REORDER                   |
1177                                                                ALIGN );
1178       mImpl->mRecalculateNaturalSize = true;
1179       mImpl->RequestRelayout();
1180
1181       mImpl->mTextUpdateInfo.mCharacterIndex = startOfSelectedText;
1182       mImpl->mTextUpdateInfo.mNumberOfCharactersToRemove = lengthOfSelectedText;
1183       mImpl->mTextUpdateInfo.mNumberOfCharactersToAdd = lengthOfSelectedText;
1184
1185       // As the font might change, recalculate the handle positions is needed.
1186       mImpl->mEventData->mUpdateLeftSelectionPosition = true;
1187       mImpl->mEventData->mUpdateRightSelectionPosition = true;
1188       mImpl->mEventData->mUpdateHighlightBox = true;
1189       mImpl->mEventData->mScrollAfterUpdatePosition = true;
1190     }
1191   }
1192 }
1193
1194 float Controller::GetInputFontPointSize() const
1195 {
1196   if( NULL != mImpl->mEventData )
1197   {
1198     return mImpl->mEventData->mInputStyle.size;
1199   }
1200
1201   // Return the default font's point size if there is no EventData.
1202   return GetDefaultPointSize();
1203 }
1204
1205 void Controller::SetInputLineSpacing( float lineSpacing )
1206 {
1207   if( NULL != mImpl->mEventData )
1208   {
1209     mImpl->mEventData->mInputStyle.lineSpacing = lineSpacing;
1210   }
1211 }
1212
1213 float Controller::GetInputLineSpacing() const
1214 {
1215   if( NULL != mImpl->mEventData )
1216   {
1217     return mImpl->mEventData->mInputStyle.lineSpacing;
1218   }
1219
1220   return 0.f;
1221 }
1222
1223 void Controller::SetInputShadowProperties( const std::string& shadowProperties )
1224 {
1225   if( NULL != mImpl->mEventData )
1226   {
1227     mImpl->mEventData->mInputStyle.shadowProperties = shadowProperties;
1228   }
1229 }
1230
1231 const std::string& Controller::GetInputShadowProperties() const
1232 {
1233   if( NULL != mImpl->mEventData )
1234   {
1235     return mImpl->mEventData->mInputStyle.shadowProperties;
1236   }
1237
1238   return GetDefaultShadowProperties();
1239 }
1240
1241 void Controller::SetInputUnderlineProperties( const std::string& underlineProperties )
1242 {
1243   if( NULL != mImpl->mEventData )
1244   {
1245     mImpl->mEventData->mInputStyle.underlineProperties = underlineProperties;
1246   }
1247 }
1248
1249 const std::string& Controller::GetInputUnderlineProperties() const
1250 {
1251   if( NULL != mImpl->mEventData )
1252   {
1253     return mImpl->mEventData->mInputStyle.underlineProperties;
1254   }
1255
1256   return GetDefaultUnderlineProperties();
1257 }
1258
1259 void Controller::SetInputEmbossProperties( const std::string& embossProperties )
1260 {
1261   if( NULL != mImpl->mEventData )
1262   {
1263     mImpl->mEventData->mInputStyle.embossProperties = embossProperties;
1264   }
1265 }
1266
1267 const std::string& Controller::GetInputEmbossProperties() const
1268 {
1269   if( NULL != mImpl->mEventData )
1270   {
1271     return mImpl->mEventData->mInputStyle.embossProperties;
1272   }
1273
1274   return GetDefaultEmbossProperties();
1275 }
1276
1277 void Controller::SetInputOutlineProperties( const std::string& outlineProperties )
1278 {
1279   if( NULL != mImpl->mEventData )
1280   {
1281     mImpl->mEventData->mInputStyle.outlineProperties = outlineProperties;
1282   }
1283 }
1284
1285 const std::string& Controller::GetInputOutlineProperties() const
1286 {
1287   if( NULL != mImpl->mEventData )
1288   {
1289     return mImpl->mEventData->mInputStyle.outlineProperties;
1290   }
1291
1292   return GetDefaultOutlineProperties();
1293 }
1294
1295 void Controller::SetEnableCursorBlink( bool enable )
1296 {
1297   DALI_ASSERT_DEBUG( NULL != mImpl->mEventData && "TextInput disabled" );
1298
1299   if( NULL != mImpl->mEventData )
1300   {
1301     mImpl->mEventData->mCursorBlinkEnabled = enable;
1302
1303     if( !enable &&
1304         mImpl->mEventData->mDecorator )
1305     {
1306       mImpl->mEventData->mDecorator->StopCursorBlink();
1307     }
1308   }
1309 }
1310
1311 bool Controller::GetEnableCursorBlink() const
1312 {
1313   if( NULL != mImpl->mEventData )
1314   {
1315     return mImpl->mEventData->mCursorBlinkEnabled;
1316   }
1317
1318   return false;
1319 }
1320
1321 const Vector2& Controller::GetScrollPosition() const
1322 {
1323   return mImpl->mScrollPosition;
1324 }
1325
1326 Vector3 Controller::GetNaturalSize()
1327 {
1328   DALI_LOG_INFO( gLogFilter, Debug::Verbose, "-->Controller::GetNaturalSize\n" );
1329   Vector3 naturalSize;
1330
1331   // Make sure the model is up-to-date before layouting
1332   ProcessModifyEvents();
1333
1334   if( mImpl->mRecalculateNaturalSize )
1335   {
1336     // Operations that can be done only once until the text changes.
1337     const OperationsMask onlyOnceOperations = static_cast<OperationsMask>( CONVERT_TO_UTF32  |
1338                                                                            GET_SCRIPTS       |
1339                                                                            VALIDATE_FONTS    |
1340                                                                            GET_LINE_BREAKS   |
1341                                                                            GET_WORD_BREAKS   |
1342                                                                            BIDI_INFO         |
1343                                                                            SHAPE_TEXT        |
1344                                                                            GET_GLYPH_METRICS );
1345     // Make sure the model is up-to-date before layouting
1346     mImpl->UpdateModel( onlyOnceOperations );
1347
1348     // Layout the text for the new width.
1349     mImpl->mOperationsPending = static_cast<OperationsMask>( mImpl->mOperationsPending | LAYOUT );
1350
1351     // Set the update info to relayout the whole text.
1352     mImpl->mTextUpdateInfo.mParagraphCharacterIndex = 0u;
1353     mImpl->mTextUpdateInfo.mRequestedNumberOfCharacters = mImpl->mLogicalModel->mText.Count();
1354
1355     // Store the actual control's size to restore later.
1356     const Size actualControlSize = mImpl->mVisualModel->mControlSize;
1357
1358     DoRelayout( Size( MAX_FLOAT, MAX_FLOAT ),
1359                 static_cast<OperationsMask>( onlyOnceOperations |
1360                                              LAYOUT ),
1361                 naturalSize.GetVectorXY() );
1362
1363     // Do not do again the only once operations.
1364     mImpl->mOperationsPending = static_cast<OperationsMask>( mImpl->mOperationsPending & ~onlyOnceOperations );
1365
1366     // Do the size related operations again.
1367     const OperationsMask sizeOperations =  static_cast<OperationsMask>( LAYOUT |
1368                                                                         ALIGN  |
1369                                                                         REORDER );
1370     mImpl->mOperationsPending = static_cast<OperationsMask>( mImpl->mOperationsPending | sizeOperations );
1371
1372     // Stores the natural size to avoid recalculate it again
1373     // unless the text/style changes.
1374     mImpl->mVisualModel->SetNaturalSize( naturalSize.GetVectorXY() );
1375
1376     mImpl->mRecalculateNaturalSize = false;
1377
1378     // Clear the update info. This info will be set the next time the text is updated.
1379     mImpl->mTextUpdateInfo.Clear();
1380
1381     // Restore the actual control's size.
1382     mImpl->mVisualModel->mControlSize = actualControlSize;
1383
1384     DALI_LOG_INFO( gLogFilter, Debug::Verbose, "<--Controller::GetNaturalSize calculated %f,%f,%f\n", naturalSize.x, naturalSize.y, naturalSize.z );
1385   }
1386   else
1387   {
1388     naturalSize = mImpl->mVisualModel->GetNaturalSize();
1389
1390     DALI_LOG_INFO( gLogFilter, Debug::Verbose, "<--Controller::GetNaturalSize cached %f,%f,%f\n", naturalSize.x, naturalSize.y, naturalSize.z );
1391   }
1392
1393   naturalSize.x = ConvertToEven( naturalSize.x );
1394   naturalSize.y = ConvertToEven( naturalSize.y );
1395
1396   return naturalSize;
1397 }
1398
1399 float Controller::GetHeightForWidth( float width )
1400 {
1401   DALI_LOG_INFO( gLogFilter, Debug::Verbose, "-->Controller::GetHeightForWidth %p width %f\n", this, width );
1402   // Make sure the model is up-to-date before layouting
1403   ProcessModifyEvents();
1404
1405   Size layoutSize;
1406   if( fabsf( width - mImpl->mVisualModel->mControlSize.width ) > Math::MACHINE_EPSILON_1000 )
1407   {
1408     // Operations that can be done only once until the text changes.
1409     const OperationsMask onlyOnceOperations = static_cast<OperationsMask>( CONVERT_TO_UTF32  |
1410                                                                            GET_SCRIPTS       |
1411                                                                            VALIDATE_FONTS    |
1412                                                                            GET_LINE_BREAKS   |
1413                                                                            GET_WORD_BREAKS   |
1414                                                                            BIDI_INFO         |
1415                                                                            SHAPE_TEXT        |
1416                                                                            GET_GLYPH_METRICS );
1417     // Make sure the model is up-to-date before layouting
1418     mImpl->UpdateModel( onlyOnceOperations );
1419
1420
1421     // Layout the text for the new width.
1422     mImpl->mOperationsPending = static_cast<OperationsMask>( mImpl->mOperationsPending | LAYOUT );
1423
1424     // Set the update info to relayout the whole text.
1425     mImpl->mTextUpdateInfo.mParagraphCharacterIndex = 0u;
1426     mImpl->mTextUpdateInfo.mRequestedNumberOfCharacters = mImpl->mLogicalModel->mText.Count();
1427
1428     // Store the actual control's width.
1429     const float actualControlWidth = mImpl->mVisualModel->mControlSize.width;
1430
1431     DoRelayout( Size( width, MAX_FLOAT ),
1432                 static_cast<OperationsMask>( onlyOnceOperations |
1433                                              LAYOUT ),
1434                 layoutSize );
1435
1436     // Do not do again the only once operations.
1437     mImpl->mOperationsPending = static_cast<OperationsMask>( mImpl->mOperationsPending & ~onlyOnceOperations );
1438
1439     // Do the size related operations again.
1440     const OperationsMask sizeOperations =  static_cast<OperationsMask>( LAYOUT |
1441                                                                         ALIGN  |
1442                                                                         REORDER );
1443
1444     mImpl->mOperationsPending = static_cast<OperationsMask>( mImpl->mOperationsPending | sizeOperations );
1445
1446     // Clear the update info. This info will be set the next time the text is updated.
1447     mImpl->mTextUpdateInfo.Clear();
1448
1449     // Restore the actual control's width.
1450     mImpl->mVisualModel->mControlSize.width = actualControlWidth;
1451
1452     DALI_LOG_INFO( gLogFilter, Debug::Verbose, "<--Controller::GetHeightForWidth calculated %f\n", layoutSize.height );
1453   }
1454   else
1455   {
1456     layoutSize = mImpl->mVisualModel->GetLayoutSize();
1457     DALI_LOG_INFO( gLogFilter, Debug::Verbose, "<--Controller::GetHeightForWidth cached %f\n", layoutSize.height );
1458   }
1459
1460   return layoutSize.height;
1461 }
1462
1463 Controller::UpdateTextType Controller::Relayout( const Size& size )
1464 {
1465   DALI_LOG_INFO( gLogFilter, Debug::Verbose, "-->Controller::Relayout %p size %f,%f, autoScroll[%s]\n", this, size.width, size.height, (mImpl->mAutoScrollEnabled)?"true":"false"  );
1466
1467   UpdateTextType updateTextType = NONE_UPDATED;
1468
1469   if( ( size.width < Math::MACHINE_EPSILON_1000 ) || ( size.height < Math::MACHINE_EPSILON_1000 ) )
1470   {
1471     if( 0u != mImpl->mVisualModel->mGlyphPositions.Count() )
1472     {
1473       mImpl->mVisualModel->mGlyphPositions.Clear();
1474       updateTextType = MODEL_UPDATED;
1475     }
1476
1477     // Clear the update info. This info will be set the next time the text is updated.
1478     mImpl->mTextUpdateInfo.Clear();
1479
1480     // Not worth to relayout if width or height is equal to zero.
1481     DALI_LOG_INFO( gLogFilter, Debug::Verbose, "<--Controller::Relayout (skipped)\n" );
1482
1483     return updateTextType;
1484   }
1485
1486   // Whether a new size has been set.
1487   const bool newSize = ( size != mImpl->mVisualModel->mControlSize );
1488
1489   if( newSize )
1490   {
1491     DALI_LOG_INFO( gLogFilter, Debug::Verbose, "new size (previous size %f,%f)\n", mImpl->mVisualModel->mControlSize.width, mImpl->mVisualModel->mControlSize.height );
1492
1493     // Layout operations that need to be done if the size changes.
1494     mImpl->mOperationsPending = static_cast<OperationsMask>( mImpl->mOperationsPending |
1495                                                              LAYOUT                    |
1496                                                              ALIGN                     |
1497                                                              UPDATE_LAYOUT_SIZE        |
1498                                                              REORDER );
1499     // Set the update info to relayout the whole text.
1500     mImpl->mTextUpdateInfo.mFullRelayoutNeeded = true;
1501     mImpl->mTextUpdateInfo.mCharacterIndex = 0u;
1502   }
1503
1504   // Whether there are modify events.
1505   if( 0u != mImpl->mModifyEvents.Count() )
1506   {
1507     // Style operations that need to be done if the text is modified.
1508     mImpl->mOperationsPending = static_cast<OperationsMask>( mImpl->mOperationsPending |
1509                                                              COLOR );
1510   }
1511
1512   // Make sure the model is up-to-date before layouting.
1513   ProcessModifyEvents();
1514   bool updated = mImpl->UpdateModel( mImpl->mOperationsPending );
1515
1516   // Layout the text.
1517   Size layoutSize;
1518   updated = DoRelayout( size,
1519                         mImpl->mOperationsPending,
1520                         layoutSize ) || updated;
1521
1522   if( updated )
1523   {
1524     updateTextType = MODEL_UPDATED;
1525   }
1526
1527   // Do not re-do any operation until something changes.
1528   mImpl->mOperationsPending = NO_OPERATION;
1529
1530   // Whether the text control is editable
1531   const bool isEditable = NULL != mImpl->mEventData;
1532
1533   // Keep the current offset as it will be used to update the decorator's positions (if the size changes).
1534   Vector2 offset;
1535   if( newSize && isEditable )
1536   {
1537     offset = mImpl->mScrollPosition;
1538   }
1539
1540   if( !isEditable || !IsMultiLineEnabled() )
1541   {
1542     // After doing the text layout, the vertical offset to place the actor in the desired position can be calculated.
1543     CalculateVerticalOffset( size );
1544   }
1545
1546   if( isEditable )
1547   {
1548     if( newSize )
1549     {
1550       // If there is a new size, the scroll position needs to be clamped.
1551       mImpl->ClampHorizontalScroll( layoutSize );
1552
1553       // Update the decorator's positions is needed if there is a new size.
1554       mImpl->mEventData->mDecorator->UpdatePositions( mImpl->mScrollPosition - offset );
1555     }
1556
1557     // Move the cursor, grab handle etc.
1558     if( mImpl->ProcessInputEvents() )
1559     {
1560       updateTextType = static_cast<UpdateTextType>( updateTextType | DECORATOR_UPDATED );
1561     }
1562   }
1563
1564   // Clear the update info. This info will be set the next time the text is updated.
1565   mImpl->mTextUpdateInfo.Clear();
1566   DALI_LOG_INFO( gLogFilter, Debug::Verbose, "<--Controller::Relayout\n" );
1567
1568   return updateTextType;
1569 }
1570
1571 void Controller::ProcessModifyEvents()
1572 {
1573   Vector<ModifyEvent>& events = mImpl->mModifyEvents;
1574
1575   if( 0u == events.Count() )
1576   {
1577     // Nothing to do.
1578     return;
1579   }
1580
1581   for( Vector<ModifyEvent>::ConstIterator it = events.Begin(),
1582          endIt = events.End();
1583        it != endIt;
1584        ++it )
1585   {
1586     const ModifyEvent& event = *it;
1587
1588     if( ModifyEvent::TEXT_REPLACED == event.type )
1589     {
1590       // A (single) replace event should come first, otherwise we wasted time processing NOOP events
1591       DALI_ASSERT_DEBUG( it == events.Begin() && "Unexpected TEXT_REPLACED event" );
1592
1593       TextReplacedEvent();
1594     }
1595     else if( ModifyEvent::TEXT_INSERTED == event.type )
1596     {
1597       TextInsertedEvent();
1598     }
1599     else if( ModifyEvent::TEXT_DELETED == event.type )
1600     {
1601       // Placeholder-text cannot be deleted
1602       if( !mImpl->IsShowingPlaceholderText() )
1603       {
1604         TextDeletedEvent();
1605       }
1606     }
1607   }
1608
1609   if( NULL != mImpl->mEventData )
1610   {
1611     // When the text is being modified, delay cursor blinking
1612     mImpl->mEventData->mDecorator->DelayCursorBlink();
1613   }
1614
1615   // Discard temporary text
1616   events.Clear();
1617 }
1618
1619 void Controller::ResetText()
1620 {
1621   // Reset buffers.
1622   mImpl->mLogicalModel->mText.Clear();
1623
1624   // We have cleared everything including the placeholder-text
1625   mImpl->PlaceholderCleared();
1626
1627   mImpl->mTextUpdateInfo.mCharacterIndex = 0u;
1628   mImpl->mTextUpdateInfo.mNumberOfCharactersToRemove = mImpl->mTextUpdateInfo.mPreviousNumberOfCharacters;
1629   mImpl->mTextUpdateInfo.mNumberOfCharactersToAdd = 0u;
1630
1631   // Clear any previous text.
1632   mImpl->mTextUpdateInfo.mClearAll = true;
1633
1634   // The natural size needs to be re-calculated.
1635   mImpl->mRecalculateNaturalSize = true;
1636
1637   // Apply modifications to the model
1638   mImpl->mOperationsPending = ALL_OPERATIONS;
1639 }
1640
1641 void Controller::ResetCursorPosition( CharacterIndex cursorIndex )
1642 {
1643   // Reset the cursor position
1644   if( NULL != mImpl->mEventData )
1645   {
1646     mImpl->mEventData->mPrimaryCursorPosition = cursorIndex;
1647
1648     // Update the cursor if it's in editing mode.
1649     if( EventData::IsEditingState( mImpl->mEventData->mState )  )
1650     {
1651       mImpl->mEventData->mUpdateCursorPosition = true;
1652     }
1653   }
1654 }
1655
1656 void Controller::ResetScrollPosition()
1657 {
1658   if( NULL != mImpl->mEventData )
1659   {
1660     // Reset the scroll position.
1661     mImpl->mScrollPosition = Vector2::ZERO;
1662     mImpl->mEventData->mScrollAfterUpdatePosition = true;
1663   }
1664 }
1665
1666 void Controller::TextReplacedEvent()
1667 {
1668   // The natural size needs to be re-calculated.
1669   mImpl->mRecalculateNaturalSize = true;
1670
1671   // Apply modifications to the model
1672   mImpl->mOperationsPending = ALL_OPERATIONS;
1673 }
1674
1675 void Controller::TextInsertedEvent()
1676 {
1677   DALI_ASSERT_DEBUG( NULL != mImpl->mEventData && "Unexpected TextInsertedEvent" );
1678
1679   if( NULL == mImpl->mEventData )
1680   {
1681     return;
1682   }
1683
1684   // The natural size needs to be re-calculated.
1685   mImpl->mRecalculateNaturalSize = true;
1686
1687   // Apply modifications to the model; TODO - Optimize this
1688   mImpl->mOperationsPending = ALL_OPERATIONS;
1689 }
1690
1691 void Controller::TextDeletedEvent()
1692 {
1693   DALI_ASSERT_DEBUG( NULL != mImpl->mEventData && "Unexpected TextDeletedEvent" );
1694
1695   if( NULL == mImpl->mEventData )
1696   {
1697     return;
1698   }
1699
1700   // The natural size needs to be re-calculated.
1701   mImpl->mRecalculateNaturalSize = true;
1702
1703   // Apply modifications to the model; TODO - Optimize this
1704   mImpl->mOperationsPending = ALL_OPERATIONS;
1705 }
1706
1707 bool Controller::DoRelayout( const Size& size,
1708                              OperationsMask operationsRequired,
1709                              Size& layoutSize )
1710 {
1711   DALI_LOG_INFO( gLogFilter, Debug::Verbose, "-->Controller::DoRelayout %p size %f,%f\n", this, size.width, size.height );
1712   bool viewUpdated( false );
1713
1714   // Calculate the operations to be done.
1715   const OperationsMask operations = static_cast<OperationsMask>( mImpl->mOperationsPending & operationsRequired );
1716
1717   const CharacterIndex startIndex = mImpl->mTextUpdateInfo.mParagraphCharacterIndex;
1718   const Length requestedNumberOfCharacters = mImpl->mTextUpdateInfo.mRequestedNumberOfCharacters;
1719
1720   // Get the current layout size.
1721   layoutSize = mImpl->mVisualModel->GetLayoutSize();
1722
1723   if( NO_OPERATION != ( LAYOUT & operations ) )
1724   {
1725     DALI_LOG_INFO( gLogFilter, Debug::Verbose, "-->Controller::DoRelayout LAYOUT & operations\n");
1726
1727     // Some vectors with data needed to layout and reorder may be void
1728     // after the first time the text has been laid out.
1729     // Fill the vectors again.
1730
1731     // Calculate the number of glyphs to layout.
1732     const Vector<GlyphIndex>& charactersToGlyph = mImpl->mVisualModel->mCharactersToGlyph;
1733     const Vector<Length>& glyphsPerCharacter = mImpl->mVisualModel->mGlyphsPerCharacter;
1734     const GlyphIndex* const charactersToGlyphBuffer = charactersToGlyph.Begin();
1735     const Length* const glyphsPerCharacterBuffer = glyphsPerCharacter.Begin();
1736
1737     const CharacterIndex lastIndex = startIndex + ( ( requestedNumberOfCharacters > 0u ) ? requestedNumberOfCharacters - 1u : 0u );
1738     const GlyphIndex startGlyphIndex = mImpl->mTextUpdateInfo.mStartGlyphIndex;
1739     const Length numberOfGlyphs = ( requestedNumberOfCharacters > 0u ) ? *( charactersToGlyphBuffer + lastIndex ) + *( glyphsPerCharacterBuffer + lastIndex ) - startGlyphIndex : 0u;
1740     const Length totalNumberOfGlyphs = mImpl->mVisualModel->mGlyphs.Count();
1741
1742     if( 0u == totalNumberOfGlyphs )
1743     {
1744       if( NO_OPERATION != ( UPDATE_LAYOUT_SIZE & operations ) )
1745       {
1746         mImpl->mVisualModel->SetLayoutSize( Size::ZERO );
1747       }
1748
1749       // Nothing else to do if there is no glyphs.
1750       DALI_LOG_INFO( gLogFilter, Debug::Verbose, "<--Controller::DoRelayout no glyphs, view updated true\n" );
1751       return true;
1752     }
1753
1754     const Vector<LineBreakInfo>& lineBreakInfo = mImpl->mLogicalModel->mLineBreakInfo;
1755     const Vector<WordBreakInfo>& wordBreakInfo = mImpl->mLogicalModel->mWordBreakInfo;
1756     const Vector<CharacterDirection>& characterDirection = mImpl->mLogicalModel->mCharacterDirections;
1757     const Vector<GlyphInfo>& glyphs = mImpl->mVisualModel->mGlyphs;
1758     const Vector<CharacterIndex>& glyphsToCharactersMap = mImpl->mVisualModel->mGlyphsToCharacters;
1759     const Vector<Length>& charactersPerGlyph = mImpl->mVisualModel->mCharactersPerGlyph;
1760     const Character* const textBuffer = mImpl->mLogicalModel->mText.Begin();
1761
1762     // Set the layout parameters.
1763     LayoutParameters layoutParameters( size,
1764                                        textBuffer,
1765                                        lineBreakInfo.Begin(),
1766                                        wordBreakInfo.Begin(),
1767                                        ( 0u != characterDirection.Count() ) ? characterDirection.Begin() : NULL,
1768                                        glyphs.Begin(),
1769                                        glyphsToCharactersMap.Begin(),
1770                                        charactersPerGlyph.Begin(),
1771                                        charactersToGlyphBuffer,
1772                                        glyphsPerCharacterBuffer,
1773                                        totalNumberOfGlyphs );
1774
1775     // Resize the vector of positions to have the same size than the vector of glyphs.
1776     Vector<Vector2>& glyphPositions = mImpl->mVisualModel->mGlyphPositions;
1777     glyphPositions.Resize( totalNumberOfGlyphs );
1778
1779     // Whether the last character is a new paragraph character.
1780     mImpl->mTextUpdateInfo.mIsLastCharacterNewParagraph =  TextAbstraction::IsNewParagraph( *( textBuffer + ( mImpl->mLogicalModel->mText.Count() - 1u ) ) );
1781     layoutParameters.isLastNewParagraph = mImpl->mTextUpdateInfo.mIsLastCharacterNewParagraph;
1782
1783     // The initial glyph and the number of glyphs to layout.
1784     layoutParameters.startGlyphIndex = startGlyphIndex;
1785     layoutParameters.numberOfGlyphs = numberOfGlyphs;
1786     layoutParameters.startLineIndex = mImpl->mTextUpdateInfo.mStartLineIndex;
1787     layoutParameters.estimatedNumberOfLines = mImpl->mTextUpdateInfo.mEstimatedNumberOfLines;
1788
1789     // Update the visual model.
1790     Size newLayoutSize;
1791     viewUpdated = mImpl->mLayoutEngine.LayoutText( layoutParameters,
1792                                                    glyphPositions,
1793                                                    mImpl->mVisualModel->mLines,
1794                                                    newLayoutSize );
1795
1796     viewUpdated = viewUpdated || ( newLayoutSize != layoutSize );
1797
1798     if( viewUpdated )
1799     {
1800       layoutSize = newLayoutSize;
1801
1802       if ( NO_OPERATION != ( UPDATE_DIRECTION & operations ) )
1803       {
1804         mImpl->mAutoScrollDirectionRTL = false;
1805       }
1806
1807       // Reorder the lines
1808       if( NO_OPERATION != ( REORDER & operations ) )
1809       {
1810         Vector<BidirectionalParagraphInfoRun>& bidirectionalInfo = mImpl->mLogicalModel->mBidirectionalParagraphInfo;
1811         Vector<BidirectionalLineInfoRun>& bidirectionalLineInfo = mImpl->mLogicalModel->mBidirectionalLineInfo;
1812
1813         // Check first if there are paragraphs with bidirectional info.
1814         if( 0u != bidirectionalInfo.Count() )
1815         {
1816           // Get the lines
1817           const Length numberOfLines = mImpl->mVisualModel->mLines.Count();
1818
1819           // Reorder the lines.
1820           bidirectionalLineInfo.Reserve( numberOfLines ); // Reserve because is not known yet how many lines have right to left characters.
1821           ReorderLines( bidirectionalInfo,
1822                         startIndex,
1823                         requestedNumberOfCharacters,
1824                         mImpl->mVisualModel->mLines,
1825                         bidirectionalLineInfo );
1826
1827           // Set the bidirectional info per line into the layout parameters.
1828           layoutParameters.lineBidirectionalInfoRunsBuffer = bidirectionalLineInfo.Begin();
1829           layoutParameters.numberOfBidirectionalInfoRuns = bidirectionalLineInfo.Count();
1830
1831           // Re-layout the text. Reorder those lines with right to left characters.
1832           mImpl->mLayoutEngine.ReLayoutRightToLeftLines( layoutParameters,
1833                                                          startIndex,
1834                                                          requestedNumberOfCharacters,
1835                                                          glyphPositions );
1836
1837           if ( ( NO_OPERATION != ( UPDATE_DIRECTION & operations ) ) && ( numberOfLines > 0 ) )
1838           {
1839             const LineRun* const firstline = mImpl->mVisualModel->mLines.Begin();
1840             if ( firstline )
1841             {
1842               mImpl->mAutoScrollDirectionRTL = firstline->direction;
1843             }
1844           }
1845         }
1846       } // REORDER
1847
1848       // Sets the layout size.
1849       if( NO_OPERATION != ( UPDATE_LAYOUT_SIZE & operations ) )
1850       {
1851         mImpl->mVisualModel->SetLayoutSize( layoutSize );
1852       }
1853     } // view updated
1854
1855     // Store the size used to layout the text.
1856     mImpl->mVisualModel->mControlSize = size;
1857   }
1858
1859   if( NO_OPERATION != ( ALIGN & operations ) )
1860   {
1861     // The laid-out lines.
1862     Vector<LineRun>& lines = mImpl->mVisualModel->mLines;
1863
1864     mImpl->mLayoutEngine.Align( size,
1865                                 startIndex,
1866                                 requestedNumberOfCharacters,
1867                                 lines );
1868
1869     viewUpdated = true;
1870   }
1871 #if defined(DEBUG_ENABLED)
1872   std::string currentText;
1873   GetText( currentText );
1874   DALI_LOG_INFO( gLogFilter, Debug::Concise, "Controller::DoRelayout [%p] mImpl->mAutoScrollDirectionRTL[%s] [%s]\n", this, (mImpl->mAutoScrollDirectionRTL)?"true":"false",  currentText.c_str() );
1875 #endif
1876   DALI_LOG_INFO( gLogFilter, Debug::Verbose, "<--Controller::DoRelayout, view updated %s\n", ( viewUpdated ? "true" : "false" ) );
1877   return viewUpdated;
1878 }
1879
1880 void Controller::SetMultiLineEnabled( bool enable )
1881 {
1882   const LayoutEngine::Layout layout = enable ? LayoutEngine::MULTI_LINE_BOX : LayoutEngine::SINGLE_LINE_BOX;
1883
1884   if( layout != mImpl->mLayoutEngine.GetLayout() )
1885   {
1886     // Set the layout type.
1887     mImpl->mLayoutEngine.SetLayout( layout );
1888
1889     // Set the flags to redo the layout operations
1890     const OperationsMask layoutOperations =  static_cast<OperationsMask>( LAYOUT             |
1891                                                                           UPDATE_LAYOUT_SIZE |
1892                                                                           ALIGN              |
1893                                                                           REORDER );
1894
1895     mImpl->mOperationsPending = static_cast<OperationsMask>( mImpl->mOperationsPending | layoutOperations );
1896
1897     mImpl->RequestRelayout();
1898   }
1899 }
1900
1901 bool Controller::IsMultiLineEnabled() const
1902 {
1903   return LayoutEngine::MULTI_LINE_BOX == mImpl->mLayoutEngine.GetLayout();
1904 }
1905
1906 void Controller::SetHorizontalAlignment( LayoutEngine::HorizontalAlignment alignment )
1907 {
1908   if( alignment != mImpl->mLayoutEngine.GetHorizontalAlignment() )
1909   {
1910     // Set the alignment.
1911     mImpl->mLayoutEngine.SetHorizontalAlignment( alignment );
1912
1913     // Set the flag to redo the alignment operation.
1914     mImpl->mOperationsPending = static_cast<OperationsMask>( mImpl->mOperationsPending | ALIGN );
1915
1916     mImpl->RequestRelayout();
1917   }
1918 }
1919
1920 LayoutEngine::HorizontalAlignment Controller::GetHorizontalAlignment() const
1921 {
1922   return mImpl->mLayoutEngine.GetHorizontalAlignment();
1923 }
1924
1925 void Controller::SetVerticalAlignment( LayoutEngine::VerticalAlignment alignment )
1926 {
1927   if( alignment != mImpl->mLayoutEngine.GetVerticalAlignment() )
1928   {
1929     // Set the alignment.
1930     mImpl->mLayoutEngine.SetVerticalAlignment( alignment );
1931
1932     mImpl->mOperationsPending = static_cast<OperationsMask>( mImpl->mOperationsPending | ALIGN );
1933
1934     mImpl->RequestRelayout();
1935   }
1936 }
1937
1938 LayoutEngine::VerticalAlignment Controller::GetVerticalAlignment() const
1939 {
1940   return mImpl->mLayoutEngine.GetVerticalAlignment();
1941 }
1942
1943 void Controller::CalculateVerticalOffset( const Size& controlSize )
1944 {
1945   Size layoutSize = mImpl->mVisualModel->GetLayoutSize();
1946
1947   if( fabsf( layoutSize.height ) < Math::MACHINE_EPSILON_1000 )
1948   {
1949     // Get the line height of the default font.
1950     layoutSize.height = mImpl->GetDefaultFontLineHeight();
1951   }
1952
1953   switch( mImpl->mLayoutEngine.GetVerticalAlignment() )
1954   {
1955     case LayoutEngine::VERTICAL_ALIGN_TOP:
1956     {
1957       mImpl->mScrollPosition.y = 0.f;
1958       break;
1959     }
1960     case LayoutEngine::VERTICAL_ALIGN_CENTER:
1961     {
1962       mImpl->mScrollPosition.y = floorf( 0.5f * ( controlSize.height - layoutSize.height ) ); // try to avoid pixel alignment.
1963       break;
1964     }
1965     case LayoutEngine::VERTICAL_ALIGN_BOTTOM:
1966     {
1967       mImpl->mScrollPosition.y = controlSize.height - layoutSize.height;
1968       break;
1969     }
1970   }
1971 }
1972
1973 LayoutEngine& Controller::GetLayoutEngine()
1974 {
1975   return mImpl->mLayoutEngine;
1976 }
1977
1978 View& Controller::GetView()
1979 {
1980   return mImpl->mView;
1981 }
1982
1983 void Controller::KeyboardFocusGainEvent()
1984 {
1985   DALI_ASSERT_DEBUG( mImpl->mEventData && "Unexpected KeyboardFocusGainEvent" );
1986
1987   if( NULL != mImpl->mEventData )
1988   {
1989     if( ( EventData::INACTIVE == mImpl->mEventData->mState ) ||
1990         ( EventData::INTERRUPTED == mImpl->mEventData->mState ) )
1991     {
1992       mImpl->ChangeState( EventData::EDITING );
1993       mImpl->mEventData->mUpdateCursorPosition = true; //If editing started without tap event, cursor update must be triggered.
1994     }
1995     mImpl->NotifyImfMultiLineStatus();
1996     if( mImpl->IsShowingPlaceholderText() )
1997     {
1998       // Show alternative placeholder-text when editing
1999       ShowPlaceholderText();
2000     }
2001
2002     mImpl->RequestRelayout();
2003   }
2004 }
2005
2006 void Controller::KeyboardFocusLostEvent()
2007 {
2008   DALI_ASSERT_DEBUG( mImpl->mEventData && "Unexpected KeyboardFocusLostEvent" );
2009
2010   if( NULL != mImpl->mEventData )
2011   {
2012     if( EventData::INTERRUPTED != mImpl->mEventData->mState )
2013     {
2014       mImpl->ChangeState( EventData::INACTIVE );
2015
2016       if( !mImpl->IsShowingRealText() )
2017       {
2018         // Revert to regular placeholder-text when not editing
2019         ShowPlaceholderText();
2020       }
2021     }
2022   }
2023   mImpl->RequestRelayout();
2024 }
2025
2026 bool Controller::KeyEvent( const Dali::KeyEvent& keyEvent )
2027 {
2028   DALI_ASSERT_DEBUG( mImpl->mEventData && "Unexpected KeyEvent" );
2029
2030   bool textChanged( false );
2031
2032   if( ( NULL != mImpl->mEventData ) &&
2033       ( keyEvent.state == KeyEvent::Down ) )
2034   {
2035     int keyCode = keyEvent.keyCode;
2036     const std::string& keyString = keyEvent.keyPressed;
2037
2038     // Pre-process to separate modifying events from non-modifying input events.
2039     if( Dali::DALI_KEY_ESCAPE == keyCode )
2040     {
2041       // Escape key is a special case which causes focus loss
2042       KeyboardFocusLostEvent();
2043     }
2044     else if( ( Dali::DALI_KEY_CURSOR_LEFT  == keyCode ) ||
2045              ( Dali::DALI_KEY_CURSOR_RIGHT == keyCode ) ||
2046              ( Dali::DALI_KEY_CURSOR_UP    == keyCode ) ||
2047              ( Dali::DALI_KEY_CURSOR_DOWN  == keyCode ) )
2048     {
2049       Event event( Event::CURSOR_KEY_EVENT );
2050       event.p1.mInt = keyCode;
2051       mImpl->mEventData->mEventQueue.push_back( event );
2052     }
2053     else if( Dali::DALI_KEY_BACKSPACE == keyCode )
2054     {
2055       textChanged = BackspaceKeyEvent();
2056     }
2057     else if( IsKey( keyEvent,  Dali::DALI_KEY_POWER ) )
2058     {
2059       mImpl->ChangeState( EventData::INTERRUPTED ); // State is not INACTIVE as expect to return to edit mode.
2060       // Avoids calling the InsertText() method which can delete selected text
2061     }
2062     else if( IsKey( keyEvent, Dali::DALI_KEY_MENU ) ||
2063              IsKey( keyEvent, Dali::DALI_KEY_HOME ) )
2064     {
2065       mImpl->ChangeState( EventData::INACTIVE );
2066       // Menu/Home key behaviour does not allow edit mode to resume like Power key
2067       // Avoids calling the InsertText() method which can delete selected text
2068     }
2069     else if( Dali::DALI_KEY_SHIFT_LEFT == keyCode )
2070     {
2071       // DALI_KEY_SHIFT_LEFT is the key code for the Left Shift. It's sent (by the imf?) when the predictive text is enabled
2072       // and a character is typed after the type of a upper case latin character.
2073
2074       // Do nothing.
2075     }
2076     else
2077     {
2078       DALI_LOG_INFO( gLogFilter, Debug::Verbose, "Controller::KeyEvent %p keyString %s\n", this, keyString.c_str() );
2079
2080       // IMF manager is no longer handling key-events
2081       mImpl->ClearPreEditFlag();
2082
2083       InsertText( keyString, COMMIT );
2084       textChanged = true;
2085     }
2086
2087     if ( ( mImpl->mEventData->mState != EventData::INTERRUPTED ) &&
2088          ( mImpl->mEventData->mState != EventData::INACTIVE ) &&
2089          ( Dali::DALI_KEY_SHIFT_LEFT != keyCode ) )
2090     {
2091       // Should not change the state if the key is the shift send by the imf manager.
2092       // Otherwise, when the state is SELECTING the text controller can't send the right
2093       // surrounding info to the imf.
2094       mImpl->ChangeState( EventData::EDITING );
2095     }
2096
2097     mImpl->RequestRelayout();
2098   }
2099
2100   if( textChanged )
2101   {
2102     // Do this last since it provides callbacks into application code
2103     mImpl->mControlInterface.TextChanged();
2104   }
2105
2106   return true;
2107 }
2108
2109 void Controller::InsertText( const std::string& text, Controller::InsertType type )
2110 {
2111   bool removedPrevious( false );
2112   bool maxLengthReached( false );
2113
2114   DALI_ASSERT_DEBUG( NULL != mImpl->mEventData && "Unexpected InsertText" )
2115
2116   if( NULL == mImpl->mEventData )
2117   {
2118     return;
2119   }
2120
2121   DALI_LOG_INFO( gLogFilter, Debug::Verbose, "Controller::InsertText %p %s (%s) mPrimaryCursorPosition %d mPreEditFlag %d mPreEditStartPosition %d mPreEditLength %d\n",
2122                  this, text.c_str(), (COMMIT == type ? "COMMIT" : "PRE_EDIT"),
2123                  mImpl->mEventData->mPrimaryCursorPosition, mImpl->mEventData->mPreEditFlag, mImpl->mEventData->mPreEditStartPosition, mImpl->mEventData->mPreEditLength );
2124
2125   // TODO: At the moment the underline runs are only for pre-edit.
2126   mImpl->mVisualModel->mUnderlineRuns.Clear();
2127
2128   // Keep the current number of characters.
2129   const Length currentNumberOfCharacters = mImpl->IsShowingRealText() ? mImpl->mLogicalModel->mText.Count() : 0u;
2130
2131   // Remove the previous IMF pre-edit.
2132   if( mImpl->mEventData->mPreEditFlag && ( 0u != mImpl->mEventData->mPreEditLength ) )
2133   {
2134     removedPrevious = RemoveText( -static_cast<int>( mImpl->mEventData->mPrimaryCursorPosition - mImpl->mEventData->mPreEditStartPosition ),
2135                                   mImpl->mEventData->mPreEditLength,
2136                                   DONT_UPDATE_INPUT_STYLE );
2137
2138     mImpl->mEventData->mPrimaryCursorPosition = mImpl->mEventData->mPreEditStartPosition;
2139     mImpl->mEventData->mPreEditLength = 0u;
2140   }
2141   else
2142   {
2143     // Remove the previous Selection.
2144     removedPrevious = RemoveSelectedText();
2145   }
2146
2147   Vector<Character> utf32Characters;
2148   Length characterCount = 0u;
2149
2150   if( !text.empty() )
2151   {
2152     //  Convert text into UTF-32
2153     utf32Characters.Resize( text.size() );
2154
2155     // This is a bit horrible but std::string returns a (signed) char*
2156     const uint8_t* utf8 = reinterpret_cast<const uint8_t*>( text.c_str() );
2157
2158     // Transform a text array encoded in utf8 into an array encoded in utf32.
2159     // It returns the actual number of characters.
2160     characterCount = Utf8ToUtf32( utf8, text.size(), utf32Characters.Begin() );
2161     utf32Characters.Resize( characterCount );
2162
2163     DALI_ASSERT_DEBUG( text.size() >= utf32Characters.Count() && "Invalid UTF32 conversion length" );
2164     DALI_LOG_INFO( gLogFilter, Debug::Verbose, "UTF8 size %d, UTF32 size %d\n", text.size(), utf32Characters.Count() );
2165   }
2166
2167   if( 0u != utf32Characters.Count() ) // Check if Utf8ToUtf32 conversion succeeded
2168   {
2169     // The placeholder text is no longer needed
2170     if( mImpl->IsShowingPlaceholderText() )
2171     {
2172       ResetText();
2173     }
2174
2175     mImpl->ChangeState( EventData::EDITING );
2176
2177     // Handle the IMF (predicitive text) state changes
2178     if( COMMIT == type )
2179     {
2180       // IMF manager is no longer handling key-events
2181       mImpl->ClearPreEditFlag();
2182     }
2183     else // PRE_EDIT
2184     {
2185       if( !mImpl->mEventData->mPreEditFlag )
2186       {
2187         DALI_LOG_INFO( gLogFilter, Debug::Verbose, "Entered PreEdit state\n" );
2188
2189         // Record the start of the pre-edit text
2190         mImpl->mEventData->mPreEditStartPosition = mImpl->mEventData->mPrimaryCursorPosition;
2191       }
2192
2193       mImpl->mEventData->mPreEditLength = utf32Characters.Count();
2194       mImpl->mEventData->mPreEditFlag = true;
2195
2196       DALI_LOG_INFO( gLogFilter, Debug::Verbose, "mPreEditStartPosition %d mPreEditLength %d\n", mImpl->mEventData->mPreEditStartPosition, mImpl->mEventData->mPreEditLength );
2197     }
2198
2199     const Length numberOfCharactersInModel = mImpl->mLogicalModel->mText.Count();
2200
2201     // Restrict new text to fit within Maximum characters setting.
2202     Length maxSizeOfNewText = std::min( ( mImpl->mMaximumNumberOfCharacters - numberOfCharactersInModel ), characterCount );
2203     maxLengthReached = ( characterCount > maxSizeOfNewText );
2204
2205     // The cursor position.
2206     CharacterIndex& cursorIndex = mImpl->mEventData->mPrimaryCursorPosition;
2207
2208     // Update the text's style.
2209
2210     // Updates the text style runs by adding characters.
2211     mImpl->mLogicalModel->UpdateTextStyleRuns( cursorIndex, maxSizeOfNewText );
2212
2213     // Get the character index from the cursor index.
2214     const CharacterIndex styleIndex = ( cursorIndex > 0u ) ? cursorIndex - 1u : 0u;
2215
2216     // Retrieve the text's style for the given index.
2217     InputStyle style;
2218     mImpl->RetrieveDefaultInputStyle( style );
2219     mImpl->mLogicalModel->RetrieveStyle( styleIndex, style );
2220
2221     // Whether to add a new text color run.
2222     const bool addColorRun = ( style.textColor != mImpl->mEventData->mInputStyle.textColor );
2223
2224     // Whether to add a new font run.
2225     const bool addFontNameRun = style.familyName != mImpl->mEventData->mInputStyle.familyName;
2226     const bool addFontWeightRun = style.weight != mImpl->mEventData->mInputStyle.weight;
2227     const bool addFontWidthRun = style.width != mImpl->mEventData->mInputStyle.width;
2228     const bool addFontSlantRun = style.slant != mImpl->mEventData->mInputStyle.slant;
2229     const bool addFontSizeRun = style.size != mImpl->mEventData->mInputStyle.size;
2230
2231     // Add style runs.
2232     if( addColorRun )
2233     {
2234       const VectorBase::SizeType numberOfRuns = mImpl->mLogicalModel->mColorRuns.Count();
2235       mImpl->mLogicalModel->mColorRuns.Resize( numberOfRuns + 1u );
2236
2237       ColorRun& colorRun = *( mImpl->mLogicalModel->mColorRuns.Begin() + numberOfRuns );
2238       colorRun.color = mImpl->mEventData->mInputStyle.textColor;
2239       colorRun.characterRun.characterIndex = cursorIndex;
2240       colorRun.characterRun.numberOfCharacters = maxSizeOfNewText;
2241     }
2242
2243     if( addFontNameRun   ||
2244         addFontWeightRun ||
2245         addFontWidthRun  ||
2246         addFontSlantRun  ||
2247         addFontSizeRun )
2248     {
2249       const VectorBase::SizeType numberOfRuns = mImpl->mLogicalModel->mFontDescriptionRuns.Count();
2250       mImpl->mLogicalModel->mFontDescriptionRuns.Resize( numberOfRuns + 1u );
2251
2252       FontDescriptionRun& fontDescriptionRun = *( mImpl->mLogicalModel->mFontDescriptionRuns.Begin() + numberOfRuns );
2253
2254       if( addFontNameRun )
2255       {
2256         fontDescriptionRun.familyLength = mImpl->mEventData->mInputStyle.familyName.size();
2257         fontDescriptionRun.familyName = new char[fontDescriptionRun.familyLength];
2258         memcpy( fontDescriptionRun.familyName, mImpl->mEventData->mInputStyle.familyName.c_str(), fontDescriptionRun.familyLength );
2259         fontDescriptionRun.familyDefined = true;
2260
2261         // The memory allocated for the font family name is freed when the font description is removed from the logical model.
2262       }
2263
2264       if( addFontWeightRun )
2265       {
2266         fontDescriptionRun.weight = mImpl->mEventData->mInputStyle.weight;
2267         fontDescriptionRun.weightDefined = true;
2268       }
2269
2270       if( addFontWidthRun )
2271       {
2272         fontDescriptionRun.width = mImpl->mEventData->mInputStyle.width;
2273         fontDescriptionRun.widthDefined = true;
2274       }
2275
2276       if( addFontSlantRun )
2277       {
2278         fontDescriptionRun.slant = mImpl->mEventData->mInputStyle.slant;
2279         fontDescriptionRun.slantDefined = true;
2280       }
2281
2282       if( addFontSizeRun )
2283       {
2284         fontDescriptionRun.size = static_cast<PointSize26Dot6>( mImpl->mEventData->mInputStyle.size * 64.f );
2285         fontDescriptionRun.sizeDefined = true;
2286       }
2287
2288       fontDescriptionRun.characterRun.characterIndex = cursorIndex;
2289       fontDescriptionRun.characterRun.numberOfCharacters = maxSizeOfNewText;
2290     }
2291
2292     // Insert at current cursor position.
2293     Vector<Character>& modifyText = mImpl->mLogicalModel->mText;
2294
2295     if( cursorIndex < numberOfCharactersInModel )
2296     {
2297       modifyText.Insert( modifyText.Begin() + cursorIndex, utf32Characters.Begin(), utf32Characters.Begin() + maxSizeOfNewText );
2298     }
2299     else
2300     {
2301       modifyText.Insert( modifyText.End(), utf32Characters.Begin(), utf32Characters.Begin() + maxSizeOfNewText );
2302     }
2303
2304     // Mark the first paragraph to be updated.
2305     mImpl->mTextUpdateInfo.mCharacterIndex = std::min( cursorIndex, mImpl->mTextUpdateInfo.mCharacterIndex );
2306     mImpl->mTextUpdateInfo.mNumberOfCharactersToAdd += maxSizeOfNewText;
2307
2308     // Update the cursor index.
2309     cursorIndex += maxSizeOfNewText;
2310
2311     DALI_LOG_INFO( gLogFilter, Debug::Verbose, "Inserted %d characters, new size %d new cursor %d\n", maxSizeOfNewText, mImpl->mLogicalModel->mText.Count(), mImpl->mEventData->mPrimaryCursorPosition );
2312   }
2313
2314   const Length numberOfCharacters = mImpl->IsShowingRealText() ? mImpl->mLogicalModel->mText.Count() : 0u;
2315
2316   if( ( 0u == mImpl->mLogicalModel->mText.Count() ) &&
2317       mImpl->IsPlaceholderAvailable() )
2318   {
2319     // Show place-holder if empty after removing the pre-edit text
2320     ShowPlaceholderText();
2321     mImpl->mEventData->mUpdateCursorPosition = true;
2322     mImpl->ClearPreEditFlag();
2323   }
2324   else if( removedPrevious ||
2325            ( 0 != utf32Characters.Count() ) )
2326   {
2327     // Queue an inserted event
2328     mImpl->QueueModifyEvent( ModifyEvent::TEXT_INSERTED );
2329
2330     mImpl->mEventData->mUpdateCursorPosition = true;
2331     if( numberOfCharacters < currentNumberOfCharacters )
2332     {
2333       mImpl->mEventData->mScrollAfterDelete = true;
2334     }
2335     else
2336     {
2337       mImpl->mEventData->mScrollAfterUpdatePosition = true;
2338     }
2339   }
2340
2341   if( maxLengthReached )
2342   {
2343     DALI_LOG_INFO( gLogFilter, Debug::Verbose, "MaxLengthReached (%d)\n", mImpl->mLogicalModel->mText.Count() );
2344
2345     mImpl->ResetImfManager();
2346
2347     // Do this last since it provides callbacks into application code
2348     mImpl->mControlInterface.MaxLengthReached();
2349   }
2350 }
2351
2352 bool Controller::RemoveSelectedText()
2353 {
2354   bool textRemoved( false );
2355
2356   if( EventData::SELECTING == mImpl->mEventData->mState )
2357   {
2358     std::string removedString;
2359     mImpl->RetrieveSelection( removedString, true );
2360
2361     if( !removedString.empty() )
2362     {
2363       textRemoved = true;
2364       mImpl->ChangeState( EventData::EDITING );
2365     }
2366   }
2367
2368   return textRemoved;
2369 }
2370
2371 void Controller::TapEvent( unsigned int tapCount, float x, float y )
2372 {
2373   DALI_ASSERT_DEBUG( mImpl->mEventData && "Unexpected TapEvent" );
2374
2375   if( NULL != mImpl->mEventData )
2376   {
2377     DALI_LOG_INFO( gLogFilter, Debug::Concise, "TapEvent state:%d \n", mImpl->mEventData->mState );
2378
2379     if( 1u == tapCount )
2380     {
2381       // This is to avoid unnecessary relayouts when tapping an empty text-field
2382       bool relayoutNeeded( false );
2383
2384       if( ( EventData::EDITING_WITH_POPUP == mImpl->mEventData->mState ) ||
2385           ( EventData::EDITING_WITH_PASTE_POPUP == mImpl->mEventData->mState ) )
2386       {
2387         mImpl->ChangeState( EventData::EDITING_WITH_GRAB_HANDLE );  // If Popup shown hide it here so can be shown again if required.
2388       }
2389
2390       if( mImpl->IsShowingRealText() && ( EventData::INACTIVE != mImpl->mEventData->mState ) )
2391       {
2392         // Already in an active state so show a popup
2393         if( !mImpl->IsClipboardEmpty() )
2394         {
2395           // Shows Paste popup but could show full popup with Selection options. ( EDITING_WITH_POPUP )
2396           mImpl->ChangeState( EventData::EDITING_WITH_PASTE_POPUP );
2397         }
2398         else
2399         {
2400           // Show cursor and grabhandle on first tap, this matches the behaviour of tapping when already editing
2401           mImpl->ChangeState( EventData::EDITING_WITH_GRAB_HANDLE );
2402         }
2403         relayoutNeeded = true;
2404       }
2405       else
2406       {
2407         if( mImpl->IsShowingPlaceholderText() && !mImpl->IsFocusedPlaceholderAvailable() )
2408         {
2409           // Hide placeholder text
2410           ResetText();
2411         }
2412
2413         if( EventData::INACTIVE == mImpl->mEventData->mState )
2414         {
2415           mImpl->ChangeState( EventData::EDITING );
2416         }
2417         else if( !mImpl->IsClipboardEmpty() )
2418         {
2419           mImpl->ChangeState( EventData::EDITING_WITH_POPUP );
2420         }
2421         relayoutNeeded = true;
2422       }
2423
2424       // Handles & cursors must be repositioned after Relayout() i.e. after the Model has been updated
2425       if( relayoutNeeded )
2426       {
2427         Event event( Event::TAP_EVENT );
2428         event.p1.mUint = tapCount;
2429         event.p2.mFloat = x;
2430         event.p3.mFloat = y;
2431         mImpl->mEventData->mEventQueue.push_back( event );
2432
2433         mImpl->RequestRelayout();
2434       }
2435     }
2436     else if( 2u == tapCount )
2437     {
2438       if( mImpl->mEventData->mSelectionEnabled &&
2439           mImpl->IsShowingRealText() )
2440       {
2441         SelectEvent( x, y, false );
2442       }
2443     }
2444   }
2445
2446   // Reset keyboard as tap event has occurred.
2447   mImpl->ResetImfManager();
2448 }
2449
2450 void Controller::PanEvent( Gesture::State state, const Vector2& displacement )
2451 {
2452   DALI_ASSERT_DEBUG( mImpl->mEventData && "Unexpected PanEvent" );
2453
2454   if( NULL != mImpl->mEventData )
2455   {
2456     Event event( Event::PAN_EVENT );
2457     event.p1.mInt = state;
2458     event.p2.mFloat = displacement.x;
2459     event.p3.mFloat = displacement.y;
2460     mImpl->mEventData->mEventQueue.push_back( event );
2461
2462     mImpl->RequestRelayout();
2463   }
2464 }
2465
2466 void Controller::LongPressEvent( Gesture::State state, float x, float y  )
2467 {
2468   DALI_ASSERT_DEBUG( mImpl->mEventData && "Unexpected LongPressEvent" );
2469
2470   if( ( state == Gesture::Started ) &&
2471       ( NULL != mImpl->mEventData ) )
2472   {
2473     if( !mImpl->IsShowingRealText() )
2474     {
2475       Event event( Event::LONG_PRESS_EVENT );
2476       event.p1.mInt = state;
2477       mImpl->mEventData->mEventQueue.push_back( event );
2478       mImpl->RequestRelayout();
2479     }
2480     else
2481     {
2482       // The 1st long-press on inactive text-field is treated as tap
2483       if( EventData::INACTIVE == mImpl->mEventData->mState )
2484       {
2485         mImpl->ChangeState( EventData::EDITING );
2486
2487         Event event( Event::TAP_EVENT );
2488         event.p1.mUint = 1;
2489         event.p2.mFloat = x;
2490         event.p3.mFloat = y;
2491         mImpl->mEventData->mEventQueue.push_back( event );
2492
2493         mImpl->RequestRelayout();
2494       }
2495       else
2496       {
2497         // Reset the imf manger to commit the pre-edit before selecting the text.
2498         mImpl->ResetImfManager();
2499
2500         SelectEvent( x, y, false );
2501       }
2502     }
2503   }
2504 }
2505
2506 void Controller::SelectEvent( float x, float y, bool selectAll )
2507 {
2508   DALI_LOG_INFO( gLogFilter, Debug::Verbose, "Controller::SelectEvent\n" );
2509
2510   if( NULL != mImpl->mEventData )
2511   {
2512     if( selectAll )
2513     {
2514       Event event( Event::SELECT_ALL );
2515       mImpl->mEventData->mEventQueue.push_back( event );
2516     }
2517     else
2518     {
2519       Event event( Event::SELECT );
2520       event.p2.mFloat = x;
2521       event.p3.mFloat = y;
2522       mImpl->mEventData->mEventQueue.push_back( event );
2523     }
2524
2525     mImpl->RequestRelayout();
2526   }
2527 }
2528
2529 void Controller::GetTargetSize( Vector2& targetSize )
2530 {
2531   targetSize = mImpl->mVisualModel->mControlSize;
2532 }
2533
2534 void Controller::AddDecoration( Actor& actor, bool needsClipping )
2535 {
2536   mImpl->mControlInterface.AddDecoration( actor, needsClipping );
2537 }
2538
2539 void Controller::DecorationEvent( HandleType handleType, HandleState state, float x, float y )
2540 {
2541   DALI_ASSERT_DEBUG( mImpl->mEventData && "Unexpected DecorationEvent" );
2542
2543   if( NULL != mImpl->mEventData )
2544   {
2545     switch( handleType )
2546     {
2547       case GRAB_HANDLE:
2548       {
2549         Event event( Event::GRAB_HANDLE_EVENT );
2550         event.p1.mUint  = state;
2551         event.p2.mFloat = x;
2552         event.p3.mFloat = y;
2553
2554         mImpl->mEventData->mEventQueue.push_back( event );
2555         break;
2556       }
2557       case LEFT_SELECTION_HANDLE:
2558       {
2559         Event event( Event::LEFT_SELECTION_HANDLE_EVENT );
2560         event.p1.mUint  = state;
2561         event.p2.mFloat = x;
2562         event.p3.mFloat = y;
2563
2564         mImpl->mEventData->mEventQueue.push_back( event );
2565         break;
2566       }
2567       case RIGHT_SELECTION_HANDLE:
2568       {
2569         Event event( Event::RIGHT_SELECTION_HANDLE_EVENT );
2570         event.p1.mUint  = state;
2571         event.p2.mFloat = x;
2572         event.p3.mFloat = y;
2573
2574         mImpl->mEventData->mEventQueue.push_back( event );
2575         break;
2576       }
2577       case LEFT_SELECTION_HANDLE_MARKER:
2578       case RIGHT_SELECTION_HANDLE_MARKER:
2579       {
2580         // Markers do not move the handles.
2581         break;
2582       }
2583       case HANDLE_TYPE_COUNT:
2584       {
2585         DALI_ASSERT_DEBUG( !"Controller::HandleEvent. Unexpected handle type" );
2586       }
2587     }
2588
2589     mImpl->RequestRelayout();
2590   }
2591 }
2592
2593 void Controller::PasteText( const std::string& stringToPaste )
2594 {
2595   InsertText( stringToPaste, Text::Controller::COMMIT );
2596   mImpl->ChangeState( EventData::EDITING );
2597   mImpl->RequestRelayout();
2598
2599   // Do this last since it provides callbacks into application code
2600   mImpl->mControlInterface.TextChanged();
2601 }
2602
2603 void Controller::PasteClipboardItemEvent()
2604 {
2605   // Retrieve the clipboard contents first
2606   ClipboardEventNotifier notifier( ClipboardEventNotifier::Get() );
2607   std::string stringToPaste( notifier.GetContent() );
2608
2609   // Commit the current pre-edit text; the contents of the clipboard should be appended
2610   mImpl->ResetImfManager();
2611
2612   // Temporary disable hiding clipboard
2613   mImpl->SetClipboardHideEnable( false );
2614
2615   // Paste
2616   PasteText( stringToPaste );
2617
2618   mImpl->SetClipboardHideEnable( true );
2619 }
2620
2621 void Controller::TextPopupButtonTouched( Dali::Toolkit::TextSelectionPopup::Buttons button )
2622 {
2623   if( NULL == mImpl->mEventData )
2624   {
2625     return;
2626   }
2627
2628   switch( button )
2629   {
2630     case Toolkit::TextSelectionPopup::CUT:
2631     {
2632       mImpl->SendSelectionToClipboard( true ); // Synchronous call to modify text
2633       mImpl->mOperationsPending = ALL_OPERATIONS;
2634
2635       if( ( 0u != mImpl->mLogicalModel->mText.Count() ) ||
2636           !mImpl->IsPlaceholderAvailable() )
2637       {
2638         mImpl->QueueModifyEvent( ModifyEvent::TEXT_DELETED );
2639       }
2640       else
2641       {
2642         ShowPlaceholderText();
2643       }
2644
2645       mImpl->mEventData->mUpdateCursorPosition = true;
2646       mImpl->mEventData->mScrollAfterDelete = true;
2647
2648       mImpl->RequestRelayout();
2649       mImpl->mControlInterface.TextChanged();
2650       break;
2651     }
2652     case Toolkit::TextSelectionPopup::COPY:
2653     {
2654       mImpl->SendSelectionToClipboard( false ); // Text not modified
2655
2656       mImpl->mEventData->mUpdateCursorPosition = true;
2657
2658       mImpl->RequestRelayout(); // Cursor, Handles, Selection Highlight, Popup
2659       break;
2660     }
2661     case Toolkit::TextSelectionPopup::PASTE:
2662     {
2663       std::string stringToPaste("");
2664       mImpl->GetTextFromClipboard( 0, stringToPaste ); // Paste latest item from system clipboard
2665       PasteText( stringToPaste );
2666       break;
2667     }
2668     case Toolkit::TextSelectionPopup::SELECT:
2669     {
2670       const Vector2& currentCursorPosition = mImpl->mEventData->mDecorator->GetPosition( PRIMARY_CURSOR );
2671
2672       if( mImpl->mEventData->mSelectionEnabled )
2673       {
2674         // Creates a SELECT event.
2675         SelectEvent( currentCursorPosition.x, currentCursorPosition.y, false );
2676       }
2677       break;
2678     }
2679     case Toolkit::TextSelectionPopup::SELECT_ALL:
2680     {
2681       // Creates a SELECT_ALL event
2682       SelectEvent( 0.f, 0.f, true );
2683       break;
2684     }
2685     case Toolkit::TextSelectionPopup::CLIPBOARD:
2686     {
2687       mImpl->ShowClipboard();
2688       break;
2689     }
2690     case Toolkit::TextSelectionPopup::NONE:
2691     {
2692       // Nothing to do.
2693       break;
2694     }
2695   }
2696 }
2697
2698 ImfManager::ImfCallbackData Controller::OnImfEvent( ImfManager& imfManager, const ImfManager::ImfEventData& imfEvent )
2699 {
2700   // Whether the text needs to be relaid-out.
2701   bool requestRelayout = false;
2702
2703   // Whether to retrieve the text and cursor position to be sent to the IMF manager.
2704   bool retrieveText = false;
2705   bool retrieveCursor = false;
2706
2707   switch( imfEvent.eventName )
2708   {
2709     case ImfManager::COMMIT:
2710     {
2711       InsertText( imfEvent.predictiveString, Text::Controller::COMMIT );
2712       requestRelayout = true;
2713       retrieveCursor = true;
2714       break;
2715     }
2716     case ImfManager::PREEDIT:
2717     {
2718       InsertText( imfEvent.predictiveString, Text::Controller::PRE_EDIT );
2719       requestRelayout = true;
2720       retrieveCursor = true;
2721       break;
2722     }
2723     case ImfManager::DELETESURROUNDING:
2724     {
2725       const bool textDeleted = RemoveText( imfEvent.cursorOffset,
2726                                            imfEvent.numberOfChars,
2727                                            DONT_UPDATE_INPUT_STYLE );
2728
2729       if( textDeleted )
2730       {
2731         if( ( 0u != mImpl->mLogicalModel->mText.Count() ) ||
2732             !mImpl->IsPlaceholderAvailable() )
2733         {
2734           mImpl->QueueModifyEvent( ModifyEvent::TEXT_DELETED );
2735         }
2736         else
2737         {
2738           ShowPlaceholderText();
2739         }
2740         mImpl->mEventData->mUpdateCursorPosition = true;
2741         mImpl->mEventData->mScrollAfterDelete = true;
2742
2743         requestRelayout = true;
2744       }
2745       break;
2746     }
2747     case ImfManager::GETSURROUNDING:
2748     {
2749       retrieveText = true;
2750       retrieveCursor = true;
2751       break;
2752     }
2753     case ImfManager::VOID:
2754     {
2755       // do nothing
2756       break;
2757     }
2758   } // end switch
2759
2760   if( requestRelayout )
2761   {
2762     mImpl->mOperationsPending = ALL_OPERATIONS;
2763     mImpl->RequestRelayout();
2764
2765     // Do this last since it provides callbacks into application code
2766     mImpl->mControlInterface.TextChanged();
2767   }
2768
2769   std::string text;
2770   CharacterIndex cursorPosition = 0u;
2771   Length numberOfWhiteSpaces = 0u;
2772
2773   if( retrieveCursor )
2774   {
2775     numberOfWhiteSpaces = mImpl->GetNumberOfWhiteSpaces( 0u );
2776
2777     cursorPosition = mImpl->GetLogicalCursorPosition();
2778
2779     if( cursorPosition < numberOfWhiteSpaces )
2780     {
2781       cursorPosition = 0u;
2782     }
2783     else
2784     {
2785       cursorPosition -= numberOfWhiteSpaces;
2786     }
2787   }
2788
2789   if( retrieveText )
2790   {
2791     mImpl->GetText( numberOfWhiteSpaces, text );
2792   }
2793
2794   ImfManager::ImfCallbackData callbackData( ( retrieveText || retrieveCursor ), cursorPosition, text, false );
2795
2796   return callbackData;
2797 }
2798
2799 Controller::~Controller()
2800 {
2801   delete mImpl;
2802 }
2803
2804 bool Controller::BackspaceKeyEvent()
2805 {
2806   DALI_LOG_INFO( gLogFilter, Debug::Verbose, "Controller::KeyEvent %p DALI_KEY_BACKSPACE\n", this );
2807
2808   bool removed = false;
2809
2810   if( NULL == mImpl->mEventData )
2811   {
2812     return removed;
2813   }
2814
2815   // IMF manager is no longer handling key-events
2816   mImpl->ClearPreEditFlag();
2817
2818   if( EventData::SELECTING == mImpl->mEventData->mState )
2819   {
2820     removed = RemoveSelectedText();
2821   }
2822   else if( mImpl->mEventData->mPrimaryCursorPosition > 0 )
2823   {
2824     // Remove the character before the current cursor position
2825     removed = RemoveText( -1,
2826                           1,
2827                           UPDATE_INPUT_STYLE );
2828   }
2829
2830   if( removed )
2831   {
2832     if( ( 0u != mImpl->mLogicalModel->mText.Count() ) ||
2833         !mImpl->IsPlaceholderAvailable() )
2834     {
2835       mImpl->QueueModifyEvent( ModifyEvent::TEXT_DELETED );
2836     }
2837     else
2838     {
2839       ShowPlaceholderText();
2840     }
2841     mImpl->mEventData->mUpdateCursorPosition = true;
2842     mImpl->mEventData->mScrollAfterDelete = true;
2843   }
2844
2845   return removed;
2846 }
2847
2848 void Controller::ShowPlaceholderText()
2849 {
2850   if( mImpl->IsPlaceholderAvailable() )
2851   {
2852     DALI_ASSERT_DEBUG( mImpl->mEventData && "No placeholder text available" );
2853
2854     if( NULL == mImpl->mEventData )
2855     {
2856       return;
2857     }
2858
2859     mImpl->mEventData->mIsShowingPlaceholderText = true;
2860
2861     // Disable handles when showing place-holder text
2862     mImpl->mEventData->mDecorator->SetHandleActive( GRAB_HANDLE, false );
2863     mImpl->mEventData->mDecorator->SetHandleActive( LEFT_SELECTION_HANDLE, false );
2864     mImpl->mEventData->mDecorator->SetHandleActive( RIGHT_SELECTION_HANDLE, false );
2865
2866     const char* text( NULL );
2867     size_t size( 0 );
2868
2869     // TODO - Switch placeholder text styles when changing state
2870     if( ( EventData::INACTIVE != mImpl->mEventData->mState ) &&
2871         ( 0u != mImpl->mEventData->mPlaceholderTextActive.c_str() ) )
2872     {
2873       text = mImpl->mEventData->mPlaceholderTextActive.c_str();
2874       size = mImpl->mEventData->mPlaceholderTextActive.size();
2875     }
2876     else
2877     {
2878       text = mImpl->mEventData->mPlaceholderTextInactive.c_str();
2879       size = mImpl->mEventData->mPlaceholderTextInactive.size();
2880     }
2881
2882     mImpl->mTextUpdateInfo.mCharacterIndex = 0u;
2883     mImpl->mTextUpdateInfo.mNumberOfCharactersToRemove = mImpl->mTextUpdateInfo.mPreviousNumberOfCharacters;
2884
2885     // Reset model for showing placeholder.
2886     mImpl->mLogicalModel->mText.Clear();
2887     mImpl->mVisualModel->SetTextColor( mImpl->mEventData->mPlaceholderTextColor );
2888
2889     // Convert text into UTF-32
2890     Vector<Character>& utf32Characters = mImpl->mLogicalModel->mText;
2891     utf32Characters.Resize( size );
2892
2893     // This is a bit horrible but std::string returns a (signed) char*
2894     const uint8_t* utf8 = reinterpret_cast<const uint8_t*>( text );
2895
2896     // Transform a text array encoded in utf8 into an array encoded in utf32.
2897     // It returns the actual number of characters.
2898     const Length characterCount = Utf8ToUtf32( utf8, size, utf32Characters.Begin() );
2899     utf32Characters.Resize( characterCount );
2900
2901     // The characters to be added.
2902     mImpl->mTextUpdateInfo.mNumberOfCharactersToAdd = characterCount;
2903
2904     // Reset the cursor position
2905     mImpl->mEventData->mPrimaryCursorPosition = 0;
2906
2907     // The natural size needs to be re-calculated.
2908     mImpl->mRecalculateNaturalSize = true;
2909
2910     // Apply modifications to the model
2911     mImpl->mOperationsPending = ALL_OPERATIONS;
2912
2913     // Update the rest of the model during size negotiation
2914     mImpl->QueueModifyEvent( ModifyEvent::TEXT_REPLACED );
2915   }
2916 }
2917
2918 void Controller::ClearFontData()
2919 {
2920   if( mImpl->mFontDefaults )
2921   {
2922     mImpl->mFontDefaults->mFontId = 0u; // Remove old font ID
2923   }
2924
2925   // Set flags to update the model.
2926   mImpl->mTextUpdateInfo.mCharacterIndex = 0u;
2927   mImpl->mTextUpdateInfo.mNumberOfCharactersToRemove = mImpl->mTextUpdateInfo.mPreviousNumberOfCharacters;
2928   mImpl->mTextUpdateInfo.mNumberOfCharactersToAdd = mImpl->mLogicalModel->mText.Count();
2929
2930   mImpl->mTextUpdateInfo.mClearAll = true;
2931   mImpl->mTextUpdateInfo.mFullRelayoutNeeded = true;
2932   mImpl->mRecalculateNaturalSize = true;
2933
2934   mImpl->mOperationsPending = static_cast<OperationsMask>( mImpl->mOperationsPending |
2935                                                            VALIDATE_FONTS            |
2936                                                            SHAPE_TEXT                |
2937                                                            GET_GLYPH_METRICS         |
2938                                                            LAYOUT                    |
2939                                                            UPDATE_LAYOUT_SIZE        |
2940                                                            REORDER                   |
2941                                                            ALIGN );
2942 }
2943
2944 void Controller::ClearStyleData()
2945 {
2946   mImpl->mLogicalModel->mColorRuns.Clear();
2947   mImpl->mLogicalModel->ClearFontDescriptionRuns();
2948 }
2949
2950 Controller::Controller( ControlInterface& controlInterface )
2951 : mImpl( NULL )
2952 {
2953   mImpl = new Controller::Impl( controlInterface );
2954 }
2955
2956 } // namespace Text
2957
2958 } // namespace Toolkit
2959
2960 } // namespace Dali