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