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