Merge "DALi C# binding - Write pure C# Color & Position classes and use typemaps...
[platform/core/uifw/dali-toolkit.git] / dali-toolkit / internal / text / text-controller.cpp
1 /*
2  * Copyright (c) 2016 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->mIsAutoScrollEnabled = 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->mIsAutoScrollEnabled = false;
186   }
187 }
188
189 bool Controller::IsAutoScrollEnabled() const
190 {
191   DALI_LOG_INFO( gLogFilter, Debug::Verbose, "Controller::IsAutoScrollEnabled[%s]\n", mImpl->mIsAutoScrollEnabled?"true":"false" );
192
193   return mImpl->mIsAutoScrollEnabled;
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::SetUnderlineColor( const Vector4& color )
762 {
763   mImpl->mVisualModel->SetUnderlineColor( color );
764
765   mImpl->RequestRelayout();
766 }
767
768 const Vector4& Controller::GetUnderlineColor() const
769 {
770   return mImpl->mVisualModel->GetUnderlineColor();
771 }
772
773 void Controller::SetUnderlineEnabled( bool enabled )
774 {
775   mImpl->mVisualModel->SetUnderlineEnabled( enabled );
776
777   mImpl->RequestRelayout();
778 }
779
780 bool Controller::IsUnderlineEnabled() const
781 {
782   return mImpl->mVisualModel->IsUnderlineEnabled();
783 }
784
785 void Controller::SetUnderlineHeight( float height )
786 {
787   mImpl->mVisualModel->SetUnderlineHeight( height );
788
789   mImpl->RequestRelayout();
790 }
791
792 float Controller::GetUnderlineHeight() const
793 {
794   return mImpl->mVisualModel->GetUnderlineHeight();
795 }
796
797 void Controller::SetDefaultEmbossProperties( const std::string& embossProperties )
798 {
799   if( NULL == mImpl->mEmbossDefaults )
800   {
801     mImpl->mEmbossDefaults = new EmbossDefaults();
802   }
803
804   mImpl->mEmbossDefaults->properties = embossProperties;
805 }
806
807 const std::string& Controller::GetDefaultEmbossProperties() const
808 {
809   if( NULL != mImpl->mEmbossDefaults )
810   {
811     return mImpl->mEmbossDefaults->properties;
812   }
813
814   return EMPTY_STRING;
815 }
816
817 void Controller::SetDefaultOutlineProperties( const std::string& outlineProperties )
818 {
819   if( NULL == mImpl->mOutlineDefaults )
820   {
821     mImpl->mOutlineDefaults = new OutlineDefaults();
822   }
823
824   mImpl->mOutlineDefaults->properties = outlineProperties;
825 }
826
827 const std::string& Controller::GetDefaultOutlineProperties() const
828 {
829   if( NULL != mImpl->mOutlineDefaults )
830   {
831     return mImpl->mOutlineDefaults->properties;
832   }
833
834   return EMPTY_STRING;
835 }
836
837 void Controller::SetDefaultLineSpacing( float lineSpacing )
838 {
839   //TODO finish implementation
840   mImpl->mLayoutEngine.SetDefaultLineSpacing( lineSpacing );
841 }
842
843 float Controller::GetDefaultLineSpacing() const
844 {
845   return mImpl->mLayoutEngine.GetDefaultLineSpacing();
846 }
847
848 void Controller::SetInputColor( const Vector4& color )
849 {
850   if( NULL != mImpl->mEventData )
851   {
852     mImpl->mEventData->mInputStyle.textColor = color;
853     mImpl->mEventData->mInputStyle.isDefaultColor = false;
854
855     if( EventData::SELECTING == mImpl->mEventData->mState )
856     {
857       const bool handlesCrossed = mImpl->mEventData->mLeftSelectionPosition > mImpl->mEventData->mRightSelectionPosition;
858
859       // Get start and end position of selection
860       const CharacterIndex startOfSelectedText = handlesCrossed ? mImpl->mEventData->mRightSelectionPosition : mImpl->mEventData->mLeftSelectionPosition;
861       const Length lengthOfSelectedText = ( handlesCrossed ? mImpl->mEventData->mLeftSelectionPosition : mImpl->mEventData->mRightSelectionPosition ) - startOfSelectedText;
862
863       // Add the color run.
864       const VectorBase::SizeType numberOfRuns = mImpl->mLogicalModel->mColorRuns.Count();
865       mImpl->mLogicalModel->mColorRuns.Resize( numberOfRuns + 1u );
866
867       ColorRun& colorRun = *( mImpl->mLogicalModel->mColorRuns.Begin() + numberOfRuns );
868       colorRun.color = color;
869       colorRun.characterRun.characterIndex = startOfSelectedText;
870       colorRun.characterRun.numberOfCharacters = lengthOfSelectedText;
871
872       // Request to relayout.
873       mImpl->mOperationsPending = static_cast<OperationsMask>( mImpl->mOperationsPending | COLOR );
874       mImpl->RequestRelayout();
875
876       mImpl->mTextUpdateInfo.mCharacterIndex = startOfSelectedText;
877       mImpl->mTextUpdateInfo.mNumberOfCharactersToRemove = lengthOfSelectedText;
878       mImpl->mTextUpdateInfo.mNumberOfCharactersToAdd = lengthOfSelectedText;
879     }
880   }
881 }
882
883 const Vector4& Controller::GetInputColor() const
884 {
885   if( NULL != mImpl->mEventData )
886   {
887     return mImpl->mEventData->mInputStyle.textColor;
888   }
889
890   // Return the default text's color if there is no EventData.
891   return mImpl->mTextColor;
892
893 }
894
895 void Controller::SetInputFontFamily( const std::string& fontFamily )
896 {
897   if( NULL != mImpl->mEventData )
898   {
899     mImpl->mEventData->mInputStyle.familyName = fontFamily;
900     mImpl->mEventData->mInputStyle.isFamilyDefined = true;
901
902     if( EventData::SELECTING == mImpl->mEventData->mState )
903     {
904       CharacterIndex startOfSelectedText = 0u;
905       Length lengthOfSelectedText = 0u;
906       FontDescriptionRun& fontDescriptionRun = UpdateSelectionFontStyleRun( mImpl->mEventData,
907                                                                             mImpl->mLogicalModel,
908                                                                             startOfSelectedText,
909                                                                             lengthOfSelectedText );
910
911       fontDescriptionRun.familyLength = fontFamily.size();
912       fontDescriptionRun.familyName = new char[fontDescriptionRun.familyLength];
913       memcpy( fontDescriptionRun.familyName, fontFamily.c_str(), fontDescriptionRun.familyLength );
914       fontDescriptionRun.familyDefined = true;
915
916       // The memory allocated for the font family name is freed when the font description is removed from the logical model.
917
918       // Request to relayout.
919       mImpl->mOperationsPending = static_cast<OperationsMask>( mImpl->mOperationsPending |
920                                                                VALIDATE_FONTS            |
921                                                                SHAPE_TEXT                |
922                                                                GET_GLYPH_METRICS         |
923                                                                LAYOUT                    |
924                                                                UPDATE_LAYOUT_SIZE        |
925                                                                REORDER                   |
926                                                                ALIGN );
927       mImpl->mRecalculateNaturalSize = true;
928       mImpl->RequestRelayout();
929
930       mImpl->mTextUpdateInfo.mCharacterIndex = startOfSelectedText;
931       mImpl->mTextUpdateInfo.mNumberOfCharactersToRemove = lengthOfSelectedText;
932       mImpl->mTextUpdateInfo.mNumberOfCharactersToAdd = lengthOfSelectedText;
933
934       // As the font changes, recalculate the handle positions is needed.
935       mImpl->mEventData->mUpdateLeftSelectionPosition = true;
936       mImpl->mEventData->mUpdateRightSelectionPosition = true;
937       mImpl->mEventData->mUpdateHighlightBox = true;
938       mImpl->mEventData->mScrollAfterUpdatePosition = true;
939     }
940   }
941 }
942
943 const std::string& Controller::GetInputFontFamily() const
944 {
945   if( NULL != mImpl->mEventData )
946   {
947     return mImpl->mEventData->mInputStyle.familyName;
948   }
949
950   // Return the default font's family if there is no EventData.
951   return GetDefaultFontFamily();
952 }
953
954 void Controller::SetInputFontWeight( FontWeight weight )
955 {
956   if( NULL != mImpl->mEventData )
957   {
958     mImpl->mEventData->mInputStyle.weight = weight;
959     mImpl->mEventData->mInputStyle.isWeightDefined = true;
960
961     if( EventData::SELECTING == mImpl->mEventData->mState )
962     {
963       CharacterIndex startOfSelectedText = 0u;
964       Length lengthOfSelectedText = 0u;
965       FontDescriptionRun& fontDescriptionRun = UpdateSelectionFontStyleRun( mImpl->mEventData,
966                                                                             mImpl->mLogicalModel,
967                                                                             startOfSelectedText,
968                                                                             lengthOfSelectedText );
969
970       fontDescriptionRun.weight = weight;
971       fontDescriptionRun.weightDefined = true;
972
973       // Request to relayout.
974       mImpl->mOperationsPending = static_cast<OperationsMask>( mImpl->mOperationsPending |
975                                                                VALIDATE_FONTS            |
976                                                                SHAPE_TEXT                |
977                                                                GET_GLYPH_METRICS         |
978                                                                LAYOUT                    |
979                                                                UPDATE_LAYOUT_SIZE        |
980                                                                REORDER                   |
981                                                                ALIGN );
982       mImpl->mRecalculateNaturalSize = true;
983       mImpl->RequestRelayout();
984
985       mImpl->mTextUpdateInfo.mCharacterIndex = startOfSelectedText;
986       mImpl->mTextUpdateInfo.mNumberOfCharactersToRemove = lengthOfSelectedText;
987       mImpl->mTextUpdateInfo.mNumberOfCharactersToAdd = lengthOfSelectedText;
988
989       // As the font might change, recalculate the handle positions is needed.
990       mImpl->mEventData->mUpdateLeftSelectionPosition = true;
991       mImpl->mEventData->mUpdateRightSelectionPosition = true;
992       mImpl->mEventData->mUpdateHighlightBox = true;
993       mImpl->mEventData->mScrollAfterUpdatePosition = true;
994     }
995   }
996 }
997
998 bool Controller::IsInputFontWeightDefined() const
999 {
1000   bool defined = false;
1001
1002   if( NULL != mImpl->mEventData )
1003   {
1004     defined = mImpl->mEventData->mInputStyle.isWeightDefined;
1005   }
1006
1007   return defined;
1008 }
1009
1010 FontWeight Controller::GetInputFontWeight() const
1011 {
1012   if( NULL != mImpl->mEventData )
1013   {
1014     return mImpl->mEventData->mInputStyle.weight;
1015   }
1016
1017   return GetDefaultFontWeight();
1018 }
1019
1020 void Controller::SetInputFontWidth( FontWidth width )
1021 {
1022   if( NULL != mImpl->mEventData )
1023   {
1024     mImpl->mEventData->mInputStyle.width = width;
1025     mImpl->mEventData->mInputStyle.isWidthDefined = true;
1026
1027     if( EventData::SELECTING == mImpl->mEventData->mState )
1028     {
1029       CharacterIndex startOfSelectedText = 0u;
1030       Length lengthOfSelectedText = 0u;
1031       FontDescriptionRun& fontDescriptionRun = UpdateSelectionFontStyleRun( mImpl->mEventData,
1032                                                                             mImpl->mLogicalModel,
1033                                                                             startOfSelectedText,
1034                                                                             lengthOfSelectedText );
1035
1036       fontDescriptionRun.width = width;
1037       fontDescriptionRun.widthDefined = true;
1038
1039       // Request to relayout.
1040       mImpl->mOperationsPending = static_cast<OperationsMask>( mImpl->mOperationsPending |
1041                                                                VALIDATE_FONTS            |
1042                                                                SHAPE_TEXT                |
1043                                                                GET_GLYPH_METRICS         |
1044                                                                LAYOUT                    |
1045                                                                UPDATE_LAYOUT_SIZE        |
1046                                                                REORDER                   |
1047                                                                ALIGN );
1048       mImpl->mRecalculateNaturalSize = true;
1049       mImpl->RequestRelayout();
1050
1051       mImpl->mTextUpdateInfo.mCharacterIndex = startOfSelectedText;
1052       mImpl->mTextUpdateInfo.mNumberOfCharactersToRemove = lengthOfSelectedText;
1053       mImpl->mTextUpdateInfo.mNumberOfCharactersToAdd = lengthOfSelectedText;
1054
1055       // As the font might change, recalculate the handle positions is needed.
1056       mImpl->mEventData->mUpdateLeftSelectionPosition = true;
1057       mImpl->mEventData->mUpdateRightSelectionPosition = true;
1058       mImpl->mEventData->mUpdateHighlightBox = true;
1059       mImpl->mEventData->mScrollAfterUpdatePosition = true;
1060     }
1061   }
1062 }
1063
1064 bool Controller::IsInputFontWidthDefined() const
1065 {
1066   bool defined = false;
1067
1068   if( NULL != mImpl->mEventData )
1069   {
1070     defined = mImpl->mEventData->mInputStyle.isWidthDefined;
1071   }
1072
1073   return defined;
1074 }
1075
1076 FontWidth Controller::GetInputFontWidth() const
1077 {
1078   if( NULL != mImpl->mEventData )
1079   {
1080     return mImpl->mEventData->mInputStyle.width;
1081   }
1082
1083   return GetDefaultFontWidth();
1084 }
1085
1086 void Controller::SetInputFontSlant( FontSlant slant )
1087 {
1088   if( NULL != mImpl->mEventData )
1089   {
1090     mImpl->mEventData->mInputStyle.slant = slant;
1091     mImpl->mEventData->mInputStyle.isSlantDefined = true;
1092
1093     if( EventData::SELECTING == mImpl->mEventData->mState )
1094     {
1095       CharacterIndex startOfSelectedText = 0u;
1096       Length lengthOfSelectedText = 0u;
1097       FontDescriptionRun& fontDescriptionRun = UpdateSelectionFontStyleRun( mImpl->mEventData,
1098                                                                             mImpl->mLogicalModel,
1099                                                                             startOfSelectedText,
1100                                                                             lengthOfSelectedText );
1101
1102       fontDescriptionRun.slant = slant;
1103       fontDescriptionRun.slantDefined = true;
1104
1105       // Request to relayout.
1106       mImpl->mOperationsPending = static_cast<OperationsMask>( mImpl->mOperationsPending |
1107                                                                VALIDATE_FONTS            |
1108                                                                SHAPE_TEXT                |
1109                                                                GET_GLYPH_METRICS         |
1110                                                                LAYOUT                    |
1111                                                                UPDATE_LAYOUT_SIZE        |
1112                                                                REORDER                   |
1113                                                                ALIGN );
1114       mImpl->mRecalculateNaturalSize = true;
1115       mImpl->RequestRelayout();
1116
1117       mImpl->mTextUpdateInfo.mCharacterIndex = startOfSelectedText;
1118       mImpl->mTextUpdateInfo.mNumberOfCharactersToRemove = lengthOfSelectedText;
1119       mImpl->mTextUpdateInfo.mNumberOfCharactersToAdd = lengthOfSelectedText;
1120
1121       // As the font might change, recalculate the handle positions is needed.
1122       mImpl->mEventData->mUpdateLeftSelectionPosition = true;
1123       mImpl->mEventData->mUpdateRightSelectionPosition = true;
1124       mImpl->mEventData->mUpdateHighlightBox = true;
1125       mImpl->mEventData->mScrollAfterUpdatePosition = true;
1126     }
1127   }
1128 }
1129
1130 bool Controller::IsInputFontSlantDefined() const
1131 {
1132   bool defined = false;
1133
1134   if( NULL != mImpl->mEventData )
1135   {
1136     defined = mImpl->mEventData->mInputStyle.isSlantDefined;
1137   }
1138
1139   return defined;
1140 }
1141
1142 FontSlant Controller::GetInputFontSlant() const
1143 {
1144   if( NULL != mImpl->mEventData )
1145   {
1146     return mImpl->mEventData->mInputStyle.slant;
1147   }
1148
1149   return GetDefaultFontSlant();
1150 }
1151
1152 void Controller::SetInputFontPointSize( float size )
1153 {
1154   if( NULL != mImpl->mEventData )
1155   {
1156     mImpl->mEventData->mInputStyle.size = size;
1157     mImpl->mEventData->mInputStyle.isSizeDefined = true;
1158
1159     if( EventData::SELECTING == mImpl->mEventData->mState )
1160     {
1161       CharacterIndex startOfSelectedText = 0u;
1162       Length lengthOfSelectedText = 0u;
1163       FontDescriptionRun& fontDescriptionRun = UpdateSelectionFontStyleRun( mImpl->mEventData,
1164                                                                             mImpl->mLogicalModel,
1165                                                                             startOfSelectedText,
1166                                                                             lengthOfSelectedText );
1167
1168       fontDescriptionRun.size = static_cast<PointSize26Dot6>( size * 64.f );
1169       fontDescriptionRun.sizeDefined = true;
1170
1171       // Request to relayout.
1172       mImpl->mOperationsPending = static_cast<OperationsMask>( mImpl->mOperationsPending |
1173                                                                VALIDATE_FONTS            |
1174                                                                SHAPE_TEXT                |
1175                                                                GET_GLYPH_METRICS         |
1176                                                                LAYOUT                    |
1177                                                                UPDATE_LAYOUT_SIZE        |
1178                                                                REORDER                   |
1179                                                                ALIGN );
1180       mImpl->mRecalculateNaturalSize = true;
1181       mImpl->RequestRelayout();
1182
1183       mImpl->mTextUpdateInfo.mCharacterIndex = startOfSelectedText;
1184       mImpl->mTextUpdateInfo.mNumberOfCharactersToRemove = lengthOfSelectedText;
1185       mImpl->mTextUpdateInfo.mNumberOfCharactersToAdd = lengthOfSelectedText;
1186
1187       // As the font might change, recalculate the handle positions is needed.
1188       mImpl->mEventData->mUpdateLeftSelectionPosition = true;
1189       mImpl->mEventData->mUpdateRightSelectionPosition = true;
1190       mImpl->mEventData->mUpdateHighlightBox = true;
1191       mImpl->mEventData->mScrollAfterUpdatePosition = true;
1192     }
1193   }
1194 }
1195
1196 float Controller::GetInputFontPointSize() const
1197 {
1198   if( NULL != mImpl->mEventData )
1199   {
1200     return mImpl->mEventData->mInputStyle.size;
1201   }
1202
1203   // Return the default font's point size if there is no EventData.
1204   return GetDefaultPointSize();
1205 }
1206
1207 void Controller::SetInputLineSpacing( float lineSpacing )
1208 {
1209   if( NULL != mImpl->mEventData )
1210   {
1211     mImpl->mEventData->mInputStyle.lineSpacing = lineSpacing;
1212     mImpl->mEventData->mInputStyle.isLineSpacingDefined = true;
1213   }
1214 }
1215
1216 float Controller::GetInputLineSpacing() const
1217 {
1218   if( NULL != mImpl->mEventData )
1219   {
1220     return mImpl->mEventData->mInputStyle.lineSpacing;
1221   }
1222
1223   return 0.f;
1224 }
1225
1226 void Controller::SetInputShadowProperties( const std::string& shadowProperties )
1227 {
1228   if( NULL != mImpl->mEventData )
1229   {
1230     mImpl->mEventData->mInputStyle.shadowProperties = shadowProperties;
1231   }
1232 }
1233
1234 const std::string& Controller::GetInputShadowProperties() const
1235 {
1236   if( NULL != mImpl->mEventData )
1237   {
1238     return mImpl->mEventData->mInputStyle.shadowProperties;
1239   }
1240
1241   return EMPTY_STRING;
1242 }
1243
1244 void Controller::SetInputUnderlineProperties( const std::string& underlineProperties )
1245 {
1246   if( NULL != mImpl->mEventData )
1247   {
1248     mImpl->mEventData->mInputStyle.underlineProperties = underlineProperties;
1249   }
1250 }
1251
1252 const std::string& Controller::GetInputUnderlineProperties() const
1253 {
1254   if( NULL != mImpl->mEventData )
1255   {
1256     return mImpl->mEventData->mInputStyle.underlineProperties;
1257   }
1258
1259   return EMPTY_STRING;
1260 }
1261
1262 void Controller::SetInputEmbossProperties( const std::string& embossProperties )
1263 {
1264   if( NULL != mImpl->mEventData )
1265   {
1266     mImpl->mEventData->mInputStyle.embossProperties = embossProperties;
1267   }
1268 }
1269
1270 const std::string& Controller::GetInputEmbossProperties() const
1271 {
1272   if( NULL != mImpl->mEventData )
1273   {
1274     return mImpl->mEventData->mInputStyle.embossProperties;
1275   }
1276
1277   return GetDefaultEmbossProperties();
1278 }
1279
1280 void Controller::SetInputOutlineProperties( const std::string& outlineProperties )
1281 {
1282   if( NULL != mImpl->mEventData )
1283   {
1284     mImpl->mEventData->mInputStyle.outlineProperties = outlineProperties;
1285   }
1286 }
1287
1288 const std::string& Controller::GetInputOutlineProperties() const
1289 {
1290   if( NULL != mImpl->mEventData )
1291   {
1292     return mImpl->mEventData->mInputStyle.outlineProperties;
1293   }
1294
1295   return GetDefaultOutlineProperties();
1296 }
1297
1298 // public : Queries & retrieves.
1299
1300 LayoutEngine& Controller::GetLayoutEngine()
1301 {
1302   return mImpl->mLayoutEngine;
1303 }
1304
1305 View& Controller::GetView()
1306 {
1307   return mImpl->mView;
1308 }
1309
1310 const Vector2& Controller::GetScrollPosition() const
1311 {
1312   return mImpl->mScrollPosition;
1313 }
1314
1315 Vector3 Controller::GetNaturalSize()
1316 {
1317   DALI_LOG_INFO( gLogFilter, Debug::Verbose, "-->Controller::GetNaturalSize\n" );
1318   Vector3 naturalSize;
1319
1320   // Make sure the model is up-to-date before layouting
1321   ProcessModifyEvents();
1322
1323   if( mImpl->mRecalculateNaturalSize )
1324   {
1325     // Operations that can be done only once until the text changes.
1326     const OperationsMask onlyOnceOperations = static_cast<OperationsMask>( CONVERT_TO_UTF32  |
1327                                                                            GET_SCRIPTS       |
1328                                                                            VALIDATE_FONTS    |
1329                                                                            GET_LINE_BREAKS   |
1330                                                                            GET_WORD_BREAKS   |
1331                                                                            BIDI_INFO         |
1332                                                                            SHAPE_TEXT        |
1333                                                                            GET_GLYPH_METRICS );
1334     // Make sure the model is up-to-date before layouting
1335     mImpl->UpdateModel( onlyOnceOperations );
1336
1337     // Layout the text for the new width.
1338     mImpl->mOperationsPending = static_cast<OperationsMask>( mImpl->mOperationsPending | LAYOUT );
1339
1340     // Set the update info to relayout the whole text.
1341     mImpl->mTextUpdateInfo.mParagraphCharacterIndex = 0u;
1342     mImpl->mTextUpdateInfo.mRequestedNumberOfCharacters = mImpl->mLogicalModel->mText.Count();
1343
1344     // Store the actual control's size to restore later.
1345     const Size actualControlSize = mImpl->mVisualModel->mControlSize;
1346
1347     DoRelayout( Size( MAX_FLOAT, MAX_FLOAT ),
1348                 static_cast<OperationsMask>( onlyOnceOperations |
1349                                              LAYOUT ),
1350                 naturalSize.GetVectorXY() );
1351
1352     // Do not do again the only once operations.
1353     mImpl->mOperationsPending = static_cast<OperationsMask>( mImpl->mOperationsPending & ~onlyOnceOperations );
1354
1355     // Do the size related operations again.
1356     const OperationsMask sizeOperations =  static_cast<OperationsMask>( LAYOUT |
1357                                                                         ALIGN  |
1358                                                                         REORDER );
1359     mImpl->mOperationsPending = static_cast<OperationsMask>( mImpl->mOperationsPending | sizeOperations );
1360
1361     // Stores the natural size to avoid recalculate it again
1362     // unless the text/style changes.
1363     mImpl->mVisualModel->SetNaturalSize( naturalSize.GetVectorXY() );
1364
1365     mImpl->mRecalculateNaturalSize = false;
1366
1367     // Clear the update info. This info will be set the next time the text is updated.
1368     mImpl->mTextUpdateInfo.Clear();
1369
1370     // Restore the actual control's size.
1371     mImpl->mVisualModel->mControlSize = actualControlSize;
1372
1373     DALI_LOG_INFO( gLogFilter, Debug::Verbose, "<--Controller::GetNaturalSize calculated %f,%f,%f\n", naturalSize.x, naturalSize.y, naturalSize.z );
1374   }
1375   else
1376   {
1377     naturalSize = mImpl->mVisualModel->GetNaturalSize();
1378
1379     DALI_LOG_INFO( gLogFilter, Debug::Verbose, "<--Controller::GetNaturalSize cached %f,%f,%f\n", naturalSize.x, naturalSize.y, naturalSize.z );
1380   }
1381
1382   naturalSize.x = ConvertToEven( naturalSize.x );
1383   naturalSize.y = ConvertToEven( naturalSize.y );
1384
1385   return naturalSize;
1386 }
1387
1388 float Controller::GetHeightForWidth( float width )
1389 {
1390   DALI_LOG_INFO( gLogFilter, Debug::Verbose, "-->Controller::GetHeightForWidth %p width %f\n", this, width );
1391   // Make sure the model is up-to-date before layouting
1392   ProcessModifyEvents();
1393
1394   Size layoutSize;
1395   if( fabsf( width - mImpl->mVisualModel->mControlSize.width ) > Math::MACHINE_EPSILON_1000 )
1396   {
1397     // Operations that can be done only once until the text changes.
1398     const OperationsMask onlyOnceOperations = static_cast<OperationsMask>( CONVERT_TO_UTF32  |
1399                                                                            GET_SCRIPTS       |
1400                                                                            VALIDATE_FONTS    |
1401                                                                            GET_LINE_BREAKS   |
1402                                                                            GET_WORD_BREAKS   |
1403                                                                            BIDI_INFO         |
1404                                                                            SHAPE_TEXT        |
1405                                                                            GET_GLYPH_METRICS );
1406     // Make sure the model is up-to-date before layouting
1407     mImpl->UpdateModel( onlyOnceOperations );
1408
1409
1410     // Layout the text for the new width.
1411     mImpl->mOperationsPending = static_cast<OperationsMask>( mImpl->mOperationsPending | LAYOUT );
1412
1413     // Set the update info to relayout the whole text.
1414     mImpl->mTextUpdateInfo.mParagraphCharacterIndex = 0u;
1415     mImpl->mTextUpdateInfo.mRequestedNumberOfCharacters = mImpl->mLogicalModel->mText.Count();
1416
1417     // Store the actual control's width.
1418     const float actualControlWidth = mImpl->mVisualModel->mControlSize.width;
1419
1420     DoRelayout( Size( width, MAX_FLOAT ),
1421                 static_cast<OperationsMask>( onlyOnceOperations |
1422                                              LAYOUT ),
1423                 layoutSize );
1424
1425     // Do not do again the only once operations.
1426     mImpl->mOperationsPending = static_cast<OperationsMask>( mImpl->mOperationsPending & ~onlyOnceOperations );
1427
1428     // Do the size related operations again.
1429     const OperationsMask sizeOperations =  static_cast<OperationsMask>( LAYOUT |
1430                                                                         ALIGN  |
1431                                                                         REORDER );
1432
1433     mImpl->mOperationsPending = static_cast<OperationsMask>( mImpl->mOperationsPending | sizeOperations );
1434
1435     // Clear the update info. This info will be set the next time the text is updated.
1436     mImpl->mTextUpdateInfo.Clear();
1437
1438     // Restore the actual control's width.
1439     mImpl->mVisualModel->mControlSize.width = actualControlWidth;
1440
1441     DALI_LOG_INFO( gLogFilter, Debug::Verbose, "<--Controller::GetHeightForWidth calculated %f\n", layoutSize.height );
1442   }
1443   else
1444   {
1445     layoutSize = mImpl->mVisualModel->GetLayoutSize();
1446     DALI_LOG_INFO( gLogFilter, Debug::Verbose, "<--Controller::GetHeightForWidth cached %f\n", layoutSize.height );
1447   }
1448
1449   return layoutSize.height;
1450 }
1451
1452 // public : Relayout.
1453
1454 Controller::UpdateTextType Controller::Relayout( const Size& size )
1455 {
1456   DALI_LOG_INFO( gLogFilter, Debug::Verbose, "-->Controller::Relayout %p size %f,%f, autoScroll[%s]\n", this, size.width, size.height, mImpl->mIsAutoScrollEnabled ?"true":"false"  );
1457
1458   UpdateTextType updateTextType = NONE_UPDATED;
1459
1460   if( ( size.width < Math::MACHINE_EPSILON_1000 ) || ( size.height < Math::MACHINE_EPSILON_1000 ) )
1461   {
1462     if( 0u != mImpl->mVisualModel->mGlyphPositions.Count() )
1463     {
1464       mImpl->mVisualModel->mGlyphPositions.Clear();
1465       updateTextType = MODEL_UPDATED;
1466     }
1467
1468     // Clear the update info. This info will be set the next time the text is updated.
1469     mImpl->mTextUpdateInfo.Clear();
1470
1471     // Not worth to relayout if width or height is equal to zero.
1472     DALI_LOG_INFO( gLogFilter, Debug::Verbose, "<--Controller::Relayout (skipped)\n" );
1473
1474     return updateTextType;
1475   }
1476
1477   // Whether a new size has been set.
1478   const bool newSize = ( size != mImpl->mVisualModel->mControlSize );
1479
1480   if( newSize )
1481   {
1482     DALI_LOG_INFO( gLogFilter, Debug::Verbose, "new size (previous size %f,%f)\n", mImpl->mVisualModel->mControlSize.width, mImpl->mVisualModel->mControlSize.height );
1483
1484     // Layout operations that need to be done if the size changes.
1485     mImpl->mOperationsPending = static_cast<OperationsMask>( mImpl->mOperationsPending |
1486                                                              LAYOUT                    |
1487                                                              ALIGN                     |
1488                                                              UPDATE_LAYOUT_SIZE        |
1489                                                              REORDER );
1490     // Set the update info to relayout the whole text.
1491     mImpl->mTextUpdateInfo.mFullRelayoutNeeded = true;
1492     mImpl->mTextUpdateInfo.mCharacterIndex = 0u;
1493   }
1494
1495   // Whether there are modify events.
1496   if( 0u != mImpl->mModifyEvents.Count() )
1497   {
1498     // Style operations that need to be done if the text is modified.
1499     mImpl->mOperationsPending = static_cast<OperationsMask>( mImpl->mOperationsPending |
1500                                                              COLOR );
1501   }
1502
1503   // Make sure the model is up-to-date before layouting.
1504   ProcessModifyEvents();
1505   bool updated = mImpl->UpdateModel( mImpl->mOperationsPending );
1506
1507   // Layout the text.
1508   Size layoutSize;
1509   updated = DoRelayout( size,
1510                         mImpl->mOperationsPending,
1511                         layoutSize ) || updated;
1512
1513   if( updated )
1514   {
1515     updateTextType = MODEL_UPDATED;
1516   }
1517
1518   // Do not re-do any operation until something changes.
1519   mImpl->mOperationsPending = NO_OPERATION;
1520
1521   // Whether the text control is editable
1522   const bool isEditable = NULL != mImpl->mEventData;
1523
1524   // Keep the current offset as it will be used to update the decorator's positions (if the size changes).
1525   Vector2 offset;
1526   if( newSize && isEditable )
1527   {
1528     offset = mImpl->mScrollPosition;
1529   }
1530
1531   if( !isEditable || !IsMultiLineEnabled() )
1532   {
1533     // After doing the text layout, the vertical offset to place the actor in the desired position can be calculated.
1534     CalculateVerticalOffset( size );
1535   }
1536
1537   if( isEditable )
1538   {
1539     if( newSize )
1540     {
1541       // If there is a new size, the scroll position needs to be clamped.
1542       mImpl->ClampHorizontalScroll( layoutSize );
1543
1544       // Update the decorator's positions is needed if there is a new size.
1545       mImpl->mEventData->mDecorator->UpdatePositions( mImpl->mScrollPosition - offset );
1546     }
1547
1548     // Move the cursor, grab handle etc.
1549     if( mImpl->ProcessInputEvents() )
1550     {
1551       updateTextType = static_cast<UpdateTextType>( updateTextType | DECORATOR_UPDATED );
1552     }
1553   }
1554
1555   // Clear the update info. This info will be set the next time the text is updated.
1556   mImpl->mTextUpdateInfo.Clear();
1557   DALI_LOG_INFO( gLogFilter, Debug::Verbose, "<--Controller::Relayout\n" );
1558
1559   return updateTextType;
1560 }
1561
1562 void Controller::RequestRelayout()
1563 {
1564   mImpl->RequestRelayout();
1565 }
1566
1567 // public : Input style change signals.
1568
1569 bool Controller::IsInputStyleChangedSignalsQueueEmpty()
1570 {
1571   return ( NULL == mImpl->mEventData ) || ( 0u == mImpl->mEventData->mInputStyleChangedQueue.Count() );
1572 }
1573
1574 void Controller::ProcessInputStyleChangedSignals()
1575 {
1576   if( NULL == mImpl->mEventData )
1577   {
1578     // Nothing to do.
1579     return;
1580   }
1581
1582   for( Vector<InputStyle::Mask>::ConstIterator it = mImpl->mEventData->mInputStyleChangedQueue.Begin(),
1583          endIt = mImpl->mEventData->mInputStyleChangedQueue.End();
1584        it != endIt;
1585        ++it )
1586   {
1587     const InputStyle::Mask mask = *it;
1588
1589     if( NULL != mImpl->mEditableControlInterface )
1590     {
1591       // Emit the input style changed signal.
1592       mImpl->mEditableControlInterface->InputStyleChanged( mask );
1593     }
1594   }
1595
1596   mImpl->mEventData->mInputStyleChangedQueue.Clear();
1597 }
1598
1599 // public : Text-input Event Queuing.
1600
1601 void Controller::KeyboardFocusGainEvent()
1602 {
1603   DALI_ASSERT_DEBUG( mImpl->mEventData && "Unexpected KeyboardFocusGainEvent" );
1604
1605   if( NULL != mImpl->mEventData )
1606   {
1607     if( ( EventData::INACTIVE == mImpl->mEventData->mState ) ||
1608         ( EventData::INTERRUPTED == mImpl->mEventData->mState ) )
1609     {
1610       mImpl->ChangeState( EventData::EDITING );
1611       mImpl->mEventData->mUpdateCursorPosition = true; //If editing started without tap event, cursor update must be triggered.
1612       mImpl->mEventData->mUpdateInputStyle = true;
1613     }
1614     mImpl->NotifyImfMultiLineStatus();
1615     if( mImpl->IsShowingPlaceholderText() )
1616     {
1617       // Show alternative placeholder-text when editing
1618       ShowPlaceholderText();
1619     }
1620
1621     mImpl->RequestRelayout();
1622   }
1623 }
1624
1625 void Controller::KeyboardFocusLostEvent()
1626 {
1627   DALI_ASSERT_DEBUG( mImpl->mEventData && "Unexpected KeyboardFocusLostEvent" );
1628
1629   if( NULL != mImpl->mEventData )
1630   {
1631     if( EventData::INTERRUPTED != mImpl->mEventData->mState )
1632     {
1633       mImpl->ChangeState( EventData::INACTIVE );
1634
1635       if( !mImpl->IsShowingRealText() )
1636       {
1637         // Revert to regular placeholder-text when not editing
1638         ShowPlaceholderText();
1639       }
1640     }
1641   }
1642   mImpl->RequestRelayout();
1643 }
1644
1645 bool Controller::KeyEvent( const Dali::KeyEvent& keyEvent )
1646 {
1647   DALI_ASSERT_DEBUG( mImpl->mEventData && "Unexpected KeyEvent" );
1648
1649   bool textChanged( false );
1650
1651   if( ( NULL != mImpl->mEventData ) &&
1652       ( keyEvent.state == KeyEvent::Down ) )
1653   {
1654     int keyCode = keyEvent.keyCode;
1655     const std::string& keyString = keyEvent.keyPressed;
1656
1657     // Pre-process to separate modifying events from non-modifying input events.
1658     if( Dali::DALI_KEY_ESCAPE == keyCode )
1659     {
1660       // Escape key is a special case which causes focus loss
1661       KeyboardFocusLostEvent();
1662     }
1663     else if( ( Dali::DALI_KEY_CURSOR_LEFT  == keyCode ) ||
1664              ( Dali::DALI_KEY_CURSOR_RIGHT == keyCode ) ||
1665              ( Dali::DALI_KEY_CURSOR_UP    == keyCode ) ||
1666              ( Dali::DALI_KEY_CURSOR_DOWN  == keyCode ) )
1667     {
1668       Event event( Event::CURSOR_KEY_EVENT );
1669       event.p1.mInt = keyCode;
1670       mImpl->mEventData->mEventQueue.push_back( event );
1671     }
1672     else if( Dali::DALI_KEY_BACKSPACE == keyCode )
1673     {
1674       textChanged = BackspaceKeyEvent();
1675     }
1676     else if( IsKey( keyEvent,  Dali::DALI_KEY_POWER ) )
1677     {
1678       mImpl->ChangeState( EventData::INTERRUPTED ); // State is not INACTIVE as expect to return to edit mode.
1679       // Avoids calling the InsertText() method which can delete selected text
1680     }
1681     else if( IsKey( keyEvent, Dali::DALI_KEY_MENU ) ||
1682              IsKey( keyEvent, Dali::DALI_KEY_HOME ) )
1683     {
1684       mImpl->ChangeState( EventData::INACTIVE );
1685       // Menu/Home key behaviour does not allow edit mode to resume like Power key
1686       // Avoids calling the InsertText() method which can delete selected text
1687     }
1688     else if( Dali::DALI_KEY_SHIFT_LEFT == keyCode )
1689     {
1690       // DALI_KEY_SHIFT_LEFT is the key code for the Left Shift. It's sent (by the imf?) when the predictive text is enabled
1691       // and a character is typed after the type of a upper case latin character.
1692
1693       // Do nothing.
1694     }
1695     else
1696     {
1697       DALI_LOG_INFO( gLogFilter, Debug::Verbose, "Controller::KeyEvent %p keyString %s\n", this, keyString.c_str() );
1698
1699       // IMF manager is no longer handling key-events
1700       mImpl->ClearPreEditFlag();
1701
1702       InsertText( keyString, COMMIT );
1703       textChanged = true;
1704     }
1705
1706     if ( ( mImpl->mEventData->mState != EventData::INTERRUPTED ) &&
1707          ( mImpl->mEventData->mState != EventData::INACTIVE ) &&
1708          ( Dali::DALI_KEY_SHIFT_LEFT != keyCode ) )
1709     {
1710       // Should not change the state if the key is the shift send by the imf manager.
1711       // Otherwise, when the state is SELECTING the text controller can't send the right
1712       // surrounding info to the imf.
1713       mImpl->ChangeState( EventData::EDITING );
1714     }
1715
1716     mImpl->RequestRelayout();
1717   }
1718
1719   if( textChanged &&
1720       ( NULL != mImpl->mEditableControlInterface ) )
1721   {
1722     // Do this last since it provides callbacks into application code
1723     mImpl->mEditableControlInterface->TextChanged();
1724   }
1725
1726   return true;
1727 }
1728
1729 void Controller::TapEvent( unsigned int tapCount, float x, float y )
1730 {
1731   DALI_ASSERT_DEBUG( mImpl->mEventData && "Unexpected TapEvent" );
1732
1733   if( NULL != mImpl->mEventData )
1734   {
1735     DALI_LOG_INFO( gLogFilter, Debug::Concise, "TapEvent state:%d \n", mImpl->mEventData->mState );
1736     EventData::State state( mImpl->mEventData->mState );
1737     bool relayoutNeeded( false );   // to avoid unnecessary relayouts when tapping an empty text-field
1738
1739     if( mImpl->IsClipboardVisible() )
1740     {
1741       if( EventData::INACTIVE == state || EventData::EDITING == state)
1742       {
1743         mImpl->ChangeState( EventData::EDITING_WITH_GRAB_HANDLE );
1744       }
1745       relayoutNeeded = true;
1746     }
1747     else if( 1u == tapCount )
1748     {
1749       if( EventData::EDITING_WITH_POPUP == state || EventData::EDITING_WITH_PASTE_POPUP == state )
1750       {
1751         mImpl->ChangeState( EventData::EDITING_WITH_GRAB_HANDLE );  // If Popup shown hide it here so can be shown again if required.
1752       }
1753
1754       if( mImpl->IsShowingRealText() && ( EventData::INACTIVE != state ) )
1755       {
1756         mImpl->ChangeState( EventData::EDITING_WITH_GRAB_HANDLE );
1757         relayoutNeeded = true;
1758       }
1759       else
1760       {
1761         if( mImpl->IsShowingPlaceholderText() && !mImpl->IsFocusedPlaceholderAvailable() )
1762         {
1763           // Hide placeholder text
1764           ResetText();
1765         }
1766
1767         if( EventData::INACTIVE == state )
1768         {
1769           mImpl->ChangeState( EventData::EDITING );
1770         }
1771         else if( !mImpl->IsClipboardEmpty() )
1772         {
1773           mImpl->ChangeState( EventData::EDITING_WITH_POPUP );
1774         }
1775         relayoutNeeded = true;
1776       }
1777     }
1778     else if( 2u == tapCount )
1779     {
1780       if( mImpl->mEventData->mSelectionEnabled &&
1781           mImpl->IsShowingRealText() )
1782       {
1783         SelectEvent( x, y, false );
1784       }
1785     }
1786     // Handles & cursors must be repositioned after Relayout() i.e. after the Model has been updated
1787     if( relayoutNeeded )
1788     {
1789       Event event( Event::TAP_EVENT );
1790       event.p1.mUint = tapCount;
1791       event.p2.mFloat = x;
1792       event.p3.mFloat = y;
1793       mImpl->mEventData->mEventQueue.push_back( event );
1794
1795       mImpl->RequestRelayout();
1796     }
1797   }
1798
1799   // Reset keyboard as tap event has occurred.
1800   mImpl->ResetImfManager();
1801 }
1802
1803 void Controller::PanEvent( Gesture::State state, const Vector2& displacement )
1804 {
1805   DALI_ASSERT_DEBUG( mImpl->mEventData && "Unexpected PanEvent" );
1806
1807   if( NULL != mImpl->mEventData )
1808   {
1809     Event event( Event::PAN_EVENT );
1810     event.p1.mInt = state;
1811     event.p2.mFloat = displacement.x;
1812     event.p3.mFloat = displacement.y;
1813     mImpl->mEventData->mEventQueue.push_back( event );
1814
1815     mImpl->RequestRelayout();
1816   }
1817 }
1818
1819 void Controller::LongPressEvent( Gesture::State state, float x, float y  )
1820 {
1821   DALI_ASSERT_DEBUG( mImpl->mEventData && "Unexpected LongPressEvent" );
1822
1823   if( ( state == Gesture::Started ) &&
1824       ( NULL != mImpl->mEventData ) )
1825   {
1826     if( !mImpl->IsShowingRealText() )
1827     {
1828       Event event( Event::LONG_PRESS_EVENT );
1829       event.p1.mInt = state;
1830       mImpl->mEventData->mEventQueue.push_back( event );
1831       mImpl->RequestRelayout();
1832     }
1833     else
1834     {
1835       // The 1st long-press on inactive text-field is treated as tap
1836       if( EventData::INACTIVE == mImpl->mEventData->mState )
1837       {
1838         mImpl->ChangeState( EventData::EDITING );
1839
1840         Event event( Event::TAP_EVENT );
1841         event.p1.mUint = 1;
1842         event.p2.mFloat = x;
1843         event.p3.mFloat = y;
1844         mImpl->mEventData->mEventQueue.push_back( event );
1845
1846         mImpl->RequestRelayout();
1847       }
1848       else if( !mImpl->IsClipboardVisible() )
1849       {
1850         // Reset the imf manger to commit the pre-edit before selecting the text.
1851         mImpl->ResetImfManager();
1852
1853         SelectEvent( x, y, false );
1854       }
1855     }
1856   }
1857 }
1858
1859 ImfManager::ImfCallbackData Controller::OnImfEvent( ImfManager& imfManager, const ImfManager::ImfEventData& imfEvent )
1860 {
1861   // Whether the text needs to be relaid-out.
1862   bool requestRelayout = false;
1863
1864   // Whether to retrieve the text and cursor position to be sent to the IMF manager.
1865   bool retrieveText = false;
1866   bool retrieveCursor = false;
1867
1868   switch( imfEvent.eventName )
1869   {
1870     case ImfManager::COMMIT:
1871     {
1872       InsertText( imfEvent.predictiveString, Text::Controller::COMMIT );
1873       requestRelayout = true;
1874       retrieveCursor = true;
1875       break;
1876     }
1877     case ImfManager::PREEDIT:
1878     {
1879       InsertText( imfEvent.predictiveString, Text::Controller::PRE_EDIT );
1880       requestRelayout = true;
1881       retrieveCursor = true;
1882       break;
1883     }
1884     case ImfManager::DELETESURROUNDING:
1885     {
1886       const bool textDeleted = RemoveText( imfEvent.cursorOffset,
1887                                            imfEvent.numberOfChars,
1888                                            DONT_UPDATE_INPUT_STYLE );
1889
1890       if( textDeleted )
1891       {
1892         if( ( 0u != mImpl->mLogicalModel->mText.Count() ) ||
1893             !mImpl->IsPlaceholderAvailable() )
1894         {
1895           mImpl->QueueModifyEvent( ModifyEvent::TEXT_DELETED );
1896         }
1897         else
1898         {
1899           ShowPlaceholderText();
1900         }
1901         mImpl->mEventData->mUpdateCursorPosition = true;
1902         mImpl->mEventData->mScrollAfterDelete = true;
1903
1904         requestRelayout = true;
1905       }
1906       break;
1907     }
1908     case ImfManager::GETSURROUNDING:
1909     {
1910       retrieveText = true;
1911       retrieveCursor = true;
1912       break;
1913     }
1914     case ImfManager::VOID:
1915     {
1916       // do nothing
1917       break;
1918     }
1919   } // end switch
1920
1921   if( requestRelayout )
1922   {
1923     mImpl->mOperationsPending = ALL_OPERATIONS;
1924     mImpl->RequestRelayout();
1925   }
1926
1927   std::string text;
1928   CharacterIndex cursorPosition = 0u;
1929   Length numberOfWhiteSpaces = 0u;
1930
1931   if( retrieveCursor )
1932   {
1933     numberOfWhiteSpaces = mImpl->GetNumberOfWhiteSpaces( 0u );
1934
1935     cursorPosition = mImpl->GetLogicalCursorPosition();
1936
1937     if( cursorPosition < numberOfWhiteSpaces )
1938     {
1939       cursorPosition = 0u;
1940     }
1941     else
1942     {
1943       cursorPosition -= numberOfWhiteSpaces;
1944     }
1945   }
1946
1947   if( retrieveText )
1948   {
1949     mImpl->GetText( numberOfWhiteSpaces, text );
1950   }
1951
1952   ImfManager::ImfCallbackData callbackData( ( retrieveText || retrieveCursor ), cursorPosition, text, false );
1953
1954   if( requestRelayout &&
1955       ( NULL != mImpl->mEditableControlInterface ) )
1956   {
1957     // Do this last since it provides callbacks into application code
1958     mImpl->mEditableControlInterface->TextChanged();
1959   }
1960
1961   return callbackData;
1962 }
1963
1964 void Controller::PasteClipboardItemEvent()
1965 {
1966   // Retrieve the clipboard contents first
1967   ClipboardEventNotifier notifier( ClipboardEventNotifier::Get() );
1968   std::string stringToPaste( notifier.GetContent() );
1969
1970   // Commit the current pre-edit text; the contents of the clipboard should be appended
1971   mImpl->ResetImfManager();
1972
1973   // Temporary disable hiding clipboard
1974   mImpl->SetClipboardHideEnable( false );
1975
1976   // Paste
1977   PasteText( stringToPaste );
1978
1979   mImpl->SetClipboardHideEnable( true );
1980 }
1981
1982 // protected : Inherit from Text::Decorator::ControllerInterface.
1983
1984 void Controller::GetTargetSize( Vector2& targetSize )
1985 {
1986   targetSize = mImpl->mVisualModel->mControlSize;
1987 }
1988
1989 void Controller::AddDecoration( Actor& actor, bool needsClipping )
1990 {
1991   if( NULL != mImpl->mEditableControlInterface )
1992   {
1993     mImpl->mEditableControlInterface->AddDecoration( actor, needsClipping );
1994   }
1995 }
1996
1997 void Controller::DecorationEvent( HandleType handleType, HandleState state, float x, float y )
1998 {
1999   DALI_ASSERT_DEBUG( mImpl->mEventData && "Unexpected DecorationEvent" );
2000
2001   if( NULL != mImpl->mEventData )
2002   {
2003     switch( handleType )
2004     {
2005       case GRAB_HANDLE:
2006       {
2007         Event event( Event::GRAB_HANDLE_EVENT );
2008         event.p1.mUint  = state;
2009         event.p2.mFloat = x;
2010         event.p3.mFloat = y;
2011
2012         mImpl->mEventData->mEventQueue.push_back( event );
2013         break;
2014       }
2015       case LEFT_SELECTION_HANDLE:
2016       {
2017         Event event( Event::LEFT_SELECTION_HANDLE_EVENT );
2018         event.p1.mUint  = state;
2019         event.p2.mFloat = x;
2020         event.p3.mFloat = y;
2021
2022         mImpl->mEventData->mEventQueue.push_back( event );
2023         break;
2024       }
2025       case RIGHT_SELECTION_HANDLE:
2026       {
2027         Event event( Event::RIGHT_SELECTION_HANDLE_EVENT );
2028         event.p1.mUint  = state;
2029         event.p2.mFloat = x;
2030         event.p3.mFloat = y;
2031
2032         mImpl->mEventData->mEventQueue.push_back( event );
2033         break;
2034       }
2035       case LEFT_SELECTION_HANDLE_MARKER:
2036       case RIGHT_SELECTION_HANDLE_MARKER:
2037       {
2038         // Markers do not move the handles.
2039         break;
2040       }
2041       case HANDLE_TYPE_COUNT:
2042       {
2043         DALI_ASSERT_DEBUG( !"Controller::HandleEvent. Unexpected handle type" );
2044       }
2045     }
2046
2047     mImpl->RequestRelayout();
2048   }
2049 }
2050
2051 // protected : Inherit from TextSelectionPopup::TextPopupButtonCallbackInterface.
2052
2053 void Controller::TextPopupButtonTouched( Dali::Toolkit::TextSelectionPopup::Buttons button )
2054 {
2055   if( NULL == mImpl->mEventData )
2056   {
2057     return;
2058   }
2059
2060   switch( button )
2061   {
2062     case Toolkit::TextSelectionPopup::CUT:
2063     {
2064       mImpl->SendSelectionToClipboard( true ); // Synchronous call to modify text
2065       mImpl->mOperationsPending = ALL_OPERATIONS;
2066
2067       if( ( 0u != mImpl->mLogicalModel->mText.Count() ) ||
2068           !mImpl->IsPlaceholderAvailable() )
2069       {
2070         mImpl->QueueModifyEvent( ModifyEvent::TEXT_DELETED );
2071       }
2072       else
2073       {
2074         ShowPlaceholderText();
2075       }
2076
2077       mImpl->mEventData->mUpdateCursorPosition = true;
2078       mImpl->mEventData->mScrollAfterDelete = true;
2079
2080       mImpl->RequestRelayout();
2081
2082       if( NULL != mImpl->mEditableControlInterface )
2083       {
2084         mImpl->mEditableControlInterface->TextChanged();
2085       }
2086       break;
2087     }
2088     case Toolkit::TextSelectionPopup::COPY:
2089     {
2090       mImpl->SendSelectionToClipboard( false ); // Text not modified
2091
2092       mImpl->mEventData->mUpdateCursorPosition = true;
2093
2094       mImpl->RequestRelayout(); // Cursor, Handles, Selection Highlight, Popup
2095       break;
2096     }
2097     case Toolkit::TextSelectionPopup::PASTE:
2098     {
2099       mImpl->RequestGetTextFromClipboard(); // Request clipboard service to retrieve an item
2100       break;
2101     }
2102     case Toolkit::TextSelectionPopup::SELECT:
2103     {
2104       const Vector2& currentCursorPosition = mImpl->mEventData->mDecorator->GetPosition( PRIMARY_CURSOR );
2105
2106       if( mImpl->mEventData->mSelectionEnabled )
2107       {
2108         // Creates a SELECT event.
2109         SelectEvent( currentCursorPosition.x, currentCursorPosition.y, false );
2110       }
2111       break;
2112     }
2113     case Toolkit::TextSelectionPopup::SELECT_ALL:
2114     {
2115       // Creates a SELECT_ALL event
2116       SelectEvent( 0.f, 0.f, true );
2117       break;
2118     }
2119     case Toolkit::TextSelectionPopup::CLIPBOARD:
2120     {
2121       mImpl->ShowClipboard();
2122       break;
2123     }
2124     case Toolkit::TextSelectionPopup::NONE:
2125     {
2126       // Nothing to do.
2127       break;
2128     }
2129   }
2130 }
2131
2132 // private : Update.
2133
2134 void Controller::InsertText( const std::string& text, Controller::InsertType type )
2135 {
2136   bool removedPrevious( false );
2137   bool maxLengthReached( false );
2138
2139   DALI_ASSERT_DEBUG( NULL != mImpl->mEventData && "Unexpected InsertText" )
2140
2141   if( NULL == mImpl->mEventData )
2142   {
2143     return;
2144   }
2145
2146   DALI_LOG_INFO( gLogFilter, Debug::Verbose, "Controller::InsertText %p %s (%s) mPrimaryCursorPosition %d mPreEditFlag %d mPreEditStartPosition %d mPreEditLength %d\n",
2147                  this, text.c_str(), (COMMIT == type ? "COMMIT" : "PRE_EDIT"),
2148                  mImpl->mEventData->mPrimaryCursorPosition, mImpl->mEventData->mPreEditFlag, mImpl->mEventData->mPreEditStartPosition, mImpl->mEventData->mPreEditLength );
2149
2150   // TODO: At the moment the underline runs are only for pre-edit.
2151   mImpl->mVisualModel->mUnderlineRuns.Clear();
2152
2153   // Keep the current number of characters.
2154   const Length currentNumberOfCharacters = mImpl->IsShowingRealText() ? mImpl->mLogicalModel->mText.Count() : 0u;
2155
2156   // Remove the previous IMF pre-edit.
2157   if( mImpl->mEventData->mPreEditFlag && ( 0u != mImpl->mEventData->mPreEditLength ) )
2158   {
2159     removedPrevious = RemoveText( -static_cast<int>( mImpl->mEventData->mPrimaryCursorPosition - mImpl->mEventData->mPreEditStartPosition ),
2160                                   mImpl->mEventData->mPreEditLength,
2161                                   DONT_UPDATE_INPUT_STYLE );
2162
2163     mImpl->mEventData->mPrimaryCursorPosition = mImpl->mEventData->mPreEditStartPosition;
2164     mImpl->mEventData->mPreEditLength = 0u;
2165   }
2166   else
2167   {
2168     // Remove the previous Selection.
2169     removedPrevious = RemoveSelectedText();
2170   }
2171
2172   Vector<Character> utf32Characters;
2173   Length characterCount = 0u;
2174
2175   if( !text.empty() )
2176   {
2177     //  Convert text into UTF-32
2178     utf32Characters.Resize( text.size() );
2179
2180     // This is a bit horrible but std::string returns a (signed) char*
2181     const uint8_t* utf8 = reinterpret_cast<const uint8_t*>( text.c_str() );
2182
2183     // Transform a text array encoded in utf8 into an array encoded in utf32.
2184     // It returns the actual number of characters.
2185     characterCount = Utf8ToUtf32( utf8, text.size(), utf32Characters.Begin() );
2186     utf32Characters.Resize( characterCount );
2187
2188     DALI_ASSERT_DEBUG( text.size() >= utf32Characters.Count() && "Invalid UTF32 conversion length" );
2189     DALI_LOG_INFO( gLogFilter, Debug::Verbose, "UTF8 size %d, UTF32 size %d\n", text.size(), utf32Characters.Count() );
2190   }
2191
2192   if( 0u != utf32Characters.Count() ) // Check if Utf8ToUtf32 conversion succeeded
2193   {
2194     // The placeholder text is no longer needed
2195     if( mImpl->IsShowingPlaceholderText() )
2196     {
2197       ResetText();
2198     }
2199
2200     mImpl->ChangeState( EventData::EDITING );
2201
2202     // Handle the IMF (predicitive text) state changes
2203     if( COMMIT == type )
2204     {
2205       // IMF manager is no longer handling key-events
2206       mImpl->ClearPreEditFlag();
2207     }
2208     else // PRE_EDIT
2209     {
2210       if( !mImpl->mEventData->mPreEditFlag )
2211       {
2212         DALI_LOG_INFO( gLogFilter, Debug::Verbose, "Entered PreEdit state\n" );
2213
2214         // Record the start of the pre-edit text
2215         mImpl->mEventData->mPreEditStartPosition = mImpl->mEventData->mPrimaryCursorPosition;
2216       }
2217
2218       mImpl->mEventData->mPreEditLength = utf32Characters.Count();
2219       mImpl->mEventData->mPreEditFlag = true;
2220
2221       DALI_LOG_INFO( gLogFilter, Debug::Verbose, "mPreEditStartPosition %d mPreEditLength %d\n", mImpl->mEventData->mPreEditStartPosition, mImpl->mEventData->mPreEditLength );
2222     }
2223
2224     const Length numberOfCharactersInModel = mImpl->mLogicalModel->mText.Count();
2225
2226     // Restrict new text to fit within Maximum characters setting.
2227     Length maxSizeOfNewText = std::min( ( mImpl->mMaximumNumberOfCharacters - numberOfCharactersInModel ), characterCount );
2228     maxLengthReached = ( characterCount > maxSizeOfNewText );
2229
2230     // The cursor position.
2231     CharacterIndex& cursorIndex = mImpl->mEventData->mPrimaryCursorPosition;
2232
2233     // Update the text's style.
2234
2235     // Updates the text style runs by adding characters.
2236     mImpl->mLogicalModel->UpdateTextStyleRuns( cursorIndex, maxSizeOfNewText );
2237
2238     // Get the character index from the cursor index.
2239     const CharacterIndex styleIndex = ( cursorIndex > 0u ) ? cursorIndex - 1u : 0u;
2240
2241     // Retrieve the text's style for the given index.
2242     InputStyle style;
2243     mImpl->RetrieveDefaultInputStyle( style );
2244     mImpl->mLogicalModel->RetrieveStyle( styleIndex, style );
2245
2246     // Whether to add a new text color run.
2247     const bool addColorRun = ( style.textColor != mImpl->mEventData->mInputStyle.textColor );
2248
2249     // Whether to add a new font run.
2250     const bool addFontNameRun = style.familyName != mImpl->mEventData->mInputStyle.familyName;
2251     const bool addFontWeightRun = style.weight != mImpl->mEventData->mInputStyle.weight;
2252     const bool addFontWidthRun = style.width != mImpl->mEventData->mInputStyle.width;
2253     const bool addFontSlantRun = style.slant != mImpl->mEventData->mInputStyle.slant;
2254     const bool addFontSizeRun = style.size != mImpl->mEventData->mInputStyle.size;
2255
2256     // Add style runs.
2257     if( addColorRun )
2258     {
2259       const VectorBase::SizeType numberOfRuns = mImpl->mLogicalModel->mColorRuns.Count();
2260       mImpl->mLogicalModel->mColorRuns.Resize( numberOfRuns + 1u );
2261
2262       ColorRun& colorRun = *( mImpl->mLogicalModel->mColorRuns.Begin() + numberOfRuns );
2263       colorRun.color = mImpl->mEventData->mInputStyle.textColor;
2264       colorRun.characterRun.characterIndex = cursorIndex;
2265       colorRun.characterRun.numberOfCharacters = maxSizeOfNewText;
2266     }
2267
2268     if( addFontNameRun   ||
2269         addFontWeightRun ||
2270         addFontWidthRun  ||
2271         addFontSlantRun  ||
2272         addFontSizeRun )
2273     {
2274       const VectorBase::SizeType numberOfRuns = mImpl->mLogicalModel->mFontDescriptionRuns.Count();
2275       mImpl->mLogicalModel->mFontDescriptionRuns.Resize( numberOfRuns + 1u );
2276
2277       FontDescriptionRun& fontDescriptionRun = *( mImpl->mLogicalModel->mFontDescriptionRuns.Begin() + numberOfRuns );
2278
2279       if( addFontNameRun )
2280       {
2281         fontDescriptionRun.familyLength = mImpl->mEventData->mInputStyle.familyName.size();
2282         fontDescriptionRun.familyName = new char[fontDescriptionRun.familyLength];
2283         memcpy( fontDescriptionRun.familyName, mImpl->mEventData->mInputStyle.familyName.c_str(), fontDescriptionRun.familyLength );
2284         fontDescriptionRun.familyDefined = true;
2285
2286         // The memory allocated for the font family name is freed when the font description is removed from the logical model.
2287       }
2288
2289       if( addFontWeightRun )
2290       {
2291         fontDescriptionRun.weight = mImpl->mEventData->mInputStyle.weight;
2292         fontDescriptionRun.weightDefined = true;
2293       }
2294
2295       if( addFontWidthRun )
2296       {
2297         fontDescriptionRun.width = mImpl->mEventData->mInputStyle.width;
2298         fontDescriptionRun.widthDefined = true;
2299       }
2300
2301       if( addFontSlantRun )
2302       {
2303         fontDescriptionRun.slant = mImpl->mEventData->mInputStyle.slant;
2304         fontDescriptionRun.slantDefined = true;
2305       }
2306
2307       if( addFontSizeRun )
2308       {
2309         fontDescriptionRun.size = static_cast<PointSize26Dot6>( mImpl->mEventData->mInputStyle.size * 64.f );
2310         fontDescriptionRun.sizeDefined = true;
2311       }
2312
2313       fontDescriptionRun.characterRun.characterIndex = cursorIndex;
2314       fontDescriptionRun.characterRun.numberOfCharacters = maxSizeOfNewText;
2315     }
2316
2317     // Insert at current cursor position.
2318     Vector<Character>& modifyText = mImpl->mLogicalModel->mText;
2319
2320     if( cursorIndex < numberOfCharactersInModel )
2321     {
2322       modifyText.Insert( modifyText.Begin() + cursorIndex, utf32Characters.Begin(), utf32Characters.Begin() + maxSizeOfNewText );
2323     }
2324     else
2325     {
2326       modifyText.Insert( modifyText.End(), utf32Characters.Begin(), utf32Characters.Begin() + maxSizeOfNewText );
2327     }
2328
2329     // Mark the first paragraph to be updated.
2330     mImpl->mTextUpdateInfo.mCharacterIndex = std::min( cursorIndex, mImpl->mTextUpdateInfo.mCharacterIndex );
2331     mImpl->mTextUpdateInfo.mNumberOfCharactersToAdd += maxSizeOfNewText;
2332
2333     // Update the cursor index.
2334     cursorIndex += maxSizeOfNewText;
2335
2336     DALI_LOG_INFO( gLogFilter, Debug::Verbose, "Inserted %d characters, new size %d new cursor %d\n", maxSizeOfNewText, mImpl->mLogicalModel->mText.Count(), mImpl->mEventData->mPrimaryCursorPosition );
2337   }
2338
2339   const Length numberOfCharacters = mImpl->IsShowingRealText() ? mImpl->mLogicalModel->mText.Count() : 0u;
2340
2341   if( ( 0u == mImpl->mLogicalModel->mText.Count() ) &&
2342       mImpl->IsPlaceholderAvailable() )
2343   {
2344     // Show place-holder if empty after removing the pre-edit text
2345     ShowPlaceholderText();
2346     mImpl->mEventData->mUpdateCursorPosition = true;
2347     mImpl->ClearPreEditFlag();
2348   }
2349   else if( removedPrevious ||
2350            ( 0 != utf32Characters.Count() ) )
2351   {
2352     // Queue an inserted event
2353     mImpl->QueueModifyEvent( ModifyEvent::TEXT_INSERTED );
2354
2355     mImpl->mEventData->mUpdateCursorPosition = true;
2356     if( numberOfCharacters < currentNumberOfCharacters )
2357     {
2358       mImpl->mEventData->mScrollAfterDelete = true;
2359     }
2360     else
2361     {
2362       mImpl->mEventData->mScrollAfterUpdatePosition = true;
2363     }
2364   }
2365
2366   if( maxLengthReached )
2367   {
2368     DALI_LOG_INFO( gLogFilter, Debug::Verbose, "MaxLengthReached (%d)\n", mImpl->mLogicalModel->mText.Count() );
2369
2370     mImpl->ResetImfManager();
2371
2372     if( NULL != mImpl->mEditableControlInterface )
2373     {
2374       // Do this last since it provides callbacks into application code
2375       mImpl->mEditableControlInterface->MaxLengthReached();
2376     }
2377   }
2378 }
2379
2380 void Controller::PasteText( const std::string& stringToPaste )
2381 {
2382   InsertText( stringToPaste, Text::Controller::COMMIT );
2383   mImpl->ChangeState( EventData::EDITING );
2384   mImpl->RequestRelayout();
2385
2386   if( NULL != mImpl->mEditableControlInterface )
2387   {
2388     // Do this last since it provides callbacks into application code
2389     mImpl->mEditableControlInterface->TextChanged();
2390   }
2391 }
2392
2393 bool Controller::RemoveText( int cursorOffset,
2394                              int numberOfCharacters,
2395                              UpdateInputStyleType type )
2396 {
2397   bool removed = false;
2398
2399   if( NULL == mImpl->mEventData )
2400   {
2401     return removed;
2402   }
2403
2404   DALI_LOG_INFO( gLogFilter, Debug::General, "Controller::RemoveText %p mText.Count() %d cursor %d cursorOffset %d numberOfCharacters %d\n",
2405                  this, mImpl->mLogicalModel->mText.Count(), mImpl->mEventData->mPrimaryCursorPosition, cursorOffset, numberOfCharacters );
2406
2407   if( !mImpl->IsShowingPlaceholderText() )
2408   {
2409     // Delete at current cursor position
2410     Vector<Character>& currentText = mImpl->mLogicalModel->mText;
2411     CharacterIndex& oldCursorIndex = mImpl->mEventData->mPrimaryCursorPosition;
2412
2413     CharacterIndex cursorIndex = oldCursorIndex;
2414
2415     // Validate the cursor position & number of characters
2416     if( static_cast< CharacterIndex >( std::abs( cursorOffset ) ) <= cursorIndex )
2417     {
2418       cursorIndex = oldCursorIndex + cursorOffset;
2419     }
2420
2421     if( ( cursorIndex + numberOfCharacters ) > currentText.Count() )
2422     {
2423       numberOfCharacters = currentText.Count() - cursorIndex;
2424     }
2425
2426     if( ( cursorIndex + numberOfCharacters ) <= mImpl->mTextUpdateInfo.mPreviousNumberOfCharacters )
2427     {
2428       // Mark the paragraphs to be updated.
2429       mImpl->mTextUpdateInfo.mCharacterIndex = std::min( cursorIndex, mImpl->mTextUpdateInfo.mCharacterIndex );
2430       mImpl->mTextUpdateInfo.mNumberOfCharactersToRemove += numberOfCharacters;
2431
2432       // Update the input style and remove the text's style before removing the text.
2433
2434       if( UPDATE_INPUT_STYLE == type )
2435       {
2436         // Keep a copy of the current input style.
2437         InputStyle currentInputStyle;
2438         currentInputStyle.Copy( mImpl->mEventData->mInputStyle );
2439
2440         // Set first the default input style.
2441         mImpl->RetrieveDefaultInputStyle( mImpl->mEventData->mInputStyle );
2442
2443         // Update the input style.
2444         mImpl->mLogicalModel->RetrieveStyle( cursorIndex, mImpl->mEventData->mInputStyle );
2445
2446         // Compare if the input style has changed.
2447         const bool hasInputStyleChanged = !currentInputStyle.Equal( mImpl->mEventData->mInputStyle );
2448
2449         if( hasInputStyleChanged )
2450         {
2451           const InputStyle::Mask styleChangedMask = currentInputStyle.GetInputStyleChangeMask( mImpl->mEventData->mInputStyle );
2452           // Queue the input style changed signal.
2453           mImpl->mEventData->mInputStyleChangedQueue.PushBack( styleChangedMask );
2454         }
2455       }
2456
2457       // Updates the text style runs by removing characters. Runs with no characters are removed.
2458       mImpl->mLogicalModel->UpdateTextStyleRuns( cursorIndex, -numberOfCharacters );
2459
2460       // Remove the characters.
2461       Vector<Character>::Iterator first = currentText.Begin() + cursorIndex;
2462       Vector<Character>::Iterator last  = first + numberOfCharacters;
2463
2464       currentText.Erase( first, last );
2465
2466       // Cursor position retreat
2467       oldCursorIndex = cursorIndex;
2468
2469       mImpl->mEventData->mScrollAfterDelete = true;
2470
2471       DALI_LOG_INFO( gLogFilter, Debug::General, "Controller::RemoveText %p removed %d\n", this, numberOfCharacters );
2472       removed = true;
2473     }
2474   }
2475
2476   return removed;
2477 }
2478
2479 bool Controller::RemoveSelectedText()
2480 {
2481   bool textRemoved( false );
2482
2483   if( EventData::SELECTING == mImpl->mEventData->mState )
2484   {
2485     std::string removedString;
2486     mImpl->RetrieveSelection( removedString, true );
2487
2488     if( !removedString.empty() )
2489     {
2490       textRemoved = true;
2491       mImpl->ChangeState( EventData::EDITING );
2492     }
2493   }
2494
2495   return textRemoved;
2496 }
2497
2498 // private : Relayout.
2499
2500 bool Controller::DoRelayout( const Size& size,
2501                              OperationsMask operationsRequired,
2502                              Size& layoutSize )
2503 {
2504   DALI_LOG_INFO( gLogFilter, Debug::Verbose, "-->Controller::DoRelayout %p size %f,%f\n", this, size.width, size.height );
2505   bool viewUpdated( false );
2506
2507   // Calculate the operations to be done.
2508   const OperationsMask operations = static_cast<OperationsMask>( mImpl->mOperationsPending & operationsRequired );
2509
2510   const CharacterIndex startIndex = mImpl->mTextUpdateInfo.mParagraphCharacterIndex;
2511   const Length requestedNumberOfCharacters = mImpl->mTextUpdateInfo.mRequestedNumberOfCharacters;
2512
2513   // Get the current layout size.
2514   layoutSize = mImpl->mVisualModel->GetLayoutSize();
2515
2516   if( NO_OPERATION != ( LAYOUT & operations ) )
2517   {
2518     DALI_LOG_INFO( gLogFilter, Debug::Verbose, "-->Controller::DoRelayout LAYOUT & operations\n");
2519
2520     // Some vectors with data needed to layout and reorder may be void
2521     // after the first time the text has been laid out.
2522     // Fill the vectors again.
2523
2524     // Calculate the number of glyphs to layout.
2525     const Vector<GlyphIndex>& charactersToGlyph = mImpl->mVisualModel->mCharactersToGlyph;
2526     const Vector<Length>& glyphsPerCharacter = mImpl->mVisualModel->mGlyphsPerCharacter;
2527     const GlyphIndex* const charactersToGlyphBuffer = charactersToGlyph.Begin();
2528     const Length* const glyphsPerCharacterBuffer = glyphsPerCharacter.Begin();
2529
2530     const CharacterIndex lastIndex = startIndex + ( ( requestedNumberOfCharacters > 0u ) ? requestedNumberOfCharacters - 1u : 0u );
2531     const GlyphIndex startGlyphIndex = mImpl->mTextUpdateInfo.mStartGlyphIndex;
2532     const Length numberOfGlyphs = ( requestedNumberOfCharacters > 0u ) ? *( charactersToGlyphBuffer + lastIndex ) + *( glyphsPerCharacterBuffer + lastIndex ) - startGlyphIndex : 0u;
2533     const Length totalNumberOfGlyphs = mImpl->mVisualModel->mGlyphs.Count();
2534
2535     if( 0u == totalNumberOfGlyphs )
2536     {
2537       if( NO_OPERATION != ( UPDATE_LAYOUT_SIZE & operations ) )
2538       {
2539         mImpl->mVisualModel->SetLayoutSize( Size::ZERO );
2540       }
2541
2542       // Nothing else to do if there is no glyphs.
2543       DALI_LOG_INFO( gLogFilter, Debug::Verbose, "<--Controller::DoRelayout no glyphs, view updated true\n" );
2544       return true;
2545     }
2546
2547     const Vector<LineBreakInfo>& lineBreakInfo = mImpl->mLogicalModel->mLineBreakInfo;
2548     const Vector<WordBreakInfo>& wordBreakInfo = mImpl->mLogicalModel->mWordBreakInfo;
2549     const Vector<CharacterDirection>& characterDirection = mImpl->mLogicalModel->mCharacterDirections;
2550     const Vector<GlyphInfo>& glyphs = mImpl->mVisualModel->mGlyphs;
2551     const Vector<CharacterIndex>& glyphsToCharactersMap = mImpl->mVisualModel->mGlyphsToCharacters;
2552     const Vector<Length>& charactersPerGlyph = mImpl->mVisualModel->mCharactersPerGlyph;
2553     const Character* const textBuffer = mImpl->mLogicalModel->mText.Begin();
2554
2555     // Set the layout parameters.
2556     LayoutParameters layoutParameters( size,
2557                                        textBuffer,
2558                                        lineBreakInfo.Begin(),
2559                                        wordBreakInfo.Begin(),
2560                                        ( 0u != characterDirection.Count() ) ? characterDirection.Begin() : NULL,
2561                                        glyphs.Begin(),
2562                                        glyphsToCharactersMap.Begin(),
2563                                        charactersPerGlyph.Begin(),
2564                                        charactersToGlyphBuffer,
2565                                        glyphsPerCharacterBuffer,
2566                                        totalNumberOfGlyphs );
2567
2568     // Resize the vector of positions to have the same size than the vector of glyphs.
2569     Vector<Vector2>& glyphPositions = mImpl->mVisualModel->mGlyphPositions;
2570     glyphPositions.Resize( totalNumberOfGlyphs );
2571
2572     // Whether the last character is a new paragraph character.
2573     mImpl->mTextUpdateInfo.mIsLastCharacterNewParagraph =  TextAbstraction::IsNewParagraph( *( textBuffer + ( mImpl->mLogicalModel->mText.Count() - 1u ) ) );
2574     layoutParameters.isLastNewParagraph = mImpl->mTextUpdateInfo.mIsLastCharacterNewParagraph;
2575
2576     // The initial glyph and the number of glyphs to layout.
2577     layoutParameters.startGlyphIndex = startGlyphIndex;
2578     layoutParameters.numberOfGlyphs = numberOfGlyphs;
2579     layoutParameters.startLineIndex = mImpl->mTextUpdateInfo.mStartLineIndex;
2580     layoutParameters.estimatedNumberOfLines = mImpl->mTextUpdateInfo.mEstimatedNumberOfLines;
2581
2582     // Update the visual model.
2583     Size newLayoutSize;
2584     viewUpdated = mImpl->mLayoutEngine.LayoutText( layoutParameters,
2585                                                    glyphPositions,
2586                                                    mImpl->mVisualModel->mLines,
2587                                                    newLayoutSize );
2588
2589     viewUpdated = viewUpdated || ( newLayoutSize != layoutSize );
2590
2591     if( viewUpdated )
2592     {
2593       layoutSize = newLayoutSize;
2594
2595       if ( NO_OPERATION != ( UPDATE_DIRECTION & operations ) )
2596       {
2597         mImpl->mAutoScrollDirectionRTL = false;
2598       }
2599
2600       // Reorder the lines
2601       if( NO_OPERATION != ( REORDER & operations ) )
2602       {
2603         Vector<BidirectionalParagraphInfoRun>& bidirectionalInfo = mImpl->mLogicalModel->mBidirectionalParagraphInfo;
2604         Vector<BidirectionalLineInfoRun>& bidirectionalLineInfo = mImpl->mLogicalModel->mBidirectionalLineInfo;
2605
2606         // Check first if there are paragraphs with bidirectional info.
2607         if( 0u != bidirectionalInfo.Count() )
2608         {
2609           // Get the lines
2610           const Length numberOfLines = mImpl->mVisualModel->mLines.Count();
2611
2612           // Reorder the lines.
2613           bidirectionalLineInfo.Reserve( numberOfLines ); // Reserve because is not known yet how many lines have right to left characters.
2614           ReorderLines( bidirectionalInfo,
2615                         startIndex,
2616                         requestedNumberOfCharacters,
2617                         mImpl->mVisualModel->mLines,
2618                         bidirectionalLineInfo );
2619
2620           // Set the bidirectional info per line into the layout parameters.
2621           layoutParameters.lineBidirectionalInfoRunsBuffer = bidirectionalLineInfo.Begin();
2622           layoutParameters.numberOfBidirectionalInfoRuns = bidirectionalLineInfo.Count();
2623
2624           // Re-layout the text. Reorder those lines with right to left characters.
2625           mImpl->mLayoutEngine.ReLayoutRightToLeftLines( layoutParameters,
2626                                                          startIndex,
2627                                                          requestedNumberOfCharacters,
2628                                                          glyphPositions );
2629
2630           if ( ( NO_OPERATION != ( UPDATE_DIRECTION & operations ) ) && ( numberOfLines > 0 ) )
2631           {
2632             const LineRun* const firstline = mImpl->mVisualModel->mLines.Begin();
2633             if ( firstline )
2634             {
2635               mImpl->mAutoScrollDirectionRTL = firstline->direction;
2636             }
2637           }
2638         }
2639       } // REORDER
2640
2641       // Sets the layout size.
2642       if( NO_OPERATION != ( UPDATE_LAYOUT_SIZE & operations ) )
2643       {
2644         mImpl->mVisualModel->SetLayoutSize( layoutSize );
2645       }
2646     } // view updated
2647
2648     // Store the size used to layout the text.
2649     mImpl->mVisualModel->mControlSize = size;
2650   }
2651
2652   if( NO_OPERATION != ( ALIGN & operations ) )
2653   {
2654     // The laid-out lines.
2655     Vector<LineRun>& lines = mImpl->mVisualModel->mLines;
2656
2657     mImpl->mLayoutEngine.Align( size,
2658                                 startIndex,
2659                                 requestedNumberOfCharacters,
2660                                 lines );
2661
2662     viewUpdated = true;
2663   }
2664 #if defined(DEBUG_ENABLED)
2665   std::string currentText;
2666   GetText( currentText );
2667   DALI_LOG_INFO( gLogFilter, Debug::Concise, "Controller::DoRelayout [%p] mImpl->mAutoScrollDirectionRTL[%s] [%s]\n", this, (mImpl->mAutoScrollDirectionRTL)?"true":"false",  currentText.c_str() );
2668 #endif
2669   DALI_LOG_INFO( gLogFilter, Debug::Verbose, "<--Controller::DoRelayout, view updated %s\n", ( viewUpdated ? "true" : "false" ) );
2670   return viewUpdated;
2671 }
2672
2673 void Controller::CalculateVerticalOffset( const Size& controlSize )
2674 {
2675   Size layoutSize = mImpl->mVisualModel->GetLayoutSize();
2676
2677   if( fabsf( layoutSize.height ) < Math::MACHINE_EPSILON_1000 )
2678   {
2679     // Get the line height of the default font.
2680     layoutSize.height = mImpl->GetDefaultFontLineHeight();
2681   }
2682
2683   switch( mImpl->mLayoutEngine.GetVerticalAlignment() )
2684   {
2685     case LayoutEngine::VERTICAL_ALIGN_TOP:
2686     {
2687       mImpl->mScrollPosition.y = 0.f;
2688       break;
2689     }
2690     case LayoutEngine::VERTICAL_ALIGN_CENTER:
2691     {
2692       mImpl->mScrollPosition.y = floorf( 0.5f * ( controlSize.height - layoutSize.height ) ); // try to avoid pixel alignment.
2693       break;
2694     }
2695     case LayoutEngine::VERTICAL_ALIGN_BOTTOM:
2696     {
2697       mImpl->mScrollPosition.y = controlSize.height - layoutSize.height;
2698       break;
2699     }
2700   }
2701 }
2702
2703 // private : Events.
2704
2705 void Controller::ProcessModifyEvents()
2706 {
2707   Vector<ModifyEvent>& events = mImpl->mModifyEvents;
2708
2709   if( 0u == events.Count() )
2710   {
2711     // Nothing to do.
2712     return;
2713   }
2714
2715   for( Vector<ModifyEvent>::ConstIterator it = events.Begin(),
2716          endIt = events.End();
2717        it != endIt;
2718        ++it )
2719   {
2720     const ModifyEvent& event = *it;
2721
2722     if( ModifyEvent::TEXT_REPLACED == event.type )
2723     {
2724       // A (single) replace event should come first, otherwise we wasted time processing NOOP events
2725       DALI_ASSERT_DEBUG( it == events.Begin() && "Unexpected TEXT_REPLACED event" );
2726
2727       TextReplacedEvent();
2728     }
2729     else if( ModifyEvent::TEXT_INSERTED == event.type )
2730     {
2731       TextInsertedEvent();
2732     }
2733     else if( ModifyEvent::TEXT_DELETED == event.type )
2734     {
2735       // Placeholder-text cannot be deleted
2736       if( !mImpl->IsShowingPlaceholderText() )
2737       {
2738         TextDeletedEvent();
2739       }
2740     }
2741   }
2742
2743   if( NULL != mImpl->mEventData )
2744   {
2745     // When the text is being modified, delay cursor blinking
2746     mImpl->mEventData->mDecorator->DelayCursorBlink();
2747   }
2748
2749   // Discard temporary text
2750   events.Clear();
2751 }
2752
2753 void Controller::TextReplacedEvent()
2754 {
2755   // The natural size needs to be re-calculated.
2756   mImpl->mRecalculateNaturalSize = true;
2757
2758   // Apply modifications to the model
2759   mImpl->mOperationsPending = ALL_OPERATIONS;
2760 }
2761
2762 void Controller::TextInsertedEvent()
2763 {
2764   DALI_ASSERT_DEBUG( NULL != mImpl->mEventData && "Unexpected TextInsertedEvent" );
2765
2766   if( NULL == mImpl->mEventData )
2767   {
2768     return;
2769   }
2770
2771   // The natural size needs to be re-calculated.
2772   mImpl->mRecalculateNaturalSize = true;
2773
2774   // Apply modifications to the model; TODO - Optimize this
2775   mImpl->mOperationsPending = ALL_OPERATIONS;
2776 }
2777
2778 void Controller::TextDeletedEvent()
2779 {
2780   DALI_ASSERT_DEBUG( NULL != mImpl->mEventData && "Unexpected TextDeletedEvent" );
2781
2782   if( NULL == mImpl->mEventData )
2783   {
2784     return;
2785   }
2786
2787   // The natural size needs to be re-calculated.
2788   mImpl->mRecalculateNaturalSize = true;
2789
2790   // Apply modifications to the model; TODO - Optimize this
2791   mImpl->mOperationsPending = ALL_OPERATIONS;
2792 }
2793
2794 void Controller::SelectEvent( float x, float y, bool selectAll )
2795 {
2796   DALI_LOG_INFO( gLogFilter, Debug::Verbose, "Controller::SelectEvent\n" );
2797
2798   if( NULL != mImpl->mEventData )
2799   {
2800     if( selectAll )
2801     {
2802       Event event( Event::SELECT_ALL );
2803       mImpl->mEventData->mEventQueue.push_back( event );
2804     }
2805     else
2806     {
2807       Event event( Event::SELECT );
2808       event.p2.mFloat = x;
2809       event.p3.mFloat = y;
2810       mImpl->mEventData->mEventQueue.push_back( event );
2811     }
2812
2813     mImpl->RequestRelayout();
2814   }
2815 }
2816
2817 bool Controller::BackspaceKeyEvent()
2818 {
2819   DALI_LOG_INFO( gLogFilter, Debug::Verbose, "Controller::KeyEvent %p DALI_KEY_BACKSPACE\n", this );
2820
2821   bool removed = false;
2822
2823   if( NULL == mImpl->mEventData )
2824   {
2825     return removed;
2826   }
2827
2828   // IMF manager is no longer handling key-events
2829   mImpl->ClearPreEditFlag();
2830
2831   if( EventData::SELECTING == mImpl->mEventData->mState )
2832   {
2833     removed = RemoveSelectedText();
2834   }
2835   else if( mImpl->mEventData->mPrimaryCursorPosition > 0 )
2836   {
2837     // Remove the character before the current cursor position
2838     removed = RemoveText( -1,
2839                           1,
2840                           UPDATE_INPUT_STYLE );
2841   }
2842
2843   if( removed )
2844   {
2845     if( ( 0u != mImpl->mLogicalModel->mText.Count() ) ||
2846         !mImpl->IsPlaceholderAvailable() )
2847     {
2848       mImpl->QueueModifyEvent( ModifyEvent::TEXT_DELETED );
2849     }
2850     else
2851     {
2852       ShowPlaceholderText();
2853     }
2854     mImpl->mEventData->mUpdateCursorPosition = true;
2855     mImpl->mEventData->mScrollAfterDelete = true;
2856   }
2857
2858   return removed;
2859 }
2860
2861 // private : Helpers.
2862
2863 void Controller::ResetText()
2864 {
2865   // Reset buffers.
2866   mImpl->mLogicalModel->mText.Clear();
2867
2868   // We have cleared everything including the placeholder-text
2869   mImpl->PlaceholderCleared();
2870
2871   mImpl->mTextUpdateInfo.mCharacterIndex = 0u;
2872   mImpl->mTextUpdateInfo.mNumberOfCharactersToRemove = mImpl->mTextUpdateInfo.mPreviousNumberOfCharacters;
2873   mImpl->mTextUpdateInfo.mNumberOfCharactersToAdd = 0u;
2874
2875   // Clear any previous text.
2876   mImpl->mTextUpdateInfo.mClearAll = true;
2877
2878   // The natural size needs to be re-calculated.
2879   mImpl->mRecalculateNaturalSize = true;
2880
2881   // Apply modifications to the model
2882   mImpl->mOperationsPending = ALL_OPERATIONS;
2883 }
2884
2885 void Controller::ShowPlaceholderText()
2886 {
2887   if( mImpl->IsPlaceholderAvailable() )
2888   {
2889     DALI_ASSERT_DEBUG( mImpl->mEventData && "No placeholder text available" );
2890
2891     if( NULL == mImpl->mEventData )
2892     {
2893       return;
2894     }
2895
2896     mImpl->mEventData->mIsShowingPlaceholderText = true;
2897
2898     // Disable handles when showing place-holder text
2899     mImpl->mEventData->mDecorator->SetHandleActive( GRAB_HANDLE, false );
2900     mImpl->mEventData->mDecorator->SetHandleActive( LEFT_SELECTION_HANDLE, false );
2901     mImpl->mEventData->mDecorator->SetHandleActive( RIGHT_SELECTION_HANDLE, false );
2902
2903     const char* text( NULL );
2904     size_t size( 0 );
2905
2906     // TODO - Switch placeholder text styles when changing state
2907     if( ( EventData::INACTIVE != mImpl->mEventData->mState ) &&
2908         ( 0u != mImpl->mEventData->mPlaceholderTextActive.c_str() ) )
2909     {
2910       text = mImpl->mEventData->mPlaceholderTextActive.c_str();
2911       size = mImpl->mEventData->mPlaceholderTextActive.size();
2912     }
2913     else
2914     {
2915       text = mImpl->mEventData->mPlaceholderTextInactive.c_str();
2916       size = mImpl->mEventData->mPlaceholderTextInactive.size();
2917     }
2918
2919     mImpl->mTextUpdateInfo.mCharacterIndex = 0u;
2920     mImpl->mTextUpdateInfo.mNumberOfCharactersToRemove = mImpl->mTextUpdateInfo.mPreviousNumberOfCharacters;
2921
2922     // Reset model for showing placeholder.
2923     mImpl->mLogicalModel->mText.Clear();
2924     mImpl->mVisualModel->SetTextColor( mImpl->mEventData->mPlaceholderTextColor );
2925
2926     // Convert text into UTF-32
2927     Vector<Character>& utf32Characters = mImpl->mLogicalModel->mText;
2928     utf32Characters.Resize( size );
2929
2930     // This is a bit horrible but std::string returns a (signed) char*
2931     const uint8_t* utf8 = reinterpret_cast<const uint8_t*>( text );
2932
2933     // Transform a text array encoded in utf8 into an array encoded in utf32.
2934     // It returns the actual number of characters.
2935     const Length characterCount = Utf8ToUtf32( utf8, size, utf32Characters.Begin() );
2936     utf32Characters.Resize( characterCount );
2937
2938     // The characters to be added.
2939     mImpl->mTextUpdateInfo.mNumberOfCharactersToAdd = characterCount;
2940
2941     // Reset the cursor position
2942     mImpl->mEventData->mPrimaryCursorPosition = 0;
2943
2944     // The natural size needs to be re-calculated.
2945     mImpl->mRecalculateNaturalSize = true;
2946
2947     // Apply modifications to the model
2948     mImpl->mOperationsPending = ALL_OPERATIONS;
2949
2950     // Update the rest of the model during size negotiation
2951     mImpl->QueueModifyEvent( ModifyEvent::TEXT_REPLACED );
2952   }
2953 }
2954
2955 void Controller::ClearFontData()
2956 {
2957   if( mImpl->mFontDefaults )
2958   {
2959     mImpl->mFontDefaults->mFontId = 0u; // Remove old font ID
2960   }
2961
2962   // Set flags to update the model.
2963   mImpl->mTextUpdateInfo.mCharacterIndex = 0u;
2964   mImpl->mTextUpdateInfo.mNumberOfCharactersToRemove = mImpl->mTextUpdateInfo.mPreviousNumberOfCharacters;
2965   mImpl->mTextUpdateInfo.mNumberOfCharactersToAdd = mImpl->mLogicalModel->mText.Count();
2966
2967   mImpl->mTextUpdateInfo.mClearAll = true;
2968   mImpl->mTextUpdateInfo.mFullRelayoutNeeded = true;
2969   mImpl->mRecalculateNaturalSize = true;
2970
2971   mImpl->mOperationsPending = static_cast<OperationsMask>( mImpl->mOperationsPending |
2972                                                            VALIDATE_FONTS            |
2973                                                            SHAPE_TEXT                |
2974                                                            GET_GLYPH_METRICS         |
2975                                                            LAYOUT                    |
2976                                                            UPDATE_LAYOUT_SIZE        |
2977                                                            REORDER                   |
2978                                                            ALIGN );
2979 }
2980
2981 void Controller::ClearStyleData()
2982 {
2983   mImpl->mLogicalModel->mColorRuns.Clear();
2984   mImpl->mLogicalModel->ClearFontDescriptionRuns();
2985 }
2986
2987 void Controller::ResetCursorPosition( CharacterIndex cursorIndex )
2988 {
2989   // Reset the cursor position
2990   if( NULL != mImpl->mEventData )
2991   {
2992     mImpl->mEventData->mPrimaryCursorPosition = cursorIndex;
2993
2994     // Update the cursor if it's in editing mode.
2995     if( EventData::IsEditingState( mImpl->mEventData->mState )  )
2996     {
2997       mImpl->mEventData->mUpdateCursorPosition = true;
2998     }
2999   }
3000 }
3001
3002 void Controller::ResetScrollPosition()
3003 {
3004   if( NULL != mImpl->mEventData )
3005   {
3006     // Reset the scroll position.
3007     mImpl->mScrollPosition = Vector2::ZERO;
3008     mImpl->mEventData->mScrollAfterUpdatePosition = true;
3009   }
3010 }
3011
3012 // private : Private contructors & copy operator.
3013
3014 Controller::Controller()
3015 : mImpl( NULL )
3016 {
3017   mImpl = new Controller::Impl( NULL, NULL );
3018 }
3019
3020 Controller::Controller( ControlInterface* controlInterface )
3021 {
3022   mImpl = new Controller::Impl( controlInterface, NULL );
3023 }
3024
3025 Controller::Controller( ControlInterface* controlInterface,
3026                         EditableControlInterface* editableControlInterface )
3027 {
3028   mImpl = new Controller::Impl( controlInterface,
3029                                 editableControlInterface );
3030 }
3031
3032 // The copy constructor and operator are left unimplemented.
3033
3034 // protected : Destructor.
3035
3036 Controller::~Controller()
3037 {
3038   delete mImpl;
3039 }
3040
3041 } // namespace Text
3042
3043 } // namespace Toolkit
3044
3045 } // namespace Dali