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