TextModel - Create the bidirectional info for a given range of characters inside...
[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         Vector<BidirectionalLineInfoRun>& bidirectionalLineInfo = mImpl->mLogicalModel->mBidirectionalLineInfo;
1386
1387         // Check first if there are paragraphs with bidirectional info.
1388         if( 0u != bidirectionalInfo.Count() )
1389         {
1390           // Get the lines
1391           const Length numberOfLines = mImpl->mVisualModel->mLines.Count();
1392           const CharacterIndex startIndex = 0u;
1393           Length requestedNumberOfCharacters = mImpl->mLogicalModel->mText.Count();
1394
1395           // Reorder the lines.
1396           bidirectionalLineInfo.Reserve( numberOfLines ); // Reserve because is not known yet how many lines have right to left characters.
1397           ReorderLines( bidirectionalInfo,
1398                         startIndex,
1399                         requestedNumberOfCharacters,
1400                         lines,
1401                         bidirectionalLineInfo );
1402
1403           // Set the bidirectional info per line into the layout parameters.
1404           layoutParameters.lineBidirectionalInfoRunsBuffer = bidirectionalLineInfo.Begin();
1405           layoutParameters.numberOfBidirectionalInfoRuns = bidirectionalLineInfo.Count();
1406
1407           // Set the bidirectional info into the model.
1408           mImpl->mLogicalModel->SetVisualToLogicalMap( layoutParameters.lineBidirectionalInfoRunsBuffer,
1409                                                        layoutParameters.numberOfBidirectionalInfoRuns,
1410                                                        startIndex,
1411                                                        requestedNumberOfCharacters );
1412
1413           // Get the character to glyph conversion table and set into the layout.
1414           layoutParameters.charactersToGlyphsBuffer = mImpl->mVisualModel->mCharactersToGlyph.Begin();
1415           // Get the glyphs per character table and set into the layout.
1416           layoutParameters.glyphsPerCharacterBuffer = mImpl->mVisualModel->mGlyphsPerCharacter.Begin();
1417
1418           // Re-layout the text. Reorder those lines with right to left characters.
1419           mImpl->mLayoutEngine.ReLayoutRightToLeftLines( layoutParameters,
1420                                                          glyphPositions );
1421
1422           // Free the allocated memory used to store the conversion table in the bidirectional line info run.
1423           for( Vector<BidirectionalLineInfoRun>::Iterator it = bidirectionalLineInfo.Begin(),
1424                  endIt = bidirectionalLineInfo.End();
1425                it != endIt;
1426                ++it )
1427           {
1428             BidirectionalLineInfoRun& bidiLineInfo = *it;
1429
1430             free( bidiLineInfo.visualToLogicalMap );
1431             bidiLineInfo.visualToLogicalMap = NULL;
1432           }
1433
1434           bidirectionalLineInfo.Clear();
1435         }
1436       } // REORDER
1437
1438       // Sets the actual size.
1439       if( UPDATE_ACTUAL_SIZE & operations )
1440       {
1441         mImpl->mVisualModel->SetActualSize( layoutSize );
1442       }
1443     } // view updated
1444   }
1445   else
1446   {
1447     layoutSize = mImpl->mVisualModel->GetActualSize();
1448   }
1449
1450   if( ALIGN & operations )
1451   {
1452     // The laid-out lines.
1453     Vector<LineRun>& lines = mImpl->mVisualModel->mLines;
1454
1455     mImpl->mLayoutEngine.Align( layoutSize,
1456                                 lines );
1457
1458     viewUpdated = true;
1459   }
1460
1461   DALI_LOG_INFO( gLogFilter, Debug::Verbose, "<--Controller::DoRelayout, view updated %s\n", ( viewUpdated ? "true" : "false" ) );
1462   return viewUpdated;
1463 }
1464
1465 void Controller::SetMultiLineEnabled( bool enable )
1466 {
1467   const LayoutEngine::Layout layout = enable ? LayoutEngine::MULTI_LINE_BOX : LayoutEngine::SINGLE_LINE_BOX;
1468
1469   if( layout != mImpl->mLayoutEngine.GetLayout() )
1470   {
1471     // Set the layout type.
1472     mImpl->mLayoutEngine.SetLayout( layout );
1473
1474     // Set the flags to redo the layout operations
1475     const OperationsMask layoutOperations =  static_cast<OperationsMask>( LAYOUT             |
1476                                                                           UPDATE_ACTUAL_SIZE |
1477                                                                           ALIGN              |
1478                                                                           REORDER );
1479
1480     mImpl->mOperationsPending = static_cast<OperationsMask>( mImpl->mOperationsPending | layoutOperations );
1481
1482     mImpl->RequestRelayout();
1483   }
1484 }
1485
1486 bool Controller::IsMultiLineEnabled() const
1487 {
1488   return LayoutEngine::MULTI_LINE_BOX == mImpl->mLayoutEngine.GetLayout();
1489 }
1490
1491 void Controller::SetHorizontalAlignment( LayoutEngine::HorizontalAlignment alignment )
1492 {
1493   if( alignment != mImpl->mLayoutEngine.GetHorizontalAlignment() )
1494   {
1495     // Set the alignment.
1496     mImpl->mLayoutEngine.SetHorizontalAlignment( alignment );
1497
1498     // Set the flag to redo the alignment operation.
1499     mImpl->mOperationsPending = static_cast<OperationsMask>( mImpl->mOperationsPending | ALIGN );
1500
1501     mImpl->RequestRelayout();
1502   }
1503 }
1504
1505 LayoutEngine::HorizontalAlignment Controller::GetHorizontalAlignment() const
1506 {
1507   return mImpl->mLayoutEngine.GetHorizontalAlignment();
1508 }
1509
1510 void Controller::SetVerticalAlignment( LayoutEngine::VerticalAlignment alignment )
1511 {
1512   if( alignment != mImpl->mLayoutEngine.GetVerticalAlignment() )
1513   {
1514     // Set the alignment.
1515     mImpl->mLayoutEngine.SetVerticalAlignment( alignment );
1516
1517     mImpl->mOperationsPending = static_cast<OperationsMask>( mImpl->mOperationsPending | ALIGN );
1518
1519     mImpl->RequestRelayout();
1520   }
1521 }
1522
1523 LayoutEngine::VerticalAlignment Controller::GetVerticalAlignment() const
1524 {
1525   return mImpl->mLayoutEngine.GetVerticalAlignment();
1526 }
1527
1528 void Controller::CalculateTextAlignment( const Size& size )
1529 {
1530   // Get the direction of the first character.
1531   const CharacterDirection firstParagraphDirection = mImpl->mLogicalModel->GetCharacterDirection( 0u );
1532
1533   Size actualSize = mImpl->mVisualModel->GetActualSize();
1534   if( fabsf( actualSize.height ) < Math::MACHINE_EPSILON_1000 )
1535   {
1536     // Get the line height of the default font.
1537     actualSize.height = mImpl->GetDefaultFontLineHeight();
1538   }
1539
1540   // If the first paragraph is right to left swap ALIGN_BEGIN and ALIGN_END;
1541   LayoutEngine::HorizontalAlignment horizontalAlignment = mImpl->mLayoutEngine.GetHorizontalAlignment();
1542   if( firstParagraphDirection &&
1543       ( LayoutEngine::HORIZONTAL_ALIGN_CENTER != horizontalAlignment ) )
1544   {
1545     if( LayoutEngine::HORIZONTAL_ALIGN_BEGIN == horizontalAlignment )
1546     {
1547       horizontalAlignment = LayoutEngine::HORIZONTAL_ALIGN_END;
1548     }
1549     else
1550     {
1551       horizontalAlignment = LayoutEngine::HORIZONTAL_ALIGN_BEGIN;
1552     }
1553   }
1554
1555   switch( horizontalAlignment )
1556   {
1557     case LayoutEngine::HORIZONTAL_ALIGN_BEGIN:
1558     {
1559       mImpl->mAlignmentOffset.x = 0.f;
1560       break;
1561     }
1562     case LayoutEngine::HORIZONTAL_ALIGN_CENTER:
1563     {
1564       mImpl->mAlignmentOffset.x = floorf( 0.5f * ( size.width - actualSize.width ) ); // try to avoid pixel alignment.
1565       break;
1566     }
1567     case LayoutEngine::HORIZONTAL_ALIGN_END:
1568     {
1569       mImpl->mAlignmentOffset.x = size.width - actualSize.width;
1570       break;
1571     }
1572   }
1573
1574   const LayoutEngine::VerticalAlignment verticalAlignment = mImpl->mLayoutEngine.GetVerticalAlignment();
1575   switch( verticalAlignment )
1576   {
1577     case LayoutEngine::VERTICAL_ALIGN_TOP:
1578     {
1579       mImpl->mAlignmentOffset.y = 0.f;
1580       break;
1581     }
1582     case LayoutEngine::VERTICAL_ALIGN_CENTER:
1583     {
1584       mImpl->mAlignmentOffset.y = floorf( 0.5f * ( size.height - actualSize.height ) ); // try to avoid pixel alignment.
1585       break;
1586     }
1587     case LayoutEngine::VERTICAL_ALIGN_BOTTOM:
1588     {
1589       mImpl->mAlignmentOffset.y = size.height - actualSize.height;
1590       break;
1591     }
1592   }
1593 }
1594
1595 LayoutEngine& Controller::GetLayoutEngine()
1596 {
1597   return mImpl->mLayoutEngine;
1598 }
1599
1600 View& Controller::GetView()
1601 {
1602   return mImpl->mView;
1603 }
1604
1605 void Controller::KeyboardFocusGainEvent()
1606 {
1607   DALI_ASSERT_DEBUG( mImpl->mEventData && "Unexpected KeyboardFocusGainEvent" );
1608
1609   if( NULL != mImpl->mEventData )
1610   {
1611     if( ( EventData::INACTIVE == mImpl->mEventData->mState ) ||
1612         ( EventData::INTERRUPTED == mImpl->mEventData->mState ) )
1613     {
1614       mImpl->ChangeState( EventData::EDITING );
1615       mImpl->mEventData->mUpdateCursorPosition = true; //If editing started without tap event, cursor update must be triggered.
1616     }
1617
1618     if( mImpl->IsShowingPlaceholderText() )
1619     {
1620       // Show alternative placeholder-text when editing
1621       ShowPlaceholderText();
1622     }
1623
1624     mImpl->RequestRelayout();
1625   }
1626 }
1627
1628 void Controller::KeyboardFocusLostEvent()
1629 {
1630   DALI_ASSERT_DEBUG( mImpl->mEventData && "Unexpected KeyboardFocusLostEvent" );
1631
1632   if( NULL != mImpl->mEventData )
1633   {
1634     if( EventData::INTERRUPTED != mImpl->mEventData->mState )
1635     {
1636       mImpl->ChangeState( EventData::INACTIVE );
1637
1638       if( !mImpl->IsShowingRealText() )
1639       {
1640         // Revert to regular placeholder-text when not editing
1641         ShowPlaceholderText();
1642       }
1643     }
1644   }
1645   mImpl->RequestRelayout();
1646 }
1647
1648 bool Controller::KeyEvent( const Dali::KeyEvent& keyEvent )
1649 {
1650   DALI_ASSERT_DEBUG( mImpl->mEventData && "Unexpected KeyEvent" );
1651
1652   bool textChanged( false );
1653
1654   if( ( NULL != mImpl->mEventData ) &&
1655       ( keyEvent.state == KeyEvent::Down ) )
1656   {
1657     int keyCode = keyEvent.keyCode;
1658     const std::string& keyString = keyEvent.keyPressed;
1659
1660     // Pre-process to separate modifying events from non-modifying input events.
1661     if( Dali::DALI_KEY_ESCAPE == keyCode )
1662     {
1663       // Escape key is a special case which causes focus loss
1664       KeyboardFocusLostEvent();
1665     }
1666     else if( ( Dali::DALI_KEY_CURSOR_LEFT  == keyCode ) ||
1667              ( Dali::DALI_KEY_CURSOR_RIGHT == keyCode ) ||
1668              ( Dali::DALI_KEY_CURSOR_UP    == keyCode ) ||
1669              ( Dali::DALI_KEY_CURSOR_DOWN  == keyCode ) )
1670     {
1671       Event event( Event::CURSOR_KEY_EVENT );
1672       event.p1.mInt = keyCode;
1673       mImpl->mEventData->mEventQueue.push_back( event );
1674     }
1675     else if( Dali::DALI_KEY_BACKSPACE == keyCode )
1676     {
1677       textChanged = BackspaceKeyEvent();
1678     }
1679     else if( IsKey( keyEvent,  Dali::DALI_KEY_POWER ) )
1680     {
1681       mImpl->ChangeState( EventData::INTERRUPTED ); // State is not INACTIVE as expect to return to edit mode.
1682       // Avoids calling the InsertText() method which can delete selected text
1683     }
1684     else if( IsKey( keyEvent, Dali::DALI_KEY_MENU ) ||
1685              IsKey( keyEvent, Dali::DALI_KEY_HOME ) )
1686     {
1687       mImpl->ChangeState( EventData::INACTIVE );
1688       // Menu/Home key behaviour does not allow edit mode to resume like Power key
1689       // Avoids calling the InsertText() method which can delete selected text
1690     }
1691     else if( Dali::DALI_KEY_SHIFT_LEFT == keyCode )
1692     {
1693       // DALI_KEY_SHIFT_LEFT is the key code for the Left Shift. It's sent (by the imf?) when the predictive text is enabled
1694       // and a character is typed after the type of a upper case latin character.
1695
1696       // Do nothing.
1697     }
1698     else
1699     {
1700       DALI_LOG_INFO( gLogFilter, Debug::Verbose, "Controller::KeyEvent %p keyString %s\n", this, keyString.c_str() );
1701
1702       // IMF manager is no longer handling key-events
1703       mImpl->ClearPreEditFlag();
1704
1705       InsertText( keyString, COMMIT );
1706       textChanged = true;
1707     }
1708
1709     if( ( mImpl->mEventData->mState != EventData::INTERRUPTED ) &&
1710         ( mImpl->mEventData->mState != EventData::INACTIVE ) )
1711     {
1712       mImpl->ChangeState( EventData::EDITING );
1713     }
1714
1715     mImpl->RequestRelayout();
1716   }
1717
1718   if( textChanged )
1719   {
1720     // Do this last since it provides callbacks into application code
1721     mImpl->mControlInterface.TextChanged();
1722   }
1723
1724   return true;
1725 }
1726
1727 void Controller::InsertText( const std::string& text, Controller::InsertType type )
1728 {
1729   bool removedPrevious( false );
1730   bool maxLengthReached( false );
1731
1732   DALI_ASSERT_DEBUG( NULL != mImpl->mEventData && "Unexpected InsertText" )
1733
1734   if( NULL == mImpl->mEventData )
1735   {
1736     return;
1737   }
1738
1739   DALI_LOG_INFO( gLogFilter, Debug::Verbose, "Controller::InsertText %p %s (%s) mPrimaryCursorPosition %d mPreEditFlag %d mPreEditStartPosition %d mPreEditLength %d\n",
1740                  this, text.c_str(), (COMMIT == type ? "COMMIT" : "PRE_EDIT"),
1741                  mImpl->mEventData->mPrimaryCursorPosition, mImpl->mEventData->mPreEditFlag, mImpl->mEventData->mPreEditStartPosition, mImpl->mEventData->mPreEditLength );
1742
1743   // TODO: At the moment the underline runs are only for pre-edit.
1744   mImpl->mVisualModel->mUnderlineRuns.Clear();
1745
1746   Vector<Character> utf32Characters;
1747   Length characterCount( 0u );
1748
1749   // Remove the previous IMF pre-edit (predicitive text)
1750   if( mImpl->mEventData->mPreEditFlag &&
1751       ( 0 != mImpl->mEventData->mPreEditLength ) )
1752   {
1753     CharacterIndex offset = mImpl->mEventData->mPrimaryCursorPosition - mImpl->mEventData->mPreEditStartPosition;
1754
1755     removedPrevious = RemoveText( -static_cast<int>(offset), mImpl->mEventData->mPreEditLength );
1756
1757     mImpl->mEventData->mPrimaryCursorPosition = mImpl->mEventData->mPreEditStartPosition;
1758     mImpl->mEventData->mPreEditLength = 0;
1759   }
1760   else
1761   {
1762     // Remove the previous Selection
1763     removedPrevious = RemoveSelectedText();
1764   }
1765
1766   if( !text.empty() )
1767   {
1768     //  Convert text into UTF-32
1769     utf32Characters.Resize( text.size() );
1770
1771     // This is a bit horrible but std::string returns a (signed) char*
1772     const uint8_t* utf8 = reinterpret_cast<const uint8_t*>( text.c_str() );
1773
1774     // Transform a text array encoded in utf8 into an array encoded in utf32.
1775     // It returns the actual number of characters.
1776     characterCount = Utf8ToUtf32( utf8, text.size(), utf32Characters.Begin() );
1777     utf32Characters.Resize( characterCount );
1778
1779     DALI_ASSERT_DEBUG( text.size() >= utf32Characters.Count() && "Invalid UTF32 conversion length" );
1780     DALI_LOG_INFO( gLogFilter, Debug::Verbose, "UTF8 size %d, UTF32 size %d\n", text.size(), utf32Characters.Count() );
1781   }
1782
1783   if( 0u != utf32Characters.Count() ) // Check if Utf8ToUtf32 conversion succeeded
1784   {
1785     // The placeholder text is no longer needed
1786     if( mImpl->IsShowingPlaceholderText() )
1787     {
1788       ResetText();
1789     }
1790
1791     mImpl->ChangeState( EventData::EDITING );
1792
1793     // Handle the IMF (predicitive text) state changes
1794     if( COMMIT == type )
1795     {
1796       // IMF manager is no longer handling key-events
1797       mImpl->ClearPreEditFlag();
1798     }
1799     else // PRE_EDIT
1800     {
1801       if( !mImpl->mEventData->mPreEditFlag )
1802       {
1803         DALI_LOG_INFO( gLogFilter, Debug::Verbose, "Entered PreEdit state" );
1804
1805         // Record the start of the pre-edit text
1806         mImpl->mEventData->mPreEditStartPosition = mImpl->mEventData->mPrimaryCursorPosition;
1807       }
1808
1809       mImpl->mEventData->mPreEditLength = utf32Characters.Count();
1810       mImpl->mEventData->mPreEditFlag = true;
1811
1812       DALI_LOG_INFO( gLogFilter, Debug::Verbose, "mPreEditStartPosition %d mPreEditLength %d\n", mImpl->mEventData->mPreEditStartPosition, mImpl->mEventData->mPreEditLength );
1813     }
1814
1815     const Length numberOfCharactersInModel = mImpl->mLogicalModel->mText.Count();
1816
1817     // Restrict new text to fit within Maximum characters setting
1818     Length maxSizeOfNewText = std::min ( ( mImpl->mMaximumNumberOfCharacters - numberOfCharactersInModel ), characterCount );
1819     maxLengthReached = ( characterCount > maxSizeOfNewText );
1820
1821     // The cursor position.
1822     CharacterIndex& cursorIndex = mImpl->mEventData->mPrimaryCursorPosition;
1823
1824     // Update the text's style.
1825
1826     // Updates the text style runs by adding characters.
1827     mImpl->mLogicalModel->UpdateTextStyleRuns( cursorIndex, maxSizeOfNewText );
1828
1829     // Get the character index from the cursor index.
1830     const CharacterIndex styleIndex = ( cursorIndex > 0u ) ? cursorIndex - 1u : 0u;
1831
1832     // Retrieve the text's style for the given index.
1833     InputStyle style;
1834     mImpl->mLogicalModel->RetrieveStyle( styleIndex, style );
1835
1836     // Whether to add a new text color run.
1837     const bool addColorRun = style.textColor != mImpl->mEventData->mInputStyle.textColor;
1838
1839     // Whether to add a new font run.
1840     const bool addFontNameRun = style.familyName != mImpl->mEventData->mInputStyle.familyName;
1841     const bool addFontWeightRun = style.weight != mImpl->mEventData->mInputStyle.weight;
1842     const bool addFontWidthRun = style.width != mImpl->mEventData->mInputStyle.width;
1843     const bool addFontSlantRun = style.slant != mImpl->mEventData->mInputStyle.slant;
1844     const bool addFontSizeRun = style.size != mImpl->mEventData->mInputStyle.size;
1845
1846     // Add style runs.
1847     if( addColorRun )
1848     {
1849       const VectorBase::SizeType numberOfRuns = mImpl->mLogicalModel->mColorRuns.Count();
1850       mImpl->mLogicalModel->mColorRuns.Resize( numberOfRuns + 1u );
1851
1852       ColorRun& colorRun = *( mImpl->mLogicalModel->mColorRuns.Begin() + numberOfRuns );
1853       colorRun.color = mImpl->mEventData->mInputStyle.textColor;
1854       colorRun.characterRun.characterIndex = cursorIndex;
1855       colorRun.characterRun.numberOfCharacters = maxSizeOfNewText;
1856     }
1857
1858     if( addFontNameRun   ||
1859         addFontWeightRun ||
1860         addFontWidthRun  ||
1861         addFontSlantRun  ||
1862         addFontSizeRun )
1863     {
1864       const VectorBase::SizeType numberOfRuns = mImpl->mLogicalModel->mFontDescriptionRuns.Count();
1865       mImpl->mLogicalModel->mFontDescriptionRuns.Resize( numberOfRuns + 1u );
1866
1867       FontDescriptionRun& fontDescriptionRun = *( mImpl->mLogicalModel->mFontDescriptionRuns.Begin() + numberOfRuns );
1868
1869       if( addFontNameRun )
1870       {
1871         fontDescriptionRun.familyLength = mImpl->mEventData->mInputStyle.familyName.size();
1872         fontDescriptionRun.familyName = new char[fontDescriptionRun.familyLength];
1873         memcpy( fontDescriptionRun.familyName, mImpl->mEventData->mInputStyle.familyName.c_str(), fontDescriptionRun.familyLength );
1874         fontDescriptionRun.familyDefined = true;
1875
1876         // The memory allocated for the font family name is freed when the font description is removed from the logical model.
1877       }
1878
1879       if( addFontWeightRun )
1880       {
1881         fontDescriptionRun.weight = mImpl->mEventData->mInputStyle.weight;
1882         fontDescriptionRun.weightDefined = true;
1883       }
1884
1885       if( addFontWidthRun )
1886       {
1887         fontDescriptionRun.width = mImpl->mEventData->mInputStyle.width;
1888         fontDescriptionRun.widthDefined = true;
1889       }
1890
1891       if( addFontSlantRun )
1892       {
1893         fontDescriptionRun.slant = mImpl->mEventData->mInputStyle.slant;
1894         fontDescriptionRun.slantDefined = true;
1895       }
1896
1897       if( addFontSizeRun )
1898       {
1899         fontDescriptionRun.size = static_cast<PointSize26Dot6>( mImpl->mEventData->mInputStyle.size * 64.f );
1900         fontDescriptionRun.sizeDefined = true;
1901       }
1902
1903       fontDescriptionRun.characterRun.characterIndex = cursorIndex;
1904       fontDescriptionRun.characterRun.numberOfCharacters = maxSizeOfNewText;
1905     }
1906
1907     // Insert at current cursor position.
1908     Vector<Character>& modifyText = mImpl->mLogicalModel->mText;
1909
1910     if( cursorIndex < numberOfCharactersInModel )
1911     {
1912       modifyText.Insert( modifyText.Begin() + cursorIndex, utf32Characters.Begin(), utf32Characters.Begin() + maxSizeOfNewText );
1913     }
1914     else
1915     {
1916       modifyText.Insert( modifyText.End(), utf32Characters.Begin(), utf32Characters.Begin() + maxSizeOfNewText );
1917     }
1918
1919     cursorIndex += maxSizeOfNewText;
1920
1921     DALI_LOG_INFO( gLogFilter, Debug::Verbose, "Inserted %d characters, new size %d new cursor %d\n", maxSizeOfNewText, mImpl->mLogicalModel->mText.Count(), mImpl->mEventData->mPrimaryCursorPosition );
1922   }
1923
1924   if( ( 0u == mImpl->mLogicalModel->mText.Count() ) &&
1925       mImpl->IsPlaceholderAvailable() )
1926   {
1927     // Show place-holder if empty after removing the pre-edit text
1928     ShowPlaceholderText();
1929     mImpl->mEventData->mUpdateCursorPosition = true;
1930     mImpl->ClearPreEditFlag();
1931   }
1932   else if( removedPrevious ||
1933            ( 0 != utf32Characters.Count() ) )
1934   {
1935     // Queue an inserted event
1936     mImpl->QueueModifyEvent( ModifyEvent::TEXT_INSERTED );
1937   }
1938
1939   if( maxLengthReached )
1940   {
1941     DALI_LOG_INFO( gLogFilter, Debug::Verbose, "MaxLengthReached (%d)\n", mImpl->mLogicalModel->mText.Count() );
1942
1943     mImpl->ResetImfManager();
1944
1945     // Do this last since it provides callbacks into application code
1946     mImpl->mControlInterface.MaxLengthReached();
1947   }
1948 }
1949
1950 bool Controller::RemoveSelectedText()
1951 {
1952   bool textRemoved( false );
1953
1954   if( EventData::SELECTING == mImpl->mEventData->mState )
1955   {
1956     std::string removedString;
1957     mImpl->RetrieveSelection( removedString, true );
1958
1959     if( !removedString.empty() )
1960     {
1961       textRemoved = true;
1962       mImpl->ChangeState( EventData::EDITING );
1963     }
1964   }
1965
1966   return textRemoved;
1967 }
1968
1969 void Controller::TapEvent( unsigned int tapCount, float x, float y )
1970 {
1971   DALI_ASSERT_DEBUG( mImpl->mEventData && "Unexpected TapEvent" );
1972
1973   if( NULL != mImpl->mEventData )
1974   {
1975     DALI_LOG_INFO( gLogFilter, Debug::Concise, "TapEvent state:%d \n", mImpl->mEventData->mState );
1976
1977     if( 1u == tapCount )
1978     {
1979       // This is to avoid unnecessary relayouts when tapping an empty text-field
1980       bool relayoutNeeded( false );
1981
1982       if( ( EventData::EDITING_WITH_PASTE_POPUP == mImpl->mEventData->mState ) ||
1983           ( EventData::EDITING_WITH_PASTE_POPUP == mImpl->mEventData->mState ) )
1984       {
1985         mImpl->ChangeState( EventData::EDITING_WITH_GRAB_HANDLE);  // If Popup shown hide it here so can be shown again if required.
1986       }
1987
1988       if( mImpl->IsShowingRealText() && ( EventData::INACTIVE != mImpl->mEventData->mState ) )
1989       {
1990         // Already in an active state so show a popup
1991         if( !mImpl->IsClipboardEmpty() )
1992         {
1993           // Shows Paste popup but could show full popup with Selection options. ( EDITING_WITH_POPUP )
1994           mImpl->ChangeState( EventData::EDITING_WITH_PASTE_POPUP );
1995         }
1996         else
1997         {
1998           mImpl->ChangeState( EventData::EDITING_WITH_GRAB_HANDLE );
1999         }
2000         relayoutNeeded = true;
2001       }
2002       else
2003       {
2004         if( mImpl->IsShowingPlaceholderText() && !mImpl->IsFocusedPlaceholderAvailable() )
2005         {
2006           // Hide placeholder text
2007           ResetText();
2008         }
2009
2010         if( EventData::INACTIVE == mImpl->mEventData->mState )
2011         {
2012           mImpl->ChangeState( EventData::EDITING );
2013         }
2014         else if( !mImpl->IsClipboardEmpty() )
2015         {
2016           mImpl->ChangeState( EventData::EDITING_WITH_POPUP );
2017         }
2018         relayoutNeeded = true;
2019       }
2020
2021       // Handles & cursors must be repositioned after Relayout() i.e. after the Model has been updated
2022       if( relayoutNeeded )
2023       {
2024         Event event( Event::TAP_EVENT );
2025         event.p1.mUint = tapCount;
2026         event.p2.mFloat = x;
2027         event.p3.mFloat = y;
2028         mImpl->mEventData->mEventQueue.push_back( event );
2029
2030         mImpl->RequestRelayout();
2031       }
2032     }
2033     else if( 2u == tapCount )
2034     {
2035       if( mImpl->mEventData->mSelectionEnabled &&
2036           mImpl->IsShowingRealText() )
2037       {
2038         SelectEvent( x, y, false );
2039       }
2040     }
2041   }
2042
2043   // Reset keyboard as tap event has occurred.
2044   mImpl->ResetImfManager();
2045 }
2046
2047 void Controller::PanEvent( Gesture::State state, const Vector2& displacement )
2048         // Show cursor and grabhandle on first tap, this matches the behaviour of tapping when already editing
2049 {
2050   DALI_ASSERT_DEBUG( mImpl->mEventData && "Unexpected PanEvent" );
2051
2052   if( NULL != mImpl->mEventData )
2053   {
2054     Event event( Event::PAN_EVENT );
2055     event.p1.mInt = state;
2056     event.p2.mFloat = displacement.x;
2057     event.p3.mFloat = displacement.y;
2058     mImpl->mEventData->mEventQueue.push_back( event );
2059
2060     mImpl->RequestRelayout();
2061   }
2062 }
2063
2064 void Controller::LongPressEvent( Gesture::State state, float x, float y  )
2065 {
2066   DALI_ASSERT_DEBUG( mImpl->mEventData && "Unexpected LongPressEvent" );
2067
2068   if( ( state == Gesture::Started ) &&
2069       ( NULL != mImpl->mEventData ) )
2070   {
2071     if( !mImpl->IsShowingRealText() )
2072     {
2073       Event event( Event::LONG_PRESS_EVENT );
2074       event.p1.mInt = state;
2075       mImpl->mEventData->mEventQueue.push_back( event );
2076       mImpl->RequestRelayout();
2077     }
2078     else
2079     {
2080       // The 1st long-press on inactive text-field is treated as tap
2081       if( EventData::INACTIVE == mImpl->mEventData->mState )
2082       {
2083         mImpl->ChangeState( EventData::EDITING );
2084
2085         Event event( Event::TAP_EVENT );
2086         event.p1.mUint = 1;
2087         event.p2.mFloat = x;
2088         event.p3.mFloat = y;
2089         mImpl->mEventData->mEventQueue.push_back( event );
2090
2091         mImpl->RequestRelayout();
2092       }
2093       else
2094       {
2095         // Reset the imf manger to commit the pre-edit before selecting the text.
2096         mImpl->ResetImfManager();
2097
2098         SelectEvent( x, y, false );
2099       }
2100     }
2101   }
2102 }
2103
2104 void Controller::SelectEvent( float x, float y, bool selectAll )
2105 {
2106   DALI_LOG_INFO( gLogFilter, Debug::Verbose, "Controller::SelectEvent\n" );
2107
2108   if( NULL != mImpl->mEventData )
2109   {
2110     mImpl->ChangeState( EventData::SELECTING );
2111
2112     if( selectAll )
2113     {
2114       Event event( Event::SELECT_ALL );
2115       mImpl->mEventData->mEventQueue.push_back( event );
2116     }
2117     else
2118     {
2119       Event event( Event::SELECT );
2120       event.p2.mFloat = x;
2121       event.p3.mFloat = y;
2122       mImpl->mEventData->mEventQueue.push_back( event );
2123     }
2124
2125     mImpl->RequestRelayout();
2126   }
2127 }
2128
2129 void Controller::GetTargetSize( Vector2& targetSize )
2130 {
2131   targetSize = mImpl->mVisualModel->mControlSize;
2132 }
2133
2134 void Controller::AddDecoration( Actor& actor, bool needsClipping )
2135 {
2136   mImpl->mControlInterface.AddDecoration( actor, needsClipping );
2137 }
2138
2139 void Controller::DecorationEvent( HandleType handleType, HandleState state, float x, float y )
2140 {
2141   DALI_ASSERT_DEBUG( mImpl->mEventData && "Unexpected DecorationEvent" );
2142
2143   if( NULL != mImpl->mEventData )
2144   {
2145     switch( handleType )
2146     {
2147       case GRAB_HANDLE:
2148       {
2149         Event event( Event::GRAB_HANDLE_EVENT );
2150         event.p1.mUint  = state;
2151         event.p2.mFloat = x;
2152         event.p3.mFloat = y;
2153
2154         mImpl->mEventData->mEventQueue.push_back( event );
2155         break;
2156       }
2157       case LEFT_SELECTION_HANDLE:
2158       {
2159         Event event( Event::LEFT_SELECTION_HANDLE_EVENT );
2160         event.p1.mUint  = state;
2161         event.p2.mFloat = x;
2162         event.p3.mFloat = y;
2163
2164         mImpl->mEventData->mEventQueue.push_back( event );
2165         break;
2166       }
2167       case RIGHT_SELECTION_HANDLE:
2168       {
2169         Event event( Event::RIGHT_SELECTION_HANDLE_EVENT );
2170         event.p1.mUint  = state;
2171         event.p2.mFloat = x;
2172         event.p3.mFloat = y;
2173
2174         mImpl->mEventData->mEventQueue.push_back( event );
2175         break;
2176       }
2177       case LEFT_SELECTION_HANDLE_MARKER:
2178       case RIGHT_SELECTION_HANDLE_MARKER:
2179       {
2180         // Markers do not move the handles.
2181         break;
2182       }
2183       case HANDLE_TYPE_COUNT:
2184       {
2185         DALI_ASSERT_DEBUG( !"Controller::HandleEvent. Unexpected handle type" );
2186       }
2187     }
2188
2189     mImpl->RequestRelayout();
2190   }
2191 }
2192
2193 void Controller::PasteText( const std::string& stringToPaste )
2194 {
2195   InsertText( stringToPaste, Text::Controller::COMMIT );
2196   mImpl->ChangeState( EventData::EDITING );
2197   mImpl->RequestRelayout();
2198
2199   // Do this last since it provides callbacks into application code
2200   mImpl->mControlInterface.TextChanged();
2201 }
2202
2203 void Controller::PasteClipboardItemEvent()
2204 {
2205   // Retrieve the clipboard contents first
2206   ClipboardEventNotifier notifier( ClipboardEventNotifier::Get() );
2207   std::string stringToPaste( notifier.GetContent() );
2208
2209   // Commit the current pre-edit text; the contents of the clipboard should be appended
2210   mImpl->ResetImfManager();
2211
2212   // Paste
2213   PasteText( stringToPaste );
2214 }
2215
2216 void Controller::TextPopupButtonTouched( Dali::Toolkit::TextSelectionPopup::Buttons button )
2217 {
2218   if( NULL == mImpl->mEventData )
2219   {
2220     return;
2221   }
2222
2223   switch( button )
2224   {
2225     case Toolkit::TextSelectionPopup::CUT:
2226     {
2227       mImpl->SendSelectionToClipboard( true ); // Synchronous call to modify text
2228       mImpl->mOperationsPending = ALL_OPERATIONS;
2229
2230       // This is to reset the virtual keyboard to Upper-case
2231       if( 0u == mImpl->mLogicalModel->mText.Count() )
2232       {
2233         NotifyImfManager();
2234       }
2235
2236       if( ( 0u != mImpl->mLogicalModel->mText.Count() ) ||
2237           !mImpl->IsPlaceholderAvailable() )
2238       {
2239         mImpl->QueueModifyEvent( ModifyEvent::TEXT_DELETED );
2240       }
2241       else
2242       {
2243         ShowPlaceholderText();
2244         mImpl->mEventData->mUpdateCursorPosition = true;
2245       }
2246       mImpl->RequestRelayout();
2247       mImpl->mControlInterface.TextChanged();
2248       break;
2249     }
2250     case Toolkit::TextSelectionPopup::COPY:
2251     {
2252       mImpl->SendSelectionToClipboard( false ); // Text not modified
2253       mImpl->RequestRelayout(); // Handles, Selection Highlight, Popup
2254       break;
2255     }
2256     case Toolkit::TextSelectionPopup::PASTE:
2257     {
2258       std::string stringToPaste("");
2259       mImpl->GetTextFromClipboard( 0, stringToPaste ); // Paste latest item from system clipboard
2260       PasteText( stringToPaste );
2261       break;
2262     }
2263     case Toolkit::TextSelectionPopup::SELECT:
2264     {
2265       const Vector2& currentCursorPosition = mImpl->mEventData->mDecorator->GetPosition( PRIMARY_CURSOR );
2266
2267       if( mImpl->mEventData->mSelectionEnabled )
2268       {
2269         // Creates a SELECT event.
2270         SelectEvent( currentCursorPosition.x, currentCursorPosition.y, false );
2271       }
2272       break;
2273     }
2274     case Toolkit::TextSelectionPopup::SELECT_ALL:
2275     {
2276       // Creates a SELECT_ALL event
2277       SelectEvent( 0.f, 0.f, true );
2278       break;
2279     }
2280     case Toolkit::TextSelectionPopup::CLIPBOARD:
2281     {
2282       mImpl->ShowClipboard();
2283       break;
2284     }
2285     case Toolkit::TextSelectionPopup::NONE:
2286     {
2287       // Nothing to do.
2288       break;
2289     }
2290   }
2291 }
2292
2293 ImfManager::ImfCallbackData Controller::OnImfEvent( ImfManager& imfManager, const ImfManager::ImfEventData& imfEvent )
2294 {
2295   bool update = false;
2296   bool requestRelayout = false;
2297
2298   std::string text;
2299   unsigned int cursorPosition = 0u;
2300
2301   switch( imfEvent.eventName )
2302   {
2303     case ImfManager::COMMIT:
2304     {
2305       InsertText( imfEvent.predictiveString, Text::Controller::COMMIT );
2306       update = true;
2307       requestRelayout = true;
2308       break;
2309     }
2310     case ImfManager::PREEDIT:
2311     {
2312       InsertText( imfEvent.predictiveString, Text::Controller::PRE_EDIT );
2313       update = true;
2314       requestRelayout = true;
2315       break;
2316     }
2317     case ImfManager::DELETESURROUNDING:
2318     {
2319       update = RemoveText( imfEvent.cursorOffset, imfEvent.numberOfChars );
2320
2321       if( update )
2322       {
2323         if( ( 0u != mImpl->mLogicalModel->mText.Count() ) ||
2324             !mImpl->IsPlaceholderAvailable() )
2325         {
2326           mImpl->QueueModifyEvent( ModifyEvent::TEXT_DELETED );
2327         }
2328         else
2329         {
2330           ShowPlaceholderText();
2331           mImpl->mEventData->mUpdateCursorPosition = true;
2332         }
2333       }
2334       requestRelayout = true;
2335       break;
2336     }
2337     case ImfManager::GETSURROUNDING:
2338     {
2339       GetText( text );
2340       cursorPosition = GetLogicalCursorPosition();
2341
2342       imfManager.SetSurroundingText( text );
2343       imfManager.SetCursorPosition( cursorPosition );
2344       break;
2345     }
2346     case ImfManager::VOID:
2347     {
2348       // do nothing
2349       break;
2350     }
2351   } // end switch
2352
2353   if( ImfManager::GETSURROUNDING != imfEvent.eventName )
2354   {
2355     GetText( text );
2356     cursorPosition = GetLogicalCursorPosition();
2357   }
2358
2359   if( requestRelayout )
2360   {
2361     mImpl->mOperationsPending = ALL_OPERATIONS;
2362     mImpl->RequestRelayout();
2363
2364     // Do this last since it provides callbacks into application code
2365     mImpl->mControlInterface.TextChanged();
2366   }
2367
2368   ImfManager::ImfCallbackData callbackData( update, cursorPosition, text, false );
2369
2370   return callbackData;
2371 }
2372
2373 Controller::~Controller()
2374 {
2375   delete mImpl;
2376 }
2377
2378 bool Controller::BackspaceKeyEvent()
2379 {
2380   DALI_LOG_INFO( gLogFilter, Debug::Verbose, "Controller::KeyEvent %p DALI_KEY_BACKSPACE\n", this );
2381
2382   bool removed = false;
2383
2384   if( NULL == mImpl->mEventData )
2385   {
2386     return removed;
2387   }
2388
2389   // IMF manager is no longer handling key-events
2390   mImpl->ClearPreEditFlag();
2391
2392   if( EventData::SELECTING == mImpl->mEventData->mState )
2393   {
2394     removed = RemoveSelectedText();
2395   }
2396   else if( mImpl->mEventData->mPrimaryCursorPosition > 0 )
2397   {
2398     // Remove the character before the current cursor position
2399     removed = RemoveText( -1, 1 );
2400   }
2401
2402   if( removed )
2403   {
2404     DALI_LOG_INFO( gLogFilter, Debug::Verbose, "Controller::KeyEvent %p DALI_KEY_BACKSPACE RemovedText\n", this );
2405     // Notifiy the IMF manager after text changed
2406     // Automatic  Upper-case and restarting prediction on an existing word require this.
2407     NotifyImfManager();
2408
2409     if( ( 0u != mImpl->mLogicalModel->mText.Count() ) ||
2410         !mImpl->IsPlaceholderAvailable() )
2411     {
2412       mImpl->QueueModifyEvent( ModifyEvent::TEXT_DELETED );
2413     }
2414     else
2415     {
2416       ShowPlaceholderText();
2417       mImpl->mEventData->mUpdateCursorPosition = true;
2418     }
2419   }
2420
2421   return removed;
2422 }
2423
2424 void Controller::NotifyImfManager()
2425 {
2426   if( NULL != mImpl->mEventData )
2427   {
2428     if( mImpl->mEventData->mImfManager )
2429     {
2430       // Notifying IMF of a cursor change triggers a surrounding text request so updating it now.
2431       std::string text;
2432       GetText( text );
2433       mImpl->mEventData->mImfManager.SetSurroundingText( text );
2434
2435       mImpl->mEventData->mImfManager.SetCursorPosition( GetLogicalCursorPosition() );
2436       mImpl->mEventData->mImfManager.NotifyCursorPosition();
2437     }
2438   }
2439 }
2440
2441 void Controller::ShowPlaceholderText()
2442 {
2443   if( mImpl->IsPlaceholderAvailable() )
2444   {
2445     DALI_ASSERT_DEBUG( mImpl->mEventData && "No placeholder text available" );
2446
2447     if( NULL == mImpl->mEventData )
2448     {
2449       return;
2450     }
2451
2452     mImpl->mEventData->mIsShowingPlaceholderText = true;
2453
2454     // Disable handles when showing place-holder text
2455     mImpl->mEventData->mDecorator->SetHandleActive( GRAB_HANDLE, false );
2456     mImpl->mEventData->mDecorator->SetHandleActive( LEFT_SELECTION_HANDLE, false );
2457     mImpl->mEventData->mDecorator->SetHandleActive( RIGHT_SELECTION_HANDLE, false );
2458
2459     const char* text( NULL );
2460     size_t size( 0 );
2461
2462     // TODO - Switch placeholder text styles when changing state
2463     if( ( EventData::INACTIVE != mImpl->mEventData->mState ) &&
2464         ( 0u != mImpl->mEventData->mPlaceholderTextActive.c_str() ) )
2465     {
2466       text = mImpl->mEventData->mPlaceholderTextActive.c_str();
2467       size = mImpl->mEventData->mPlaceholderTextActive.size();
2468     }
2469     else
2470     {
2471       text = mImpl->mEventData->mPlaceholderTextInactive.c_str();
2472       size = mImpl->mEventData->mPlaceholderTextInactive.size();
2473     }
2474
2475     // Reset model for showing placeholder.
2476     mImpl->mLogicalModel->mText.Clear();
2477     ClearModelData();
2478     mImpl->mVisualModel->SetTextColor( mImpl->mEventData->mPlaceholderTextColor );
2479
2480     // Convert text into UTF-32
2481     Vector<Character>& utf32Characters = mImpl->mLogicalModel->mText;
2482     utf32Characters.Resize( size );
2483
2484     // This is a bit horrible but std::string returns a (signed) char*
2485     const uint8_t* utf8 = reinterpret_cast<const uint8_t*>( text );
2486
2487     // Transform a text array encoded in utf8 into an array encoded in utf32.
2488     // It returns the actual number of characters.
2489     Length characterCount = Utf8ToUtf32( utf8, size, utf32Characters.Begin() );
2490     utf32Characters.Resize( characterCount );
2491
2492     // Reset the cursor position
2493     mImpl->mEventData->mPrimaryCursorPosition = 0;
2494
2495     // The natural size needs to be re-calculated.
2496     mImpl->mRecalculateNaturalSize = true;
2497
2498     // Apply modifications to the model
2499     mImpl->mOperationsPending = ALL_OPERATIONS;
2500
2501     // Update the rest of the model during size negotiation
2502     mImpl->QueueModifyEvent( ModifyEvent::TEXT_REPLACED );
2503   }
2504 }
2505
2506 void Controller::ClearModelData()
2507 {
2508   // n.b. This does not Clear the mText from mLogicalModel
2509   mImpl->mLogicalModel->mScriptRuns.Clear();
2510   mImpl->mLogicalModel->mFontRuns.Clear();
2511   mImpl->mLogicalModel->mLineBreakInfo.Clear();
2512   mImpl->mLogicalModel->mWordBreakInfo.Clear();
2513   mImpl->mLogicalModel->mBidirectionalParagraphInfo.Clear();
2514   mImpl->mLogicalModel->mCharacterDirections.Clear();
2515   mImpl->mLogicalModel->mBidirectionalLineInfo.Clear();
2516   mImpl->mLogicalModel->mLogicalToVisualMap.Clear();
2517   mImpl->mLogicalModel->mVisualToLogicalMap.Clear();
2518   mImpl->mVisualModel->mGlyphs.Clear();
2519   mImpl->mVisualModel->mGlyphsToCharacters.Clear();
2520   mImpl->mVisualModel->mCharactersToGlyph.Clear();
2521   mImpl->mVisualModel->mCharactersPerGlyph.Clear();
2522   mImpl->mVisualModel->mGlyphsPerCharacter.Clear();
2523   mImpl->mVisualModel->mGlyphPositions.Clear();
2524   mImpl->mVisualModel->mLines.Clear();
2525   mImpl->mVisualModel->mColorRuns.Clear();
2526   mImpl->mVisualModel->ClearCaches();
2527 }
2528
2529 void Controller::ClearFontData()
2530 {
2531   mImpl->mFontDefaults->mFontId = 0u; // Remove old font ID
2532   mImpl->mLogicalModel->mFontRuns.Clear();
2533   mImpl->mVisualModel->mGlyphs.Clear();
2534   mImpl->mVisualModel->mGlyphsToCharacters.Clear();
2535   mImpl->mVisualModel->mCharactersToGlyph.Clear();
2536   mImpl->mVisualModel->mCharactersPerGlyph.Clear();
2537   mImpl->mVisualModel->mGlyphsPerCharacter.Clear();
2538   mImpl->mVisualModel->mGlyphPositions.Clear();
2539   mImpl->mVisualModel->mLines.Clear();
2540   mImpl->mVisualModel->ClearCaches();
2541 }
2542
2543 void Controller::ClearStyleData()
2544 {
2545   mImpl->mLogicalModel->mColorRuns.Clear();
2546   mImpl->mLogicalModel->ClearFontDescriptionRuns();
2547 }
2548
2549 Controller::Controller( ControlInterface& controlInterface )
2550 : mImpl( NULL )
2551 {
2552   mImpl = new Controller::Impl( controlInterface );
2553 }
2554
2555 } // namespace Text
2556
2557 } // namespace Toolkit
2558
2559 } // namespace Dali