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