Relayout again for LTR / RTL order when layout direction is changed.
[platform/core/uifw/dali-toolkit.git] / dali-toolkit / internal / text / text-controller.cpp
1 /*
2  * Copyright (c) 2018 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 #include <dali/devel-api/text-abstraction/font-client.h>
28 #include <dali/devel-api/adaptor-framework/key-devel.h>
29
30 // INTERNAL INCLUDES
31 #include <dali-toolkit/public-api/controls/text-controls/placeholder-properties.h>
32 #include <dali-toolkit/internal/text/bidirectional-support.h>
33 #include <dali-toolkit/internal/text/character-set-conversion.h>
34 #include <dali-toolkit/internal/text/layouts/layout-parameters.h>
35 #include <dali-toolkit/internal/text/markup-processor.h>
36 #include <dali-toolkit/internal/text/multi-language-support.h>
37 #include <dali-toolkit/internal/text/text-controller-impl.h>
38 #include <dali-toolkit/internal/text/text-editable-control-interface.h>
39 #include <dali-toolkit/internal/text/text-font-style.h>
40
41 namespace
42 {
43
44 #if defined(DEBUG_ENABLED)
45   Debug::Filter* gLogFilter = Debug::Filter::New(Debug::NoLogging, true, "LOG_TEXT_CONTROLS");
46 #endif
47
48 const float MAX_FLOAT = std::numeric_limits<float>::max();
49
50 const std::string EMPTY_STRING("");
51
52 const std::string KEY_C_NAME = "c";
53 const std::string KEY_V_NAME = "v";
54 const std::string KEY_X_NAME = "x";
55
56 const char * const PLACEHOLDER_TEXT = "text";
57 const char * const PLACEHOLDER_TEXT_FOCUSED = "textFocused";
58 const char * const PLACEHOLDER_COLOR = "color";
59 const char * const PLACEHOLDER_FONT_FAMILY = "fontFamily";
60 const char * const PLACEHOLDER_FONT_STYLE = "fontStyle";
61 const char * const PLACEHOLDER_POINT_SIZE = "pointSize";
62 const char * const PLACEHOLDER_PIXEL_SIZE = "pixelSize";
63 const char * const PLACEHOLDER_ELLIPSIS = "ellipsis";
64
65 float ConvertToEven( float value )
66 {
67   int intValue(static_cast<int>( value ));
68   return static_cast<float>(intValue % 2 == 0) ? intValue : (intValue + 1);
69 }
70
71 } // namespace
72
73 namespace Dali
74 {
75
76 namespace Toolkit
77 {
78
79 namespace Text
80 {
81
82 /**
83  * @brief Adds a new font description run for the selected text.
84  *
85  * The new font parameters are added after the call to this method.
86  *
87  * @param[in] eventData The event data pointer.
88  * @param[in] logicalModel The logical model where to add the new font description run.
89  * @param[out] startOfSelectedText Index to the first selected character.
90  * @param[out] lengthOfSelectedText Number of selected characters.
91  */
92 FontDescriptionRun& UpdateSelectionFontStyleRun( EventData* eventData,
93                                                  LogicalModelPtr logicalModel,
94                                                  CharacterIndex& startOfSelectedText,
95                                                  Length& lengthOfSelectedText )
96 {
97   const bool handlesCrossed = eventData->mLeftSelectionPosition > eventData->mRightSelectionPosition;
98
99   // Get start and end position of selection
100   startOfSelectedText = handlesCrossed ? eventData->mRightSelectionPosition : eventData->mLeftSelectionPosition;
101   lengthOfSelectedText = ( handlesCrossed ? eventData->mLeftSelectionPosition : eventData->mRightSelectionPosition ) - startOfSelectedText;
102
103   // Add the font run.
104   const VectorBase::SizeType numberOfRuns = logicalModel->mFontDescriptionRuns.Count();
105   logicalModel->mFontDescriptionRuns.Resize( numberOfRuns + 1u );
106
107   FontDescriptionRun& fontDescriptionRun = *( logicalModel->mFontDescriptionRuns.Begin() + numberOfRuns );
108
109   fontDescriptionRun.characterRun.characterIndex = startOfSelectedText;
110   fontDescriptionRun.characterRun.numberOfCharacters = lengthOfSelectedText;
111
112   // Recalculate the selection highlight as the metrics may have changed.
113   eventData->mUpdateLeftSelectionPosition = true;
114   eventData->mUpdateRightSelectionPosition = true;
115   eventData->mUpdateHighlightBox = true;
116
117   return fontDescriptionRun;
118 }
119
120 // public : Constructor.
121
122 ControllerPtr Controller::New()
123 {
124   return ControllerPtr( new Controller() );
125 }
126
127 ControllerPtr Controller::New( ControlInterface* controlInterface )
128 {
129   return ControllerPtr( new Controller( controlInterface ) );
130 }
131
132 ControllerPtr Controller::New( ControlInterface* controlInterface,
133                                EditableControlInterface* editableControlInterface )
134 {
135   return ControllerPtr( new Controller( controlInterface,
136                                         editableControlInterface ) );
137 }
138
139 // public : Configure the text controller.
140
141 void Controller::EnableTextInput( DecoratorPtr decorator, InputMethodContext& inputMethodContext )
142 {
143   if( !decorator )
144   {
145     delete mImpl->mEventData;
146     mImpl->mEventData = NULL;
147
148     // Nothing else to do.
149     return;
150   }
151
152   if( NULL == mImpl->mEventData )
153   {
154     mImpl->mEventData = new EventData( decorator, inputMethodContext );
155   }
156 }
157
158 void Controller::SetGlyphType( TextAbstraction::GlyphType glyphType )
159 {
160   // Metrics for bitmap & vector based glyphs are different
161   mImpl->mMetrics->SetGlyphType( glyphType );
162
163   // Clear the font-specific data
164   ClearFontData();
165
166   mImpl->RequestRelayout();
167 }
168
169 void Controller::SetMarkupProcessorEnabled( bool enable )
170 {
171   if( enable != mImpl->mMarkupProcessorEnabled )
172   {
173     //If Text was already set, call the SetText again for enabling or disabling markup
174     mImpl->mMarkupProcessorEnabled = enable;
175     std::string text;
176     GetText( text );
177     SetText( text );
178   }
179 }
180
181 bool Controller::IsMarkupProcessorEnabled() const
182 {
183   return mImpl->mMarkupProcessorEnabled;
184 }
185
186 void Controller::SetAutoScrollEnabled( bool enable )
187 {
188   DALI_LOG_INFO( gLogFilter, Debug::General, "Controller::SetAutoScrollEnabled[%s] SingleBox[%s]-> [%p]\n", (enable)?"true":"false", ( mImpl->mLayoutEngine.GetLayout() == Layout::Engine::SINGLE_LINE_BOX)?"true":"false", this );
189
190   if( mImpl->mLayoutEngine.GetLayout() == Layout::Engine::SINGLE_LINE_BOX )
191   {
192     if( enable )
193     {
194       DALI_LOG_INFO( gLogFilter, Debug::General, "Controller::SetAutoScrollEnabled for SINGLE_LINE_BOX\n" );
195       mImpl->mOperationsPending = static_cast<OperationsMask>( mImpl->mOperationsPending |
196                                                                LAYOUT                    |
197                                                                ALIGN                     |
198                                                                UPDATE_LAYOUT_SIZE        |
199                                                                UPDATE_DIRECTION          |
200                                                                REORDER );
201
202     }
203     else
204     {
205       DALI_LOG_INFO( gLogFilter, Debug::General, "Controller::SetAutoScrollEnabled Disabling autoscroll\n");
206       mImpl->mOperationsPending = static_cast<OperationsMask>( mImpl->mOperationsPending |
207                                                                LAYOUT                    |
208                                                                ALIGN                     |
209                                                                UPDATE_LAYOUT_SIZE        |
210                                                                REORDER );
211     }
212
213     mImpl->mIsAutoScrollEnabled = enable;
214     mImpl->RequestRelayout();
215   }
216   else
217   {
218     DALI_LOG_WARNING( "Attempted AutoScrolling on a non SINGLE_LINE_BOX, request ignored\n" );
219     mImpl->mIsAutoScrollEnabled = false;
220   }
221 }
222
223 bool Controller::IsAutoScrollEnabled() const
224 {
225   DALI_LOG_INFO( gLogFilter, Debug::Verbose, "Controller::IsAutoScrollEnabled[%s]\n", mImpl->mIsAutoScrollEnabled?"true":"false" );
226
227   return mImpl->mIsAutoScrollEnabled;
228 }
229
230 CharacterDirection Controller::GetAutoScrollDirection() const
231 {
232   return mImpl->mIsTextDirectionRTL;
233 }
234
235 float Controller::GetAutoScrollLineAlignment() const
236 {
237   float offset = 0.f;
238
239   if( mImpl->mModel->mVisualModel &&
240       ( 0u != mImpl->mModel->mVisualModel->mLines.Count() ) )
241   {
242     offset = ( *mImpl->mModel->mVisualModel->mLines.Begin() ).alignmentOffset;
243   }
244
245   return offset;
246 }
247
248 void Controller::SetHorizontalScrollEnabled( bool enable )
249 {
250   if( ( NULL != mImpl->mEventData ) &&
251       mImpl->mEventData->mDecorator )
252   {
253     mImpl->mEventData->mDecorator->SetHorizontalScrollEnabled( enable );
254   }
255 }
256 bool Controller::IsHorizontalScrollEnabled() const
257 {
258   if( ( NULL != mImpl->mEventData ) &&
259       mImpl->mEventData->mDecorator )
260   {
261     return mImpl->mEventData->mDecorator->IsHorizontalScrollEnabled();
262   }
263
264   return false;
265 }
266
267 void Controller::SetVerticalScrollEnabled( bool enable )
268 {
269   if( ( NULL != mImpl->mEventData ) &&
270       mImpl->mEventData->mDecorator )
271   {
272     if( mImpl->mEventData->mDecorator )
273     {
274       mImpl->mEventData->mDecorator->SetVerticalScrollEnabled( enable );
275     }
276   }
277 }
278
279 bool Controller::IsVerticalScrollEnabled() const
280 {
281   if( ( NULL != mImpl->mEventData ) &&
282       mImpl->mEventData->mDecorator )
283   {
284     return mImpl->mEventData->mDecorator->IsVerticalScrollEnabled();
285   }
286
287   return false;
288 }
289
290 void Controller::SetSmoothHandlePanEnabled( bool enable )
291 {
292   if( ( NULL != mImpl->mEventData ) &&
293       mImpl->mEventData->mDecorator )
294   {
295     mImpl->mEventData->mDecorator->SetSmoothHandlePanEnabled( enable );
296   }
297 }
298
299 bool Controller::IsSmoothHandlePanEnabled() const
300 {
301   if( ( NULL != mImpl->mEventData ) &&
302       mImpl->mEventData->mDecorator )
303   {
304     return mImpl->mEventData->mDecorator->IsSmoothHandlePanEnabled();
305   }
306
307   return false;
308 }
309
310 void Controller::SetMaximumNumberOfCharacters( Length maxCharacters )
311 {
312   mImpl->mMaximumNumberOfCharacters = maxCharacters;
313 }
314
315 int Controller::GetMaximumNumberOfCharacters()
316 {
317   return mImpl->mMaximumNumberOfCharacters;
318 }
319
320 void Controller::SetEnableCursorBlink( bool enable )
321 {
322   DALI_ASSERT_DEBUG( NULL != mImpl->mEventData && "TextInput disabled" );
323
324   if( NULL != mImpl->mEventData )
325   {
326     mImpl->mEventData->mCursorBlinkEnabled = enable;
327
328     if( !enable &&
329         mImpl->mEventData->mDecorator )
330     {
331       mImpl->mEventData->mDecorator->StopCursorBlink();
332     }
333   }
334 }
335
336 bool Controller::GetEnableCursorBlink() const
337 {
338   if( NULL != mImpl->mEventData )
339   {
340     return mImpl->mEventData->mCursorBlinkEnabled;
341   }
342
343   return false;
344 }
345
346 void Controller::SetMultiLineEnabled( bool enable )
347 {
348   const Layout::Engine::Type layout = enable ? Layout::Engine::MULTI_LINE_BOX : Layout::Engine::SINGLE_LINE_BOX;
349
350   if( layout != mImpl->mLayoutEngine.GetLayout() )
351   {
352     // Set the layout type.
353     mImpl->mLayoutEngine.SetLayout( layout );
354
355     // Set the flags to redo the layout operations
356     const OperationsMask layoutOperations =  static_cast<OperationsMask>( LAYOUT             |
357                                                                           UPDATE_LAYOUT_SIZE |
358                                                                           ALIGN              |
359                                                                           REORDER );
360
361     mImpl->mTextUpdateInfo.mFullRelayoutNeeded = true;
362     mImpl->mOperationsPending = static_cast<OperationsMask>( mImpl->mOperationsPending | layoutOperations );
363
364     mImpl->RequestRelayout();
365   }
366 }
367
368 bool Controller::IsMultiLineEnabled() const
369 {
370   return Layout::Engine::MULTI_LINE_BOX == mImpl->mLayoutEngine.GetLayout();
371 }
372
373 void Controller::SetHorizontalAlignment( Text::HorizontalAlignment::Type alignment )
374 {
375   if( alignment != mImpl->mModel->mHorizontalAlignment )
376   {
377     // Set the alignment.
378     mImpl->mModel->mHorizontalAlignment = alignment;
379
380     // Set the flag to redo the alignment operation.
381     mImpl->mOperationsPending = static_cast<OperationsMask>( mImpl->mOperationsPending | ALIGN );
382
383     mImpl->RequestRelayout();
384   }
385 }
386
387 Text::HorizontalAlignment::Type Controller::GetHorizontalAlignment() const
388 {
389   return mImpl->mModel->mHorizontalAlignment;
390 }
391
392 void Controller::SetVerticalAlignment( VerticalAlignment::Type alignment )
393 {
394   if( alignment != mImpl->mModel->mVerticalAlignment )
395   {
396     // Set the alignment.
397     mImpl->mModel->mVerticalAlignment = alignment;
398
399     mImpl->mOperationsPending = static_cast<OperationsMask>( mImpl->mOperationsPending | ALIGN );
400
401     mImpl->RequestRelayout();
402   }
403 }
404
405 VerticalAlignment::Type Controller::GetVerticalAlignment() const
406 {
407   return mImpl->mModel->mVerticalAlignment;
408 }
409
410 bool Controller::IsIgnoreSpacesAfterText() const
411 {
412   return mImpl->mModel->mIgnoreSpacesAfterText;
413 }
414
415 void Controller::SetIgnoreSpacesAfterText( bool ignore )
416 {
417   mImpl->mModel->mIgnoreSpacesAfterText = ignore;
418 }
419
420 bool Controller::IsMatchSystemLanguageDirection() const
421 {
422   return mImpl->mModel->mMatchSystemLanguageDirection;
423 }
424
425 void Controller::SetMatchSystemLanguageDirection( bool match )
426 {
427   mImpl->mModel->mMatchSystemLanguageDirection = match;
428 }
429
430 void Controller::SetLayoutDirection( Dali::LayoutDirection::Type layoutDirection )
431 {
432   mImpl->mLayoutDirection = layoutDirection;
433 }
434
435
436 void Controller::SetLineWrapMode( Text::LineWrap::Mode lineWrapMode )
437 {
438   if( lineWrapMode != mImpl->mModel->mLineWrapMode )
439   {
440     // Set the text wrap mode.
441     mImpl->mModel->mLineWrapMode = lineWrapMode;
442
443
444     // Update Text layout for applying wrap mode
445     mImpl->mOperationsPending = static_cast<OperationsMask>( mImpl->mOperationsPending |
446                                                              ALIGN                     |
447                                                              LAYOUT                    |
448                                                              UPDATE_LAYOUT_SIZE        |
449                                                              REORDER                   );
450     mImpl->mTextUpdateInfo.mCharacterIndex = 0u;
451     mImpl->mTextUpdateInfo.mNumberOfCharactersToRemove = mImpl->mTextUpdateInfo.mPreviousNumberOfCharacters;
452     mImpl->mTextUpdateInfo.mNumberOfCharactersToAdd = mImpl->mModel->mLogicalModel->mText.Count();
453
454     // Request relayout
455     mImpl->RequestRelayout();
456   }
457 }
458
459 Text::LineWrap::Mode Controller::GetLineWrapMode() const
460 {
461   return mImpl->mModel->mLineWrapMode;
462 }
463
464 void Controller::SetTextElideEnabled( bool enabled )
465 {
466   mImpl->mModel->mElideEnabled = enabled;
467 }
468
469 bool Controller::IsTextElideEnabled() const
470 {
471   return mImpl->mModel->mElideEnabled;
472 }
473
474 void Controller::SetPlaceholderTextElideEnabled( bool enabled )
475 {
476   mImpl->mEventData->mIsPlaceholderElideEnabled = enabled;
477   mImpl->mEventData->mPlaceholderEllipsisFlag = true;
478
479   // Update placeholder if there is no text
480   if( mImpl->IsShowingPlaceholderText() ||
481       ( 0u == mImpl->mModel->mLogicalModel->mText.Count() ) )
482   {
483     ShowPlaceholderText();
484   }
485 }
486
487 bool Controller::IsPlaceholderTextElideEnabled() const
488 {
489   return mImpl->mEventData->mIsPlaceholderElideEnabled;
490 }
491
492 void Controller::SetSelectionEnabled( bool enabled )
493 {
494   mImpl->mEventData->mSelectionEnabled = enabled;
495 }
496
497 bool Controller::IsSelectionEnabled() const
498 {
499   return mImpl->mEventData->mSelectionEnabled;
500 }
501
502 void Controller::SetShiftSelectionEnabled( bool enabled )
503 {
504   mImpl->mEventData->mShiftSelectionFlag = enabled;
505 }
506
507 bool Controller::IsShiftSelectionEnabled() const
508 {
509   return mImpl->mEventData->mShiftSelectionFlag;
510 }
511
512 void Controller::SetGrabHandleEnabled( bool enabled )
513 {
514   mImpl->mEventData->mGrabHandleEnabled = enabled;
515 }
516
517 bool Controller::IsGrabHandleEnabled() const
518 {
519   return mImpl->mEventData->mGrabHandleEnabled;
520 }
521
522 // public : Update
523
524 void Controller::SetText( const std::string& text )
525 {
526   DALI_LOG_INFO( gLogFilter, Debug::Verbose, "Controller::SetText\n" );
527
528   // Reset keyboard as text changed
529   mImpl->ResetInputMethodContext();
530
531   // Remove the previously set text and style.
532   ResetText();
533
534   // Remove the style.
535   ClearStyleData();
536
537   CharacterIndex lastCursorIndex = 0u;
538
539   if( NULL != mImpl->mEventData )
540   {
541     // If popup shown then hide it by switching to Editing state
542     if( ( EventData::SELECTING == mImpl->mEventData->mState )          ||
543         ( EventData::EDITING_WITH_POPUP == mImpl->mEventData->mState ) ||
544         ( EventData::EDITING_WITH_GRAB_HANDLE == mImpl->mEventData->mState ) ||
545         ( EventData::EDITING_WITH_PASTE_POPUP == mImpl->mEventData->mState ) )
546     {
547       mImpl->ChangeState( EventData::EDITING );
548     }
549   }
550
551   if( !text.empty() )
552   {
553     mImpl->mModel->mVisualModel->SetTextColor( mImpl->mTextColor );
554
555     MarkupProcessData markupProcessData( mImpl->mModel->mLogicalModel->mColorRuns,
556                                          mImpl->mModel->mLogicalModel->mFontDescriptionRuns );
557
558     Length textSize = 0u;
559     const uint8_t* utf8 = NULL;
560     if( mImpl->mMarkupProcessorEnabled )
561     {
562       ProcessMarkupString( text, markupProcessData );
563       textSize = markupProcessData.markupProcessedText.size();
564
565       // This is a bit horrible but std::string returns a (signed) char*
566       utf8 = reinterpret_cast<const uint8_t*>( markupProcessData.markupProcessedText.c_str() );
567     }
568     else
569     {
570       textSize = text.size();
571
572       // This is a bit horrible but std::string returns a (signed) char*
573       utf8 = reinterpret_cast<const uint8_t*>( text.c_str() );
574     }
575
576     //  Convert text into UTF-32
577     Vector<Character>& utf32Characters = mImpl->mModel->mLogicalModel->mText;
578     utf32Characters.Resize( textSize );
579
580     // Transform a text array encoded in utf8 into an array encoded in utf32.
581     // It returns the actual number of characters.
582     Length characterCount = Utf8ToUtf32( utf8, textSize, utf32Characters.Begin() );
583     utf32Characters.Resize( characterCount );
584
585     DALI_ASSERT_DEBUG( textSize >= characterCount && "Invalid UTF32 conversion length" );
586     DALI_LOG_INFO( gLogFilter, Debug::Verbose, "Controller::SetText %p UTF8 size %d, UTF32 size %d\n", this, textSize, mImpl->mModel->mLogicalModel->mText.Count() );
587
588     // The characters to be added.
589     mImpl->mTextUpdateInfo.mNumberOfCharactersToAdd = mImpl->mModel->mLogicalModel->mText.Count();
590
591     // To reset the cursor position
592     lastCursorIndex = characterCount;
593
594     // Update the rest of the model during size negotiation
595     mImpl->QueueModifyEvent( ModifyEvent::TEXT_REPLACED );
596
597     // The natural size needs to be re-calculated.
598     mImpl->mRecalculateNaturalSize = true;
599
600     // The text direction needs to be updated.
601     mImpl->mUpdateTextDirection = true;
602
603     // Apply modifications to the model
604     mImpl->mOperationsPending = ALL_OPERATIONS;
605   }
606   else
607   {
608     ShowPlaceholderText();
609   }
610
611   // Resets the cursor position.
612   ResetCursorPosition( lastCursorIndex );
613
614   // Scrolls the text to make the cursor visible.
615   ResetScrollPosition();
616
617   mImpl->RequestRelayout();
618
619   if( NULL != mImpl->mEventData )
620   {
621     // Cancel previously queued events
622     mImpl->mEventData->mEventQueue.clear();
623   }
624
625   // Do this last since it provides callbacks into application code.
626   if( NULL != mImpl->mEditableControlInterface )
627   {
628     mImpl->mEditableControlInterface->TextChanged();
629   }
630 }
631
632 void Controller::GetText( std::string& text ) const
633 {
634   if( !mImpl->IsShowingPlaceholderText() )
635   {
636     // Retrieves the text string.
637     mImpl->GetText( 0u, text );
638   }
639   else
640   {
641     DALI_LOG_INFO( gLogFilter, Debug::Verbose, "Controller::GetText %p empty (but showing placeholder)\n", this );
642   }
643 }
644
645 void Controller::SetPlaceholderText( PlaceholderType type, const std::string& text )
646 {
647   if( NULL != mImpl->mEventData )
648   {
649     if( PLACEHOLDER_TYPE_INACTIVE == type )
650     {
651       mImpl->mEventData->mPlaceholderTextInactive = text;
652     }
653     else
654     {
655       mImpl->mEventData->mPlaceholderTextActive = text;
656     }
657
658     // Update placeholder if there is no text
659     if( mImpl->IsShowingPlaceholderText() ||
660         ( 0u == mImpl->mModel->mLogicalModel->mText.Count() ) )
661     {
662       ShowPlaceholderText();
663     }
664   }
665 }
666
667 void Controller::GetPlaceholderText( PlaceholderType type, std::string& text ) const
668 {
669   if( NULL != mImpl->mEventData )
670   {
671     if( PLACEHOLDER_TYPE_INACTIVE == type )
672     {
673       text = mImpl->mEventData->mPlaceholderTextInactive;
674     }
675     else
676     {
677       text = mImpl->mEventData->mPlaceholderTextActive;
678     }
679   }
680 }
681
682 void Controller::UpdateAfterFontChange( const std::string& newDefaultFont )
683 {
684   DALI_LOG_INFO( gLogFilter, Debug::Verbose, "Controller::UpdateAfterFontChange\n");
685
686   if( !mImpl->mFontDefaults->familyDefined ) // If user defined font then should not update when system font changes
687   {
688     DALI_LOG_INFO( gLogFilter, Debug::Concise, "Controller::UpdateAfterFontChange newDefaultFont(%s)\n", newDefaultFont.c_str() );
689     mImpl->mFontDefaults->mFontDescription.family = newDefaultFont;
690
691     ClearFontData();
692
693     mImpl->RequestRelayout();
694   }
695 }
696
697 // public : Default style & Input style
698
699 void Controller::SetDefaultFontFamily( const std::string& defaultFontFamily )
700 {
701   if( NULL == mImpl->mFontDefaults )
702   {
703     mImpl->mFontDefaults = new FontDefaults();
704   }
705
706   mImpl->mFontDefaults->mFontDescription.family = defaultFontFamily;
707   DALI_LOG_INFO( gLogFilter, Debug::General, "Controller::SetDefaultFontFamily %s\n", defaultFontFamily.c_str());
708   mImpl->mFontDefaults->familyDefined = !defaultFontFamily.empty();
709
710   // Clear the font-specific data
711   ClearFontData();
712
713   mImpl->RequestRelayout();
714 }
715
716 const std::string& Controller::GetDefaultFontFamily() const
717 {
718   if( NULL != mImpl->mFontDefaults )
719   {
720     return mImpl->mFontDefaults->mFontDescription.family;
721   }
722
723   return EMPTY_STRING;
724 }
725
726 void Controller::SetPlaceholderFontFamily( const std::string& placeholderTextFontFamily )
727 {
728   if( NULL != mImpl->mEventData )
729   {
730     if( NULL == mImpl->mEventData->mPlaceholderFont )
731     {
732       mImpl->mEventData->mPlaceholderFont = new FontDefaults();
733     }
734
735     mImpl->mEventData->mPlaceholderFont->mFontDescription.family = placeholderTextFontFamily;
736     DALI_LOG_INFO( gLogFilter, Debug::General, "Controller::SetPlaceholderFontFamily %s\n", placeholderTextFontFamily.c_str());
737     mImpl->mEventData->mPlaceholderFont->familyDefined = !placeholderTextFontFamily.empty();
738
739     mImpl->RequestRelayout();
740   }
741 }
742
743 const std::string& Controller::GetPlaceholderFontFamily() const
744 {
745   if( ( NULL != mImpl->mEventData ) && ( NULL != mImpl->mEventData->mPlaceholderFont ) )
746   {
747     return mImpl->mEventData->mPlaceholderFont->mFontDescription.family;
748   }
749
750   return EMPTY_STRING;
751 }
752
753 void Controller::SetDefaultFontWeight( FontWeight weight )
754 {
755   if( NULL == mImpl->mFontDefaults )
756   {
757     mImpl->mFontDefaults = new FontDefaults();
758   }
759
760   mImpl->mFontDefaults->mFontDescription.weight = weight;
761   mImpl->mFontDefaults->weightDefined = true;
762
763   // Clear the font-specific data
764   ClearFontData();
765
766   mImpl->RequestRelayout();
767 }
768
769 bool Controller::IsDefaultFontWeightDefined() const
770 {
771   if( NULL != mImpl->mFontDefaults )
772   {
773     return mImpl->mFontDefaults->weightDefined;
774   }
775
776   return false;
777 }
778
779 FontWeight Controller::GetDefaultFontWeight() const
780 {
781   if( NULL != mImpl->mFontDefaults )
782   {
783     return mImpl->mFontDefaults->mFontDescription.weight;
784   }
785
786   return TextAbstraction::FontWeight::NORMAL;
787 }
788
789 void Controller::SetPlaceholderTextFontWeight( FontWeight weight )
790 {
791   if( NULL != mImpl->mEventData )
792   {
793     if( NULL == mImpl->mEventData->mPlaceholderFont )
794     {
795       mImpl->mEventData->mPlaceholderFont = new FontDefaults();
796     }
797
798     mImpl->mEventData->mPlaceholderFont->mFontDescription.weight = weight;
799     mImpl->mEventData->mPlaceholderFont->weightDefined = true;
800
801     mImpl->RequestRelayout();
802   }
803 }
804
805 bool Controller::IsPlaceholderTextFontWeightDefined() const
806 {
807   if( ( NULL != mImpl->mEventData ) && ( NULL != mImpl->mEventData->mPlaceholderFont ) )
808   {
809     return mImpl->mEventData->mPlaceholderFont->weightDefined;
810   }
811   return false;
812 }
813
814 FontWeight Controller::GetPlaceholderTextFontWeight() const
815 {
816   if( ( NULL != mImpl->mEventData ) && ( NULL != mImpl->mEventData->mPlaceholderFont ) )
817   {
818     return mImpl->mEventData->mPlaceholderFont->mFontDescription.weight;
819   }
820
821   return TextAbstraction::FontWeight::NORMAL;
822 }
823
824 void Controller::SetDefaultFontWidth( FontWidth width )
825 {
826   if( NULL == mImpl->mFontDefaults )
827   {
828     mImpl->mFontDefaults = new FontDefaults();
829   }
830
831   mImpl->mFontDefaults->mFontDescription.width = width;
832   mImpl->mFontDefaults->widthDefined = true;
833
834   // Clear the font-specific data
835   ClearFontData();
836
837   mImpl->RequestRelayout();
838 }
839
840 bool Controller::IsDefaultFontWidthDefined() const
841 {
842   if( NULL != mImpl->mFontDefaults )
843   {
844     return mImpl->mFontDefaults->widthDefined;
845   }
846
847   return false;
848 }
849
850 FontWidth Controller::GetDefaultFontWidth() const
851 {
852   if( NULL != mImpl->mFontDefaults )
853   {
854     return mImpl->mFontDefaults->mFontDescription.width;
855   }
856
857   return TextAbstraction::FontWidth::NORMAL;
858 }
859
860 void Controller::SetPlaceholderTextFontWidth( FontWidth width )
861 {
862   if( NULL != mImpl->mEventData )
863   {
864     if( NULL == mImpl->mEventData->mPlaceholderFont )
865     {
866       mImpl->mEventData->mPlaceholderFont = new FontDefaults();
867     }
868
869     mImpl->mEventData->mPlaceholderFont->mFontDescription.width = width;
870     mImpl->mEventData->mPlaceholderFont->widthDefined = true;
871
872     mImpl->RequestRelayout();
873   }
874 }
875
876 bool Controller::IsPlaceholderTextFontWidthDefined() const
877 {
878   if( ( NULL != mImpl->mEventData ) && ( NULL != mImpl->mEventData->mPlaceholderFont ) )
879   {
880     return mImpl->mEventData->mPlaceholderFont->widthDefined;
881   }
882   return false;
883 }
884
885 FontWidth Controller::GetPlaceholderTextFontWidth() const
886 {
887   if( ( NULL != mImpl->mEventData ) && ( NULL != mImpl->mEventData->mPlaceholderFont ) )
888   {
889     return mImpl->mEventData->mPlaceholderFont->mFontDescription.width;
890   }
891
892   return TextAbstraction::FontWidth::NORMAL;
893 }
894
895 void Controller::SetDefaultFontSlant( FontSlant slant )
896 {
897   if( NULL == mImpl->mFontDefaults )
898   {
899     mImpl->mFontDefaults = new FontDefaults();
900   }
901
902   mImpl->mFontDefaults->mFontDescription.slant = slant;
903   mImpl->mFontDefaults->slantDefined = true;
904
905   // Clear the font-specific data
906   ClearFontData();
907
908   mImpl->RequestRelayout();
909 }
910
911 bool Controller::IsDefaultFontSlantDefined() const
912 {
913   if( NULL != mImpl->mFontDefaults )
914   {
915     return mImpl->mFontDefaults->slantDefined;
916   }
917   return false;
918 }
919
920 FontSlant Controller::GetDefaultFontSlant() const
921 {
922   if( NULL != mImpl->mFontDefaults )
923   {
924     return mImpl->mFontDefaults->mFontDescription.slant;
925   }
926
927   return TextAbstraction::FontSlant::NORMAL;
928 }
929
930 void Controller::SetPlaceholderTextFontSlant( FontSlant slant )
931 {
932   if( NULL != mImpl->mEventData )
933   {
934     if( NULL == mImpl->mEventData->mPlaceholderFont )
935     {
936       mImpl->mEventData->mPlaceholderFont = new FontDefaults();
937     }
938
939     mImpl->mEventData->mPlaceholderFont->mFontDescription.slant = slant;
940     mImpl->mEventData->mPlaceholderFont->slantDefined = true;
941
942     mImpl->RequestRelayout();
943   }
944 }
945
946 bool Controller::IsPlaceholderTextFontSlantDefined() const
947 {
948   if( ( NULL != mImpl->mEventData ) && ( NULL != mImpl->mEventData->mPlaceholderFont ) )
949   {
950     return mImpl->mEventData->mPlaceholderFont->slantDefined;
951   }
952   return false;
953 }
954
955 FontSlant Controller::GetPlaceholderTextFontSlant() const
956 {
957   if( ( NULL != mImpl->mEventData ) && ( NULL != mImpl->mEventData->mPlaceholderFont ) )
958   {
959     return mImpl->mEventData->mPlaceholderFont->mFontDescription.slant;
960   }
961
962   return TextAbstraction::FontSlant::NORMAL;
963 }
964
965 void Controller::SetDefaultFontSize( float fontSize, FontSizeType type )
966 {
967   if( NULL == mImpl->mFontDefaults )
968   {
969     mImpl->mFontDefaults = new FontDefaults();
970   }
971
972   switch( type )
973   {
974     case POINT_SIZE:
975     {
976       mImpl->mFontDefaults->mDefaultPointSize = fontSize;
977       mImpl->mFontDefaults->sizeDefined = true;
978       break;
979     }
980     case PIXEL_SIZE:
981     {
982       // Point size = Pixel size * 72.f / DPI
983       unsigned int horizontalDpi = 0u;
984       unsigned int verticalDpi = 0u;
985       TextAbstraction::FontClient fontClient = TextAbstraction::FontClient::Get();
986       fontClient.GetDpi( horizontalDpi, verticalDpi );
987
988       mImpl->mFontDefaults->mDefaultPointSize = ( fontSize * 72.f ) / static_cast< float >( horizontalDpi );
989       mImpl->mFontDefaults->sizeDefined = true;
990       break;
991     }
992   }
993
994   // Clear the font-specific data
995   ClearFontData();
996
997   mImpl->RequestRelayout();
998 }
999
1000 float Controller::GetDefaultFontSize( FontSizeType type ) const
1001 {
1002   float value = 0.0f;
1003   if( NULL != mImpl->mFontDefaults )
1004   {
1005     switch( type )
1006     {
1007       case POINT_SIZE:
1008       {
1009         value = mImpl->mFontDefaults->mDefaultPointSize;
1010         break;
1011       }
1012       case PIXEL_SIZE:
1013       {
1014         // Pixel size = Point size * DPI / 72.f
1015         unsigned int horizontalDpi = 0u;
1016         unsigned int verticalDpi = 0u;
1017         TextAbstraction::FontClient fontClient = TextAbstraction::FontClient::Get();
1018         fontClient.GetDpi( horizontalDpi, verticalDpi );
1019
1020         value = mImpl->mFontDefaults->mDefaultPointSize * static_cast< float >( horizontalDpi ) / 72.f;
1021         break;
1022       }
1023     }
1024     return value;
1025   }
1026
1027   return value;
1028 }
1029
1030 void Controller::SetPlaceholderTextFontSize( float fontSize, FontSizeType type )
1031 {
1032   if( NULL != mImpl->mEventData )
1033   {
1034     if( NULL == mImpl->mEventData->mPlaceholderFont )
1035     {
1036       mImpl->mEventData->mPlaceholderFont = new FontDefaults();
1037     }
1038
1039     switch( type )
1040     {
1041       case POINT_SIZE:
1042       {
1043         mImpl->mEventData->mPlaceholderFont->mDefaultPointSize = fontSize;
1044         mImpl->mEventData->mPlaceholderFont->sizeDefined = true;
1045         mImpl->mEventData->mIsPlaceholderPixelSize = false; // Font size flag
1046         break;
1047       }
1048       case PIXEL_SIZE:
1049       {
1050         // Point size = Pixel size * 72.f / DPI
1051         unsigned int horizontalDpi = 0u;
1052         unsigned int verticalDpi = 0u;
1053         TextAbstraction::FontClient fontClient = TextAbstraction::FontClient::Get();
1054         fontClient.GetDpi( horizontalDpi, verticalDpi );
1055
1056         mImpl->mEventData->mPlaceholderFont->mDefaultPointSize = ( fontSize * 72.f ) / static_cast< float >( horizontalDpi );
1057         mImpl->mEventData->mPlaceholderFont->sizeDefined = true;
1058         mImpl->mEventData->mIsPlaceholderPixelSize = true; // Font size flag
1059         break;
1060       }
1061     }
1062
1063     mImpl->RequestRelayout();
1064   }
1065 }
1066
1067 float Controller::GetPlaceholderTextFontSize( FontSizeType type ) const
1068 {
1069   float value = 0.0f;
1070   if( NULL != mImpl->mEventData )
1071   {
1072     switch( type )
1073     {
1074       case POINT_SIZE:
1075       {
1076         if( NULL != mImpl->mEventData->mPlaceholderFont )
1077         {
1078           value = mImpl->mEventData->mPlaceholderFont->mDefaultPointSize;
1079         }
1080         else
1081         {
1082           // If the placeholder text font size is not set, then return the default font size.
1083           value = GetDefaultFontSize( POINT_SIZE );
1084         }
1085         break;
1086       }
1087       case PIXEL_SIZE:
1088       {
1089         if( NULL != mImpl->mEventData->mPlaceholderFont )
1090         {
1091           // Pixel size = Point size * DPI / 72.f
1092           unsigned int horizontalDpi = 0u;
1093           unsigned int verticalDpi = 0u;
1094           TextAbstraction::FontClient fontClient = TextAbstraction::FontClient::Get();
1095           fontClient.GetDpi( horizontalDpi, verticalDpi );
1096
1097           value = mImpl->mEventData->mPlaceholderFont->mDefaultPointSize * static_cast< float >( horizontalDpi ) / 72.f;
1098         }
1099         else
1100         {
1101           // If the placeholder text font size is not set, then return the default font size.
1102           value = GetDefaultFontSize( PIXEL_SIZE );
1103         }
1104         break;
1105       }
1106     }
1107     return value;
1108   }
1109
1110   return value;
1111 }
1112
1113 void Controller::SetDefaultColor( const Vector4& color )
1114 {
1115   mImpl->mTextColor = color;
1116
1117   if( !mImpl->IsShowingPlaceholderText() )
1118   {
1119     mImpl->mModel->mVisualModel->SetTextColor( color );
1120
1121     mImpl->RequestRelayout();
1122   }
1123 }
1124
1125 const Vector4& Controller::GetDefaultColor() const
1126 {
1127   return mImpl->mTextColor;
1128 }
1129
1130 void Controller::SetPlaceholderTextColor( const Vector4& textColor )
1131 {
1132   if( NULL != mImpl->mEventData )
1133   {
1134     mImpl->mEventData->mPlaceholderTextColor = textColor;
1135   }
1136
1137   if( mImpl->IsShowingPlaceholderText() )
1138   {
1139     mImpl->mModel->mVisualModel->SetTextColor( textColor );
1140     mImpl->RequestRelayout();
1141   }
1142 }
1143
1144 const Vector4& Controller::GetPlaceholderTextColor() const
1145 {
1146   if( NULL != mImpl->mEventData )
1147   {
1148     return mImpl->mEventData->mPlaceholderTextColor;
1149   }
1150
1151   return Color::BLACK;
1152 }
1153
1154 void Controller::SetShadowOffset( const Vector2& shadowOffset )
1155 {
1156   mImpl->mModel->mVisualModel->SetShadowOffset( shadowOffset );
1157
1158   mImpl->RequestRelayout();
1159 }
1160
1161 const Vector2& Controller::GetShadowOffset() const
1162 {
1163   return mImpl->mModel->mVisualModel->GetShadowOffset();
1164 }
1165
1166 void Controller::SetShadowColor( const Vector4& shadowColor )
1167 {
1168   mImpl->mModel->mVisualModel->SetShadowColor( shadowColor );
1169
1170   mImpl->RequestRelayout();
1171 }
1172
1173 const Vector4& Controller::GetShadowColor() const
1174 {
1175   return mImpl->mModel->mVisualModel->GetShadowColor();
1176 }
1177
1178 void Controller::SetShadowBlurRadius( const float& shadowBlurRadius )
1179 {
1180   if ( fabsf( GetShadowBlurRadius() - shadowBlurRadius ) > Math::MACHINE_EPSILON_1 )
1181   {
1182     mImpl->mModel->mVisualModel->SetShadowBlurRadius( shadowBlurRadius );
1183
1184     mImpl->RequestRelayout();
1185   }
1186 }
1187
1188 const float& Controller::GetShadowBlurRadius() const
1189 {
1190   return mImpl->mModel->mVisualModel->GetShadowBlurRadius();
1191 }
1192
1193 void Controller::SetUnderlineColor( const Vector4& color )
1194 {
1195   mImpl->mModel->mVisualModel->SetUnderlineColor( color );
1196
1197   mImpl->RequestRelayout();
1198 }
1199
1200 const Vector4& Controller::GetUnderlineColor() const
1201 {
1202   return mImpl->mModel->mVisualModel->GetUnderlineColor();
1203 }
1204
1205 void Controller::SetUnderlineEnabled( bool enabled )
1206 {
1207   mImpl->mModel->mVisualModel->SetUnderlineEnabled( enabled );
1208
1209   mImpl->RequestRelayout();
1210 }
1211
1212 bool Controller::IsUnderlineEnabled() const
1213 {
1214   return mImpl->mModel->mVisualModel->IsUnderlineEnabled();
1215 }
1216
1217 void Controller::SetUnderlineHeight( float height )
1218 {
1219   mImpl->mModel->mVisualModel->SetUnderlineHeight( height );
1220
1221   mImpl->RequestRelayout();
1222 }
1223
1224 float Controller::GetUnderlineHeight() const
1225 {
1226   return mImpl->mModel->mVisualModel->GetUnderlineHeight();
1227 }
1228
1229 void Controller::SetOutlineColor( const Vector4& color )
1230 {
1231   mImpl->mModel->mVisualModel->SetOutlineColor( color );
1232
1233   mImpl->RequestRelayout();
1234 }
1235
1236 const Vector4& Controller::GetOutlineColor() const
1237 {
1238   return mImpl->mModel->mVisualModel->GetOutlineColor();
1239 }
1240
1241 void Controller::SetOutlineWidth( unsigned int width )
1242 {
1243   mImpl->mModel->mVisualModel->SetOutlineWidth( width );
1244
1245   mImpl->RequestRelayout();
1246 }
1247
1248 unsigned int Controller::GetOutlineWidth() const
1249 {
1250   return mImpl->mModel->mVisualModel->GetOutlineWidth();
1251 }
1252
1253 void Controller::SetBackgroundColor( const Vector4& color )
1254 {
1255   mImpl->mModel->mVisualModel->SetBackgroundColor( color );
1256
1257   mImpl->RequestRelayout();
1258 }
1259
1260 const Vector4& Controller::GetBackgroundColor() const
1261 {
1262   return mImpl->mModel->mVisualModel->GetBackgroundColor();
1263 }
1264
1265 void Controller::SetBackgroundEnabled( bool enabled )
1266 {
1267   mImpl->mModel->mVisualModel->SetBackgroundEnabled( enabled );
1268
1269   mImpl->RequestRelayout();
1270 }
1271
1272 bool Controller::IsBackgroundEnabled() const
1273 {
1274   return mImpl->mModel->mVisualModel->IsBackgroundEnabled();
1275 }
1276
1277 void Controller::SetDefaultEmbossProperties( const std::string& embossProperties )
1278 {
1279   if( NULL == mImpl->mEmbossDefaults )
1280   {
1281     mImpl->mEmbossDefaults = new EmbossDefaults();
1282   }
1283
1284   mImpl->mEmbossDefaults->properties = embossProperties;
1285 }
1286
1287 const std::string& Controller::GetDefaultEmbossProperties() const
1288 {
1289   if( NULL != mImpl->mEmbossDefaults )
1290   {
1291     return mImpl->mEmbossDefaults->properties;
1292   }
1293
1294   return EMPTY_STRING;
1295 }
1296
1297 void Controller::SetDefaultOutlineProperties( const std::string& outlineProperties )
1298 {
1299   if( NULL == mImpl->mOutlineDefaults )
1300   {
1301     mImpl->mOutlineDefaults = new OutlineDefaults();
1302   }
1303
1304   mImpl->mOutlineDefaults->properties = outlineProperties;
1305 }
1306
1307 const std::string& Controller::GetDefaultOutlineProperties() const
1308 {
1309   if( NULL != mImpl->mOutlineDefaults )
1310   {
1311     return mImpl->mOutlineDefaults->properties;
1312   }
1313
1314   return EMPTY_STRING;
1315 }
1316
1317 bool Controller::SetDefaultLineSpacing( float lineSpacing )
1318 {
1319   if( std::abs(lineSpacing - mImpl->mLayoutEngine.GetDefaultLineSpacing()) > Math::MACHINE_EPSILON_1000 )
1320   {
1321     mImpl->mLayoutEngine.SetDefaultLineSpacing(lineSpacing);
1322     mImpl->mRecalculateNaturalSize = true;
1323     return true;
1324   }
1325   return false;
1326 }
1327
1328 float Controller::GetDefaultLineSpacing() const
1329 {
1330   return mImpl->mLayoutEngine.GetDefaultLineSpacing();
1331 }
1332
1333 void Controller::SetInputColor( const Vector4& color )
1334 {
1335   if( NULL != mImpl->mEventData )
1336   {
1337     mImpl->mEventData->mInputStyle.textColor = color;
1338     mImpl->mEventData->mInputStyle.isDefaultColor = false;
1339
1340     if( EventData::SELECTING == mImpl->mEventData->mState )
1341     {
1342       const bool handlesCrossed = mImpl->mEventData->mLeftSelectionPosition > mImpl->mEventData->mRightSelectionPosition;
1343
1344       // Get start and end position of selection
1345       const CharacterIndex startOfSelectedText = handlesCrossed ? mImpl->mEventData->mRightSelectionPosition : mImpl->mEventData->mLeftSelectionPosition;
1346       const Length lengthOfSelectedText = ( handlesCrossed ? mImpl->mEventData->mLeftSelectionPosition : mImpl->mEventData->mRightSelectionPosition ) - startOfSelectedText;
1347
1348       // Add the color run.
1349       const VectorBase::SizeType numberOfRuns = mImpl->mModel->mLogicalModel->mColorRuns.Count();
1350       mImpl->mModel->mLogicalModel->mColorRuns.Resize( numberOfRuns + 1u );
1351
1352       ColorRun& colorRun = *( mImpl->mModel->mLogicalModel->mColorRuns.Begin() + numberOfRuns );
1353       colorRun.color = color;
1354       colorRun.characterRun.characterIndex = startOfSelectedText;
1355       colorRun.characterRun.numberOfCharacters = lengthOfSelectedText;
1356
1357       // Request to relayout.
1358       mImpl->mOperationsPending = static_cast<OperationsMask>( mImpl->mOperationsPending | COLOR );
1359       mImpl->RequestRelayout();
1360
1361       mImpl->mTextUpdateInfo.mCharacterIndex = startOfSelectedText;
1362       mImpl->mTextUpdateInfo.mNumberOfCharactersToRemove = lengthOfSelectedText;
1363       mImpl->mTextUpdateInfo.mNumberOfCharactersToAdd = lengthOfSelectedText;
1364     }
1365   }
1366 }
1367
1368 const Vector4& Controller::GetInputColor() const
1369 {
1370   if( NULL != mImpl->mEventData )
1371   {
1372     return mImpl->mEventData->mInputStyle.textColor;
1373   }
1374
1375   // Return the default text's color if there is no EventData.
1376   return mImpl->mTextColor;
1377
1378 }
1379
1380 void Controller::SetInputFontFamily( const std::string& fontFamily )
1381 {
1382   if( NULL != mImpl->mEventData )
1383   {
1384     mImpl->mEventData->mInputStyle.familyName = fontFamily;
1385     mImpl->mEventData->mInputStyle.isFamilyDefined = true;
1386
1387     if( EventData::SELECTING == mImpl->mEventData->mState )
1388     {
1389       CharacterIndex startOfSelectedText = 0u;
1390       Length lengthOfSelectedText = 0u;
1391       FontDescriptionRun& fontDescriptionRun = UpdateSelectionFontStyleRun( mImpl->mEventData,
1392                                                                             mImpl->mModel->mLogicalModel,
1393                                                                             startOfSelectedText,
1394                                                                             lengthOfSelectedText );
1395
1396       fontDescriptionRun.familyLength = fontFamily.size();
1397       fontDescriptionRun.familyName = new char[fontDescriptionRun.familyLength];
1398       memcpy( fontDescriptionRun.familyName, fontFamily.c_str(), fontDescriptionRun.familyLength );
1399       fontDescriptionRun.familyDefined = true;
1400
1401       // The memory allocated for the font family name is freed when the font description is removed from the logical model.
1402
1403       // Request to relayout.
1404       mImpl->mOperationsPending = static_cast<OperationsMask>( mImpl->mOperationsPending |
1405                                                                VALIDATE_FONTS            |
1406                                                                SHAPE_TEXT                |
1407                                                                GET_GLYPH_METRICS         |
1408                                                                LAYOUT                    |
1409                                                                UPDATE_LAYOUT_SIZE        |
1410                                                                REORDER                   |
1411                                                                ALIGN );
1412       mImpl->mRecalculateNaturalSize = true;
1413       mImpl->RequestRelayout();
1414
1415       mImpl->mTextUpdateInfo.mCharacterIndex = startOfSelectedText;
1416       mImpl->mTextUpdateInfo.mNumberOfCharactersToRemove = lengthOfSelectedText;
1417       mImpl->mTextUpdateInfo.mNumberOfCharactersToAdd = lengthOfSelectedText;
1418
1419       // As the font changes, recalculate the handle positions is needed.
1420       mImpl->mEventData->mUpdateLeftSelectionPosition = true;
1421       mImpl->mEventData->mUpdateRightSelectionPosition = true;
1422       mImpl->mEventData->mUpdateHighlightBox = true;
1423       mImpl->mEventData->mScrollAfterUpdatePosition = true;
1424     }
1425   }
1426 }
1427
1428 const std::string& Controller::GetInputFontFamily() const
1429 {
1430   if( NULL != mImpl->mEventData )
1431   {
1432     return mImpl->mEventData->mInputStyle.familyName;
1433   }
1434
1435   // Return the default font's family if there is no EventData.
1436   return GetDefaultFontFamily();
1437 }
1438
1439 void Controller::SetInputFontWeight( FontWeight weight )
1440 {
1441   if( NULL != mImpl->mEventData )
1442   {
1443     mImpl->mEventData->mInputStyle.weight = weight;
1444     mImpl->mEventData->mInputStyle.isWeightDefined = true;
1445
1446     if( EventData::SELECTING == mImpl->mEventData->mState )
1447     {
1448       CharacterIndex startOfSelectedText = 0u;
1449       Length lengthOfSelectedText = 0u;
1450       FontDescriptionRun& fontDescriptionRun = UpdateSelectionFontStyleRun( mImpl->mEventData,
1451                                                                             mImpl->mModel->mLogicalModel,
1452                                                                             startOfSelectedText,
1453                                                                             lengthOfSelectedText );
1454
1455       fontDescriptionRun.weight = weight;
1456       fontDescriptionRun.weightDefined = true;
1457
1458       // Request to relayout.
1459       mImpl->mOperationsPending = static_cast<OperationsMask>( mImpl->mOperationsPending |
1460                                                                VALIDATE_FONTS            |
1461                                                                SHAPE_TEXT                |
1462                                                                GET_GLYPH_METRICS         |
1463                                                                LAYOUT                    |
1464                                                                UPDATE_LAYOUT_SIZE        |
1465                                                                REORDER                   |
1466                                                                ALIGN );
1467       mImpl->mRecalculateNaturalSize = true;
1468       mImpl->RequestRelayout();
1469
1470       mImpl->mTextUpdateInfo.mCharacterIndex = startOfSelectedText;
1471       mImpl->mTextUpdateInfo.mNumberOfCharactersToRemove = lengthOfSelectedText;
1472       mImpl->mTextUpdateInfo.mNumberOfCharactersToAdd = lengthOfSelectedText;
1473
1474       // As the font might change, recalculate the handle positions is needed.
1475       mImpl->mEventData->mUpdateLeftSelectionPosition = true;
1476       mImpl->mEventData->mUpdateRightSelectionPosition = true;
1477       mImpl->mEventData->mUpdateHighlightBox = true;
1478       mImpl->mEventData->mScrollAfterUpdatePosition = true;
1479     }
1480   }
1481 }
1482
1483 bool Controller::IsInputFontWeightDefined() const
1484 {
1485   bool defined = false;
1486
1487   if( NULL != mImpl->mEventData )
1488   {
1489     defined = mImpl->mEventData->mInputStyle.isWeightDefined;
1490   }
1491
1492   return defined;
1493 }
1494
1495 FontWeight Controller::GetInputFontWeight() const
1496 {
1497   if( NULL != mImpl->mEventData )
1498   {
1499     return mImpl->mEventData->mInputStyle.weight;
1500   }
1501
1502   return GetDefaultFontWeight();
1503 }
1504
1505 void Controller::SetInputFontWidth( FontWidth width )
1506 {
1507   if( NULL != mImpl->mEventData )
1508   {
1509     mImpl->mEventData->mInputStyle.width = width;
1510     mImpl->mEventData->mInputStyle.isWidthDefined = true;
1511
1512     if( EventData::SELECTING == mImpl->mEventData->mState )
1513     {
1514       CharacterIndex startOfSelectedText = 0u;
1515       Length lengthOfSelectedText = 0u;
1516       FontDescriptionRun& fontDescriptionRun = UpdateSelectionFontStyleRun( mImpl->mEventData,
1517                                                                             mImpl->mModel->mLogicalModel,
1518                                                                             startOfSelectedText,
1519                                                                             lengthOfSelectedText );
1520
1521       fontDescriptionRun.width = width;
1522       fontDescriptionRun.widthDefined = true;
1523
1524       // Request to relayout.
1525       mImpl->mOperationsPending = static_cast<OperationsMask>( mImpl->mOperationsPending |
1526                                                                VALIDATE_FONTS            |
1527                                                                SHAPE_TEXT                |
1528                                                                GET_GLYPH_METRICS         |
1529                                                                LAYOUT                    |
1530                                                                UPDATE_LAYOUT_SIZE        |
1531                                                                REORDER                   |
1532                                                                ALIGN );
1533       mImpl->mRecalculateNaturalSize = true;
1534       mImpl->RequestRelayout();
1535
1536       mImpl->mTextUpdateInfo.mCharacterIndex = startOfSelectedText;
1537       mImpl->mTextUpdateInfo.mNumberOfCharactersToRemove = lengthOfSelectedText;
1538       mImpl->mTextUpdateInfo.mNumberOfCharactersToAdd = lengthOfSelectedText;
1539
1540       // As the font might change, recalculate the handle positions is needed.
1541       mImpl->mEventData->mUpdateLeftSelectionPosition = true;
1542       mImpl->mEventData->mUpdateRightSelectionPosition = true;
1543       mImpl->mEventData->mUpdateHighlightBox = true;
1544       mImpl->mEventData->mScrollAfterUpdatePosition = true;
1545     }
1546   }
1547 }
1548
1549 bool Controller::IsInputFontWidthDefined() const
1550 {
1551   bool defined = false;
1552
1553   if( NULL != mImpl->mEventData )
1554   {
1555     defined = mImpl->mEventData->mInputStyle.isWidthDefined;
1556   }
1557
1558   return defined;
1559 }
1560
1561 FontWidth Controller::GetInputFontWidth() const
1562 {
1563   if( NULL != mImpl->mEventData )
1564   {
1565     return mImpl->mEventData->mInputStyle.width;
1566   }
1567
1568   return GetDefaultFontWidth();
1569 }
1570
1571 void Controller::SetInputFontSlant( FontSlant slant )
1572 {
1573   if( NULL != mImpl->mEventData )
1574   {
1575     mImpl->mEventData->mInputStyle.slant = slant;
1576     mImpl->mEventData->mInputStyle.isSlantDefined = true;
1577
1578     if( EventData::SELECTING == mImpl->mEventData->mState )
1579     {
1580       CharacterIndex startOfSelectedText = 0u;
1581       Length lengthOfSelectedText = 0u;
1582       FontDescriptionRun& fontDescriptionRun = UpdateSelectionFontStyleRun( mImpl->mEventData,
1583                                                                             mImpl->mModel->mLogicalModel,
1584                                                                             startOfSelectedText,
1585                                                                             lengthOfSelectedText );
1586
1587       fontDescriptionRun.slant = slant;
1588       fontDescriptionRun.slantDefined = true;
1589
1590       // Request to relayout.
1591       mImpl->mOperationsPending = static_cast<OperationsMask>( mImpl->mOperationsPending |
1592                                                                VALIDATE_FONTS            |
1593                                                                SHAPE_TEXT                |
1594                                                                GET_GLYPH_METRICS         |
1595                                                                LAYOUT                    |
1596                                                                UPDATE_LAYOUT_SIZE        |
1597                                                                REORDER                   |
1598                                                                ALIGN );
1599       mImpl->mRecalculateNaturalSize = true;
1600       mImpl->RequestRelayout();
1601
1602       mImpl->mTextUpdateInfo.mCharacterIndex = startOfSelectedText;
1603       mImpl->mTextUpdateInfo.mNumberOfCharactersToRemove = lengthOfSelectedText;
1604       mImpl->mTextUpdateInfo.mNumberOfCharactersToAdd = lengthOfSelectedText;
1605
1606       // As the font might change, recalculate the handle positions is needed.
1607       mImpl->mEventData->mUpdateLeftSelectionPosition = true;
1608       mImpl->mEventData->mUpdateRightSelectionPosition = true;
1609       mImpl->mEventData->mUpdateHighlightBox = true;
1610       mImpl->mEventData->mScrollAfterUpdatePosition = true;
1611     }
1612   }
1613 }
1614
1615 bool Controller::IsInputFontSlantDefined() const
1616 {
1617   bool defined = false;
1618
1619   if( NULL != mImpl->mEventData )
1620   {
1621     defined = mImpl->mEventData->mInputStyle.isSlantDefined;
1622   }
1623
1624   return defined;
1625 }
1626
1627 FontSlant Controller::GetInputFontSlant() const
1628 {
1629   if( NULL != mImpl->mEventData )
1630   {
1631     return mImpl->mEventData->mInputStyle.slant;
1632   }
1633
1634   return GetDefaultFontSlant();
1635 }
1636
1637 void Controller::SetInputFontPointSize( float size )
1638 {
1639   if( NULL != mImpl->mEventData )
1640   {
1641     mImpl->mEventData->mInputStyle.size = size;
1642     mImpl->mEventData->mInputStyle.isSizeDefined = true;
1643
1644     if( EventData::SELECTING == mImpl->mEventData->mState )
1645     {
1646       CharacterIndex startOfSelectedText = 0u;
1647       Length lengthOfSelectedText = 0u;
1648       FontDescriptionRun& fontDescriptionRun = UpdateSelectionFontStyleRun( mImpl->mEventData,
1649                                                                             mImpl->mModel->mLogicalModel,
1650                                                                             startOfSelectedText,
1651                                                                             lengthOfSelectedText );
1652
1653       fontDescriptionRun.size = static_cast<PointSize26Dot6>( size * 64.f );
1654       fontDescriptionRun.sizeDefined = true;
1655
1656       // Request to relayout.
1657       mImpl->mOperationsPending = static_cast<OperationsMask>( mImpl->mOperationsPending |
1658                                                                VALIDATE_FONTS            |
1659                                                                SHAPE_TEXT                |
1660                                                                GET_GLYPH_METRICS         |
1661                                                                LAYOUT                    |
1662                                                                UPDATE_LAYOUT_SIZE        |
1663                                                                REORDER                   |
1664                                                                ALIGN );
1665       mImpl->mRecalculateNaturalSize = true;
1666       mImpl->RequestRelayout();
1667
1668       mImpl->mTextUpdateInfo.mCharacterIndex = startOfSelectedText;
1669       mImpl->mTextUpdateInfo.mNumberOfCharactersToRemove = lengthOfSelectedText;
1670       mImpl->mTextUpdateInfo.mNumberOfCharactersToAdd = lengthOfSelectedText;
1671
1672       // As the font might change, recalculate the handle positions is needed.
1673       mImpl->mEventData->mUpdateLeftSelectionPosition = true;
1674       mImpl->mEventData->mUpdateRightSelectionPosition = true;
1675       mImpl->mEventData->mUpdateHighlightBox = true;
1676       mImpl->mEventData->mScrollAfterUpdatePosition = true;
1677     }
1678   }
1679 }
1680
1681 float Controller::GetInputFontPointSize() const
1682 {
1683   if( NULL != mImpl->mEventData )
1684   {
1685     return mImpl->mEventData->mInputStyle.size;
1686   }
1687
1688   // Return the default font's point size if there is no EventData.
1689   return GetDefaultFontSize( Text::Controller::POINT_SIZE );
1690 }
1691
1692 void Controller::SetInputLineSpacing( float lineSpacing )
1693 {
1694   if( NULL != mImpl->mEventData )
1695   {
1696     mImpl->mEventData->mInputStyle.lineSpacing = lineSpacing;
1697     mImpl->mEventData->mInputStyle.isLineSpacingDefined = true;
1698   }
1699 }
1700
1701 float Controller::GetInputLineSpacing() const
1702 {
1703   if( NULL != mImpl->mEventData )
1704   {
1705     return mImpl->mEventData->mInputStyle.lineSpacing;
1706   }
1707
1708   return 0.f;
1709 }
1710
1711 void Controller::SetInputShadowProperties( const std::string& shadowProperties )
1712 {
1713   if( NULL != mImpl->mEventData )
1714   {
1715     mImpl->mEventData->mInputStyle.shadowProperties = shadowProperties;
1716   }
1717 }
1718
1719 const std::string& Controller::GetInputShadowProperties() const
1720 {
1721   if( NULL != mImpl->mEventData )
1722   {
1723     return mImpl->mEventData->mInputStyle.shadowProperties;
1724   }
1725
1726   return EMPTY_STRING;
1727 }
1728
1729 void Controller::SetInputUnderlineProperties( const std::string& underlineProperties )
1730 {
1731   if( NULL != mImpl->mEventData )
1732   {
1733     mImpl->mEventData->mInputStyle.underlineProperties = underlineProperties;
1734   }
1735 }
1736
1737 const std::string& Controller::GetInputUnderlineProperties() const
1738 {
1739   if( NULL != mImpl->mEventData )
1740   {
1741     return mImpl->mEventData->mInputStyle.underlineProperties;
1742   }
1743
1744   return EMPTY_STRING;
1745 }
1746
1747 void Controller::SetInputEmbossProperties( const std::string& embossProperties )
1748 {
1749   if( NULL != mImpl->mEventData )
1750   {
1751     mImpl->mEventData->mInputStyle.embossProperties = embossProperties;
1752   }
1753 }
1754
1755 const std::string& Controller::GetInputEmbossProperties() const
1756 {
1757   if( NULL != mImpl->mEventData )
1758   {
1759     return mImpl->mEventData->mInputStyle.embossProperties;
1760   }
1761
1762   return GetDefaultEmbossProperties();
1763 }
1764
1765 void Controller::SetInputOutlineProperties( const std::string& outlineProperties )
1766 {
1767   if( NULL != mImpl->mEventData )
1768   {
1769     mImpl->mEventData->mInputStyle.outlineProperties = outlineProperties;
1770   }
1771 }
1772
1773 const std::string& Controller::GetInputOutlineProperties() const
1774 {
1775   if( NULL != mImpl->mEventData )
1776   {
1777     return mImpl->mEventData->mInputStyle.outlineProperties;
1778   }
1779
1780   return GetDefaultOutlineProperties();
1781 }
1782
1783 void Controller::SetInputModePassword( bool passwordInput )
1784 {
1785   if( NULL != mImpl->mEventData )
1786   {
1787     mImpl->mEventData->mPasswordInput = passwordInput;
1788   }
1789 }
1790
1791 bool Controller::IsInputModePassword()
1792 {
1793   if( NULL != mImpl->mEventData )
1794   {
1795     return mImpl->mEventData->mPasswordInput;
1796   }
1797   return false;
1798 }
1799
1800 void Controller::SetNoTextDoubleTapAction( NoTextTap::Action action )
1801 {
1802   if( NULL != mImpl->mEventData )
1803   {
1804     mImpl->mEventData->mDoubleTapAction = action;
1805   }
1806 }
1807
1808 Controller::NoTextTap::Action Controller::GetNoTextDoubleTapAction() const
1809 {
1810   NoTextTap::Action action = NoTextTap::NO_ACTION;
1811
1812   if( NULL != mImpl->mEventData )
1813   {
1814     action = mImpl->mEventData->mDoubleTapAction;
1815   }
1816
1817   return action;
1818 }
1819
1820 void Controller::SetNoTextLongPressAction( NoTextTap::Action action )
1821 {
1822   if( NULL != mImpl->mEventData )
1823   {
1824     mImpl->mEventData->mLongPressAction = action;
1825   }
1826 }
1827
1828 Controller::NoTextTap::Action Controller::GetNoTextLongPressAction() const
1829 {
1830   NoTextTap::Action action = NoTextTap::NO_ACTION;
1831
1832   if( NULL != mImpl->mEventData )
1833   {
1834     action = mImpl->mEventData->mLongPressAction;
1835   }
1836
1837   return action;
1838 }
1839
1840 bool Controller::IsUnderlineSetByString()
1841 {
1842   return mImpl->mUnderlineSetByString;
1843 }
1844
1845 void Controller::UnderlineSetByString( bool setByString )
1846 {
1847   mImpl->mUnderlineSetByString = setByString;
1848 }
1849
1850 bool Controller::IsShadowSetByString()
1851 {
1852   return mImpl->mShadowSetByString;
1853 }
1854
1855 void Controller::ShadowSetByString( bool setByString )
1856 {
1857   mImpl->mShadowSetByString = setByString;
1858 }
1859
1860 bool Controller::IsOutlineSetByString()
1861 {
1862   return mImpl->mOutlineSetByString;
1863 }
1864
1865 void Controller::OutlineSetByString( bool setByString )
1866 {
1867   mImpl->mOutlineSetByString = setByString;
1868 }
1869
1870 bool Controller::IsFontStyleSetByString()
1871 {
1872   return mImpl->mFontStyleSetByString;
1873 }
1874
1875 void Controller::FontStyleSetByString( bool setByString )
1876 {
1877   mImpl->mFontStyleSetByString = setByString;
1878 }
1879
1880 // public : Queries & retrieves.
1881
1882 Layout::Engine& Controller::GetLayoutEngine()
1883 {
1884   return mImpl->mLayoutEngine;
1885 }
1886
1887 View& Controller::GetView()
1888 {
1889   return mImpl->mView;
1890 }
1891
1892 Vector3 Controller::GetNaturalSize()
1893 {
1894   DALI_LOG_INFO( gLogFilter, Debug::Verbose, "-->Controller::GetNaturalSize\n" );
1895   Vector3 naturalSize;
1896
1897   // Make sure the model is up-to-date before layouting
1898   ProcessModifyEvents();
1899
1900   if( mImpl->mRecalculateNaturalSize )
1901   {
1902     // Operations that can be done only once until the text changes.
1903     const OperationsMask onlyOnceOperations = static_cast<OperationsMask>( CONVERT_TO_UTF32  |
1904                                                                            GET_SCRIPTS       |
1905                                                                            VALIDATE_FONTS    |
1906                                                                            GET_LINE_BREAKS   |
1907                                                                            GET_WORD_BREAKS   |
1908                                                                            BIDI_INFO         |
1909                                                                            SHAPE_TEXT        |
1910                                                                            GET_GLYPH_METRICS );
1911
1912     // Set the update info to relayout the whole text.
1913     mImpl->mTextUpdateInfo.mParagraphCharacterIndex = 0u;
1914     mImpl->mTextUpdateInfo.mRequestedNumberOfCharacters = mImpl->mModel->mLogicalModel->mText.Count();
1915
1916     // Make sure the model is up-to-date before layouting
1917     mImpl->UpdateModel( onlyOnceOperations );
1918
1919     // Layout the text for the new width.
1920     mImpl->mOperationsPending = static_cast<OperationsMask>( mImpl->mOperationsPending | LAYOUT | REORDER );
1921
1922     // Store the actual control's size to restore later.
1923     const Size actualControlSize = mImpl->mModel->mVisualModel->mControlSize;
1924
1925     DoRelayout( Size( MAX_FLOAT, MAX_FLOAT ),
1926                 static_cast<OperationsMask>( onlyOnceOperations |
1927                                              LAYOUT | REORDER ),
1928                 naturalSize.GetVectorXY() );
1929
1930     // Do not do again the only once operations.
1931     mImpl->mOperationsPending = static_cast<OperationsMask>( mImpl->mOperationsPending & ~onlyOnceOperations );
1932
1933     // Do the size related operations again.
1934     const OperationsMask sizeOperations =  static_cast<OperationsMask>( LAYOUT |
1935                                                                         ALIGN  |
1936                                                                         REORDER );
1937     mImpl->mOperationsPending = static_cast<OperationsMask>( mImpl->mOperationsPending | sizeOperations );
1938
1939     // Stores the natural size to avoid recalculate it again
1940     // unless the text/style changes.
1941     mImpl->mModel->mVisualModel->SetNaturalSize( naturalSize.GetVectorXY() );
1942
1943     mImpl->mRecalculateNaturalSize = false;
1944
1945     // Clear the update info. This info will be set the next time the text is updated.
1946     mImpl->mTextUpdateInfo.Clear();
1947     mImpl->mTextUpdateInfo.mClearAll = true;
1948
1949     // Restore the actual control's size.
1950     mImpl->mModel->mVisualModel->mControlSize = actualControlSize;
1951
1952     DALI_LOG_INFO( gLogFilter, Debug::Verbose, "<--Controller::GetNaturalSize calculated %f,%f,%f\n", naturalSize.x, naturalSize.y, naturalSize.z );
1953   }
1954   else
1955   {
1956     naturalSize = mImpl->mModel->mVisualModel->GetNaturalSize();
1957
1958     DALI_LOG_INFO( gLogFilter, Debug::Verbose, "<--Controller::GetNaturalSize cached %f,%f,%f\n", naturalSize.x, naturalSize.y, naturalSize.z );
1959   }
1960
1961   naturalSize.x = ConvertToEven( naturalSize.x );
1962   naturalSize.y = ConvertToEven( naturalSize.y );
1963
1964   return naturalSize;
1965 }
1966
1967 float Controller::GetHeightForWidth( float width )
1968 {
1969   DALI_LOG_INFO( gLogFilter, Debug::Verbose, "-->Controller::GetHeightForWidth %p width %f\n", this, width );
1970   // Make sure the model is up-to-date before layouting
1971   ProcessModifyEvents();
1972
1973   Size layoutSize;
1974   if( fabsf( width - mImpl->mModel->mVisualModel->mControlSize.width ) > Math::MACHINE_EPSILON_1000 ||
1975                                                          mImpl->mTextUpdateInfo.mFullRelayoutNeeded ||
1976                                                          mImpl->mTextUpdateInfo.mClearAll            )
1977   {
1978     // Operations that can be done only once until the text changes.
1979     const OperationsMask onlyOnceOperations = static_cast<OperationsMask>( CONVERT_TO_UTF32  |
1980                                                                            GET_SCRIPTS       |
1981                                                                            VALIDATE_FONTS    |
1982                                                                            GET_LINE_BREAKS   |
1983                                                                            GET_WORD_BREAKS   |
1984                                                                            BIDI_INFO         |
1985                                                                            SHAPE_TEXT        |
1986                                                                            GET_GLYPH_METRICS );
1987
1988     // Set the update info to relayout the whole text.
1989     mImpl->mTextUpdateInfo.mParagraphCharacterIndex = 0u;
1990     mImpl->mTextUpdateInfo.mRequestedNumberOfCharacters = mImpl->mModel->mLogicalModel->mText.Count();
1991
1992     // Make sure the model is up-to-date before layouting
1993     mImpl->UpdateModel( onlyOnceOperations );
1994
1995
1996     // Layout the text for the new width.
1997     mImpl->mOperationsPending = static_cast<OperationsMask>( mImpl->mOperationsPending | LAYOUT );
1998
1999     // Store the actual control's width.
2000     const float actualControlWidth = mImpl->mModel->mVisualModel->mControlSize.width;
2001
2002     DoRelayout( Size( width, MAX_FLOAT ),
2003                 static_cast<OperationsMask>( onlyOnceOperations |
2004                                              LAYOUT ),
2005                 layoutSize );
2006
2007     // Do not do again the only once operations.
2008     mImpl->mOperationsPending = static_cast<OperationsMask>( mImpl->mOperationsPending & ~onlyOnceOperations );
2009
2010     // Do the size related operations again.
2011     const OperationsMask sizeOperations =  static_cast<OperationsMask>( LAYOUT |
2012                                                                         ALIGN  |
2013                                                                         REORDER );
2014
2015     mImpl->mOperationsPending = static_cast<OperationsMask>( mImpl->mOperationsPending | sizeOperations );
2016
2017     // Clear the update info. This info will be set the next time the text is updated.
2018     mImpl->mTextUpdateInfo.Clear();
2019     mImpl->mTextUpdateInfo.mClearAll = true;
2020
2021     // Restore the actual control's width.
2022     mImpl->mModel->mVisualModel->mControlSize.width = actualControlWidth;
2023
2024     DALI_LOG_INFO( gLogFilter, Debug::Verbose, "<--Controller::GetHeightForWidth calculated %f\n", layoutSize.height );
2025   }
2026   else
2027   {
2028     layoutSize = mImpl->mModel->mVisualModel->GetLayoutSize();
2029     DALI_LOG_INFO( gLogFilter, Debug::Verbose, "<--Controller::GetHeightForWidth cached %f\n", layoutSize.height );
2030   }
2031
2032   return layoutSize.height;
2033 }
2034
2035 int Controller::GetLineCount( float width )
2036 {
2037   GetHeightForWidth( width );
2038   int numberofLines = mImpl->mModel->GetNumberOfLines();
2039   return numberofLines;
2040 }
2041
2042 const ModelInterface* const Controller::GetTextModel() const
2043 {
2044   return mImpl->mModel.Get();
2045 }
2046
2047 float Controller::GetScrollAmountByUserInput()
2048 {
2049   float scrollAmount = 0.0f;
2050
2051   if (NULL != mImpl->mEventData && mImpl->mEventData->mCheckScrollAmount)
2052   {
2053     scrollAmount = mImpl->mModel->mScrollPosition.y -  mImpl->mModel->mScrollPositionLast.y;
2054     mImpl->mEventData->mCheckScrollAmount = false;
2055   }
2056   return scrollAmount;
2057 }
2058
2059 bool Controller::GetTextScrollInfo( float& scrollPosition, float& controlHeight, float& layoutHeight )
2060 {
2061   const Vector2& layout = mImpl->mModel->mVisualModel->GetLayoutSize();
2062   bool isScrolled;
2063
2064   controlHeight = mImpl->mModel->mVisualModel->mControlSize.height;
2065   layoutHeight = layout.height;
2066   scrollPosition = mImpl->mModel->mScrollPosition.y;
2067   isScrolled = !Equals( mImpl->mModel->mScrollPosition.y, mImpl->mModel->mScrollPositionLast.y, Math::MACHINE_EPSILON_1 );
2068   return isScrolled;
2069 }
2070
2071 void Controller::SetHiddenInputOption(const Property::Map& options )
2072 {
2073   if( NULL == mImpl->mHiddenInput )
2074   {
2075     mImpl->mHiddenInput = new HiddenText( this );
2076   }
2077   mImpl->mHiddenInput->SetProperties(options);
2078 }
2079
2080 void Controller::GetHiddenInputOption(Property::Map& options )
2081 {
2082   if( NULL != mImpl->mHiddenInput )
2083   {
2084     mImpl->mHiddenInput->GetProperties(options);
2085   }
2086 }
2087
2088 void Controller::SetPlaceholderProperty( const Property::Map& map )
2089 {
2090   const Property::Map::SizeType count = map.Count();
2091
2092   for( Property::Map::SizeType position = 0; position < count; ++position )
2093   {
2094     KeyValuePair keyValue = map.GetKeyValue( position );
2095     Property::Key& key = keyValue.first;
2096     Property::Value& value = keyValue.second;
2097
2098     if( key == Toolkit::Text::PlaceHolder::Property::TEXT  || key == PLACEHOLDER_TEXT )
2099     {
2100       std::string text = "";
2101       value.Get( text );
2102       SetPlaceholderText( Controller::PLACEHOLDER_TYPE_INACTIVE, text );
2103     }
2104     else if( key == Toolkit::Text::PlaceHolder::Property::TEXT_FOCUSED || key == PLACEHOLDER_TEXT_FOCUSED )
2105     {
2106       std::string text = "";
2107       value.Get( text );
2108       SetPlaceholderText( Controller::PLACEHOLDER_TYPE_ACTIVE, text );
2109     }
2110     else if( key == Toolkit::Text::PlaceHolder::Property::COLOR || key == PLACEHOLDER_COLOR )
2111     {
2112       Vector4 textColor;
2113       value.Get( textColor );
2114       if( GetPlaceholderTextColor() != textColor )
2115       {
2116         SetPlaceholderTextColor( textColor );
2117       }
2118     }
2119     else if( key == Toolkit::Text::PlaceHolder::Property::FONT_FAMILY || key == PLACEHOLDER_FONT_FAMILY )
2120     {
2121       std::string fontFamily = "";
2122       value.Get( fontFamily );
2123       SetPlaceholderFontFamily( fontFamily );
2124     }
2125     else if( key == Toolkit::Text::PlaceHolder::Property::FONT_STYLE || key == PLACEHOLDER_FONT_STYLE )
2126     {
2127       SetFontStyleProperty( this, value, Text::FontStyle::PLACEHOLDER );
2128     }
2129     else if( key == Toolkit::Text::PlaceHolder::Property::POINT_SIZE || key == PLACEHOLDER_POINT_SIZE )
2130     {
2131       float pointSize;
2132       value.Get( pointSize );
2133       if( !Equals( GetPlaceholderTextFontSize( Text::Controller::POINT_SIZE ), pointSize ) )
2134       {
2135         SetPlaceholderTextFontSize( pointSize, Text::Controller::POINT_SIZE );
2136       }
2137     }
2138     else if( key == Toolkit::Text::PlaceHolder::Property::PIXEL_SIZE || key == PLACEHOLDER_PIXEL_SIZE )
2139     {
2140       float pixelSize;
2141       value.Get( pixelSize );
2142       if( !Equals( GetPlaceholderTextFontSize( Text::Controller::PIXEL_SIZE ), pixelSize ) )
2143       {
2144         SetPlaceholderTextFontSize( pixelSize, Text::Controller::PIXEL_SIZE );
2145       }
2146     }
2147     else if( key == Toolkit::Text::PlaceHolder::Property::ELLIPSIS || key == PLACEHOLDER_ELLIPSIS )
2148     {
2149       bool ellipsis;
2150       value.Get( ellipsis );
2151       SetPlaceholderTextElideEnabled( ellipsis );
2152     }
2153   }
2154 }
2155
2156 void Controller::GetPlaceholderProperty( Property::Map& map )
2157 {
2158   if( NULL != mImpl->mEventData )
2159   {
2160     if( !mImpl->mEventData->mPlaceholderTextActive.empty() )
2161     {
2162       map[ Text::PlaceHolder::Property::TEXT_FOCUSED ] = mImpl->mEventData->mPlaceholderTextActive;
2163     }
2164     if( !mImpl->mEventData->mPlaceholderTextInactive.empty() )
2165     {
2166       map[ Text::PlaceHolder::Property::TEXT ] = mImpl->mEventData->mPlaceholderTextInactive;
2167     }
2168
2169     map[ Text::PlaceHolder::Property::COLOR ] = mImpl->mEventData->mPlaceholderTextColor;
2170     map[ Text::PlaceHolder::Property::FONT_FAMILY ] = GetPlaceholderFontFamily();
2171
2172     Property::Value fontStyleMapGet;
2173     GetFontStyleProperty( this, fontStyleMapGet, Text::FontStyle::PLACEHOLDER );
2174     map[ Text::PlaceHolder::Property::FONT_STYLE ] = fontStyleMapGet;
2175
2176     // Choose font size : POINT_SIZE or PIXEL_SIZE
2177     if( !mImpl->mEventData->mIsPlaceholderPixelSize )
2178     {
2179       map[ Text::PlaceHolder::Property::POINT_SIZE ] = GetPlaceholderTextFontSize( Text::Controller::POINT_SIZE );
2180     }
2181     else
2182     {
2183       map[ Text::PlaceHolder::Property::PIXEL_SIZE ] = GetPlaceholderTextFontSize( Text::Controller::PIXEL_SIZE );
2184     }
2185
2186     if( mImpl->mEventData->mPlaceholderEllipsisFlag )
2187     {
2188       map[ Text::PlaceHolder::Property::ELLIPSIS ] = IsPlaceholderTextElideEnabled();
2189     }
2190   }
2191 }
2192
2193 Toolkit::DevelText::TextDirection::Type Controller::GetTextDirection()
2194 {
2195   // Make sure the model is up-to-date before layouting
2196   ProcessModifyEvents();
2197
2198   if ( mImpl->mUpdateTextDirection )
2199   {
2200     // Operations that can be done only once until the text changes.
2201     const OperationsMask onlyOnceOperations = static_cast<OperationsMask>( CONVERT_TO_UTF32  |
2202                                                                            GET_SCRIPTS       |
2203                                                                            VALIDATE_FONTS    |
2204                                                                            GET_LINE_BREAKS   |
2205                                                                            GET_WORD_BREAKS   |
2206                                                                            BIDI_INFO         |
2207                                                                            SHAPE_TEXT        |
2208                                                                            GET_GLYPH_METRICS );
2209
2210     // Set the update info to relayout the whole text.
2211     mImpl->mTextUpdateInfo.mParagraphCharacterIndex = 0u;
2212     mImpl->mTextUpdateInfo.mRequestedNumberOfCharacters = mImpl->mModel->mLogicalModel->mText.Count();
2213
2214     // Make sure the model is up-to-date before layouting
2215     mImpl->UpdateModel( onlyOnceOperations );
2216
2217     Vector3 naturalSize;
2218     DoRelayout( Size( MAX_FLOAT, MAX_FLOAT ),
2219                 static_cast<OperationsMask>( onlyOnceOperations |
2220                                              LAYOUT | REORDER | UPDATE_DIRECTION ),
2221                 naturalSize.GetVectorXY() );
2222
2223     // Do not do again the only once operations.
2224     mImpl->mOperationsPending = static_cast<OperationsMask>( mImpl->mOperationsPending & ~onlyOnceOperations );
2225
2226     // Clear the update info. This info will be set the next time the text is updated.
2227     mImpl->mTextUpdateInfo.Clear();
2228
2229     mImpl->mUpdateTextDirection = false;
2230   }
2231
2232   return mImpl->mIsTextDirectionRTL ? Toolkit::DevelText::TextDirection::RIGHT_TO_LEFT : Toolkit::DevelText::TextDirection::LEFT_TO_RIGHT;
2233 }
2234
2235 Toolkit::DevelText::VerticalLineAlignment::Type Controller::GetVerticalLineAlignment() const
2236 {
2237   return mImpl->mModel->GetVerticalLineAlignment();
2238 }
2239
2240 void Controller::SetVerticalLineAlignment( Toolkit::DevelText::VerticalLineAlignment::Type alignment )
2241 {
2242   mImpl->mModel->mVerticalLineAlignment = alignment;
2243 }
2244
2245 // public : Relayout.
2246
2247 Controller::UpdateTextType Controller::Relayout( const Size& size, Dali::LayoutDirection::Type layoutDirection )
2248 {
2249   DALI_LOG_INFO( gLogFilter, Debug::Verbose, "-->Controller::Relayout %p size %f,%f, autoScroll[%s]\n", this, size.width, size.height, mImpl->mIsAutoScrollEnabled ?"true":"false"  );
2250
2251   UpdateTextType updateTextType = NONE_UPDATED;
2252
2253   if( ( size.width < Math::MACHINE_EPSILON_1000 ) || ( size.height < Math::MACHINE_EPSILON_1000 ) )
2254   {
2255     if( 0u != mImpl->mModel->mVisualModel->mGlyphPositions.Count() )
2256     {
2257       mImpl->mModel->mVisualModel->mGlyphPositions.Clear();
2258       updateTextType = MODEL_UPDATED;
2259     }
2260
2261     // Clear the update info. This info will be set the next time the text is updated.
2262     mImpl->mTextUpdateInfo.Clear();
2263
2264     // Not worth to relayout if width or height is equal to zero.
2265     DALI_LOG_INFO( gLogFilter, Debug::Verbose, "<--Controller::Relayout (skipped)\n" );
2266
2267     return updateTextType;
2268   }
2269
2270   // Whether a new size has been set.
2271   const bool newSize = ( size != mImpl->mModel->mVisualModel->mControlSize );
2272
2273   if( newSize )
2274   {
2275     DALI_LOG_INFO( gLogFilter, Debug::Verbose, "new size (previous size %f,%f)\n", mImpl->mModel->mVisualModel->mControlSize.width, mImpl->mModel->mVisualModel->mControlSize.height );
2276
2277     if( ( 0 == mImpl->mTextUpdateInfo.mNumberOfCharactersToAdd ) &&
2278         ( 0 == mImpl->mTextUpdateInfo.mPreviousNumberOfCharacters ) &&
2279         ( ( mImpl->mModel->mVisualModel->mControlSize.width < Math::MACHINE_EPSILON_1000 ) || ( mImpl->mModel->mVisualModel->mControlSize.height < Math::MACHINE_EPSILON_1000 ) ) )
2280     {
2281       mImpl->mTextUpdateInfo.mNumberOfCharactersToAdd = mImpl->mModel->mLogicalModel->mText.Count();
2282     }
2283
2284     // Layout operations that need to be done if the size changes.
2285     mImpl->mOperationsPending = static_cast<OperationsMask>( mImpl->mOperationsPending |
2286                                                              LAYOUT                    |
2287                                                              ALIGN                     |
2288                                                              UPDATE_LAYOUT_SIZE        |
2289                                                              REORDER );
2290     // Set the update info to relayout the whole text.
2291     mImpl->mTextUpdateInfo.mFullRelayoutNeeded = true;
2292     mImpl->mTextUpdateInfo.mCharacterIndex = 0u;
2293
2294     // Store the size used to layout the text.
2295     mImpl->mModel->mVisualModel->mControlSize = size;
2296   }
2297
2298   // Whether there are modify events.
2299   if( 0u != mImpl->mModifyEvents.Count() )
2300   {
2301     // Style operations that need to be done if the text is modified.
2302     mImpl->mOperationsPending = static_cast<OperationsMask>( mImpl->mOperationsPending |
2303                                                              COLOR );
2304   }
2305
2306   // Set the update info to elide the text.
2307   if( mImpl->mModel->mElideEnabled ||
2308       ( ( NULL != mImpl->mEventData ) && mImpl->mEventData->mIsPlaceholderElideEnabled ) )
2309   {
2310     // Update Text layout for applying elided
2311     mImpl->mOperationsPending = static_cast<OperationsMask>( mImpl->mOperationsPending |
2312                                                              ALIGN                     |
2313                                                              LAYOUT                    |
2314                                                              UPDATE_LAYOUT_SIZE        |
2315                                                              REORDER );
2316     mImpl->mTextUpdateInfo.mFullRelayoutNeeded = true;
2317     mImpl->mTextUpdateInfo.mCharacterIndex = 0u;
2318   }
2319
2320   if( mImpl->mModel->mMatchSystemLanguageDirection  && mImpl->mLayoutDirection != layoutDirection )
2321   {
2322     // Clear the update info. This info will be set the next time the text is updated.
2323     mImpl->mTextUpdateInfo.mClearAll = true;
2324     // Apply modifications to the model
2325     // Shape the text again is needed because characters like '()[]{}' have to be mirrored and the glyphs generated again.
2326     mImpl->mOperationsPending = static_cast<OperationsMask>( mImpl->mOperationsPending |
2327                                                              GET_GLYPH_METRICS         |
2328                                                              SHAPE_TEXT                |
2329                                                              UPDATE_DIRECTION          |
2330                                                              LAYOUT                    |
2331                                                              BIDI_INFO                 |
2332                                                              REORDER );
2333     mImpl->mLayoutDirection = layoutDirection;
2334   }
2335
2336   // Make sure the model is up-to-date before layouting.
2337   ProcessModifyEvents();
2338   bool updated = mImpl->UpdateModel( mImpl->mOperationsPending );
2339
2340   // Layout the text.
2341   Size layoutSize;
2342   updated = DoRelayout( size,
2343                         mImpl->mOperationsPending,
2344                         layoutSize ) || updated;
2345
2346
2347   if( updated )
2348   {
2349     updateTextType = MODEL_UPDATED;
2350   }
2351
2352   // Do not re-do any operation until something changes.
2353   mImpl->mOperationsPending = NO_OPERATION;
2354   mImpl->mModel->mScrollPositionLast = mImpl->mModel->mScrollPosition;
2355
2356   // Whether the text control is editable
2357   const bool isEditable = NULL != mImpl->mEventData;
2358
2359   // Keep the current offset as it will be used to update the decorator's positions (if the size changes).
2360   Vector2 offset;
2361   if( newSize && isEditable )
2362   {
2363     offset = mImpl->mModel->mScrollPosition;
2364   }
2365
2366   if( !isEditable || !IsMultiLineEnabled() )
2367   {
2368     // After doing the text layout, the vertical offset to place the actor in the desired position can be calculated.
2369     CalculateVerticalOffset( size );
2370   }
2371
2372   if( isEditable )
2373   {
2374     if( newSize )
2375     {
2376       // If there is a new size, the scroll position needs to be clamped.
2377       mImpl->ClampHorizontalScroll( layoutSize );
2378
2379       // Update the decorator's positions is needed if there is a new size.
2380       mImpl->mEventData->mDecorator->UpdatePositions( mImpl->mModel->mScrollPosition - offset );
2381     }
2382
2383     // Move the cursor, grab handle etc.
2384     if( mImpl->ProcessInputEvents() )
2385     {
2386       updateTextType = static_cast<UpdateTextType>( updateTextType | DECORATOR_UPDATED );
2387     }
2388   }
2389
2390   // Clear the update info. This info will be set the next time the text is updated.
2391   mImpl->mTextUpdateInfo.Clear();
2392   DALI_LOG_INFO( gLogFilter, Debug::Verbose, "<--Controller::Relayout\n" );
2393
2394   return updateTextType;
2395 }
2396
2397 void Controller::RequestRelayout()
2398 {
2399   mImpl->RequestRelayout();
2400 }
2401
2402 // public : Input style change signals.
2403
2404 bool Controller::IsInputStyleChangedSignalsQueueEmpty()
2405 {
2406   return ( NULL == mImpl->mEventData ) || ( 0u == mImpl->mEventData->mInputStyleChangedQueue.Count() );
2407 }
2408
2409 void Controller::ProcessInputStyleChangedSignals()
2410 {
2411   if( NULL == mImpl->mEventData )
2412   {
2413     // Nothing to do.
2414     return;
2415   }
2416
2417   for( Vector<InputStyle::Mask>::ConstIterator it = mImpl->mEventData->mInputStyleChangedQueue.Begin(),
2418          endIt = mImpl->mEventData->mInputStyleChangedQueue.End();
2419        it != endIt;
2420        ++it )
2421   {
2422     const InputStyle::Mask mask = *it;
2423
2424     if( NULL != mImpl->mEditableControlInterface )
2425     {
2426       // Emit the input style changed signal.
2427       mImpl->mEditableControlInterface->InputStyleChanged( mask );
2428     }
2429   }
2430
2431   mImpl->mEventData->mInputStyleChangedQueue.Clear();
2432 }
2433
2434 // public : Text-input Event Queuing.
2435
2436 void Controller::KeyboardFocusGainEvent()
2437 {
2438   DALI_ASSERT_DEBUG( mImpl->mEventData && "Unexpected KeyboardFocusGainEvent" );
2439
2440   if( NULL != mImpl->mEventData )
2441   {
2442     if( ( EventData::INACTIVE == mImpl->mEventData->mState ) ||
2443         ( EventData::INTERRUPTED == mImpl->mEventData->mState ) )
2444     {
2445       mImpl->ChangeState( EventData::EDITING );
2446       mImpl->mEventData->mUpdateCursorPosition = true; //If editing started without tap event, cursor update must be triggered.
2447       mImpl->mEventData->mUpdateInputStyle = true;
2448       mImpl->mEventData->mScrollAfterUpdatePosition = true;
2449     }
2450     mImpl->NotifyInputMethodContextMultiLineStatus();
2451     if( mImpl->IsShowingPlaceholderText() )
2452     {
2453       // Show alternative placeholder-text when editing
2454       ShowPlaceholderText();
2455     }
2456
2457     mImpl->RequestRelayout();
2458   }
2459 }
2460
2461 void Controller::KeyboardFocusLostEvent()
2462 {
2463   DALI_ASSERT_DEBUG( mImpl->mEventData && "Unexpected KeyboardFocusLostEvent" );
2464
2465   if( NULL != mImpl->mEventData )
2466   {
2467     if( EventData::INTERRUPTED != mImpl->mEventData->mState )
2468     {
2469       mImpl->ChangeState( EventData::INACTIVE );
2470
2471       if( !mImpl->IsShowingRealText() )
2472       {
2473         // Revert to regular placeholder-text when not editing
2474         ShowPlaceholderText();
2475       }
2476     }
2477   }
2478   mImpl->RequestRelayout();
2479 }
2480
2481 bool Controller::KeyEvent( const Dali::KeyEvent& keyEvent )
2482 {
2483   DALI_ASSERT_DEBUG( mImpl->mEventData && "Unexpected KeyEvent" );
2484
2485   bool textChanged = false;
2486   bool relayoutNeeded = false;
2487
2488   if( ( NULL != mImpl->mEventData ) &&
2489       ( keyEvent.state == KeyEvent::Down ) )
2490   {
2491     int keyCode = keyEvent.keyCode;
2492     const std::string& keyString = keyEvent.keyPressed;
2493     const std::string keyName = keyEvent.keyPressedName;
2494
2495     const bool isNullKey = ( 0 == keyCode ) && ( keyString.empty() );
2496
2497     // Pre-process to separate modifying events from non-modifying input events.
2498     if( isNullKey )
2499     {
2500       // In some platforms arrive key events with no key code.
2501       // Do nothing.
2502       return false;
2503     }
2504     else if( Dali::DALI_KEY_ESCAPE == keyCode || Dali::DALI_KEY_BACK == keyCode  || Dali::DALI_KEY_SEARCH == keyCode )
2505     {
2506       // Do nothing
2507       return false;
2508     }
2509     else if( ( Dali::DALI_KEY_CURSOR_LEFT  == keyCode ) ||
2510              ( Dali::DALI_KEY_CURSOR_RIGHT == keyCode ) ||
2511              ( Dali::DALI_KEY_CURSOR_UP    == keyCode ) ||
2512              ( Dali::DALI_KEY_CURSOR_DOWN  == keyCode ) )
2513     {
2514       // If don't have any text, do nothing.
2515       if( !mImpl->mTextUpdateInfo.mPreviousNumberOfCharacters )
2516       {
2517         return false;
2518       }
2519
2520       uint32_t cursorPosition = mImpl->mEventData->mPrimaryCursorPosition;
2521       uint32_t numberOfCharacters = mImpl->mTextUpdateInfo.mPreviousNumberOfCharacters;
2522       uint32_t cursorLine = mImpl->mModel->mVisualModel->GetLineOfCharacter( cursorPosition );
2523       uint32_t numberOfLines = mImpl->mModel->GetNumberOfLines();
2524
2525       // Logic to determine whether this text control will lose focus or not.
2526       if( ( Dali::DALI_KEY_CURSOR_LEFT == keyCode && 0 == cursorPosition && !keyEvent.IsShiftModifier() ) ||
2527           ( Dali::DALI_KEY_CURSOR_RIGHT == keyCode && numberOfCharacters == cursorPosition && !keyEvent.IsShiftModifier() ) ||
2528           ( Dali::DALI_KEY_CURSOR_DOWN == keyCode && cursorLine == numberOfLines -1 ) ||
2529           ( Dali::DALI_KEY_CURSOR_DOWN == keyCode && numberOfCharacters == cursorPosition && cursorLine -1 == numberOfLines -1 ) ||
2530           ( Dali::DALI_KEY_CURSOR_UP == keyCode && cursorLine == 0 ) ||
2531           ( Dali::DALI_KEY_CURSOR_UP == keyCode && numberOfCharacters == cursorPosition && cursorLine == 1 ) )
2532       {
2533         // Release the active highlight.
2534         if( mImpl->mEventData->mState == EventData::SELECTING )
2535         {
2536           mImpl->ChangeState( EventData::EDITING );
2537
2538           // Update selection position.
2539           mImpl->mEventData->mLeftSelectionPosition = mImpl->mEventData->mPrimaryCursorPosition;
2540           mImpl->mEventData->mRightSelectionPosition = mImpl->mEventData->mPrimaryCursorPosition;
2541           mImpl->mEventData->mUpdateCursorPosition = true;
2542           mImpl->RequestRelayout();
2543         }
2544         return false;
2545       }
2546
2547       mImpl->mEventData->mCheckScrollAmount = true;
2548       Event event( Event::CURSOR_KEY_EVENT );
2549       event.p1.mInt = keyCode;
2550       event.p2.mBool = keyEvent.IsShiftModifier();
2551       mImpl->mEventData->mEventQueue.push_back( event );
2552
2553       // Will request for relayout.
2554       relayoutNeeded = true;
2555     }
2556     else if ( Dali::DevelKey::DALI_KEY_CONTROL_LEFT == keyCode || Dali::DevelKey::DALI_KEY_CONTROL_RIGHT == keyCode )
2557     {
2558       // Left or Right Control key event is received before Ctrl-C/V/X key event is received
2559       // If not handle it here, any selected text will be deleted
2560
2561       // Do nothing
2562       return false;
2563     }
2564     else if ( keyEvent.IsCtrlModifier() )
2565     {
2566       bool consumed = false;
2567       if (keyName == KEY_C_NAME)
2568       {
2569         // Ctrl-C to copy the selected text
2570         TextPopupButtonTouched( Toolkit::TextSelectionPopup::COPY );
2571         consumed = true;
2572       }
2573       else if (keyName == KEY_V_NAME)
2574       {
2575         // Ctrl-V to paste the copied text
2576         TextPopupButtonTouched( Toolkit::TextSelectionPopup::PASTE );
2577         consumed = true;
2578       }
2579       else if (keyName == KEY_X_NAME)
2580       {
2581         // Ctrl-X to cut the selected text
2582         TextPopupButtonTouched( Toolkit::TextSelectionPopup::CUT );
2583         consumed = true;
2584       }
2585       return consumed;
2586     }
2587     else if( ( Dali::DALI_KEY_BACKSPACE == keyCode ) ||
2588              ( Dali::DevelKey::DALI_KEY_DELETE == keyCode ) )
2589     {
2590       textChanged = DeleteEvent( keyCode );
2591
2592       // Will request for relayout.
2593       relayoutNeeded = true;
2594     }
2595     else if( IsKey( keyEvent, Dali::DALI_KEY_POWER ) ||
2596              IsKey( keyEvent, Dali::DALI_KEY_MENU ) ||
2597              IsKey( keyEvent, Dali::DALI_KEY_HOME ) )
2598     {
2599       // Power key/Menu/Home key behaviour does not allow edit mode to resume.
2600       mImpl->ChangeState( EventData::INACTIVE );
2601
2602       // Will request for relayout.
2603       relayoutNeeded = true;
2604
2605       // This branch avoids calling the InsertText() method of the 'else' branch which can delete selected text.
2606     }
2607     else if( Dali::DALI_KEY_SHIFT_LEFT == keyCode )
2608     {
2609       // DALI_KEY_SHIFT_LEFT is the key code for the Left Shift. It's sent (by the InputMethodContext?) when the predictive text is enabled
2610       // and a character is typed after the type of a upper case latin character.
2611
2612       // Do nothing.
2613       return false;
2614     }
2615     else if( ( Dali::DALI_KEY_VOLUME_UP == keyCode ) || ( Dali::DALI_KEY_VOLUME_DOWN == keyCode ) )
2616     {
2617       // This branch avoids calling the InsertText() method of the 'else' branch which can delete selected text.
2618       // Do nothing.
2619       return false;
2620     }
2621     else
2622     {
2623       DALI_LOG_INFO( gLogFilter, Debug::Verbose, "Controller::KeyEvent %p keyString %s\n", this, keyString.c_str() );
2624
2625       // InputMethodContext is no longer handling key-events
2626       mImpl->ClearPreEditFlag();
2627
2628       InsertText( keyString, COMMIT );
2629       textChanged = true;
2630
2631       // Will request for relayout.
2632       relayoutNeeded = true;
2633     }
2634
2635     if ( ( mImpl->mEventData->mState != EventData::INTERRUPTED ) &&
2636          ( mImpl->mEventData->mState != EventData::INACTIVE ) &&
2637          ( !isNullKey ) &&
2638          ( Dali::DALI_KEY_SHIFT_LEFT != keyCode ) &&
2639          ( Dali::DALI_KEY_VOLUME_UP != keyCode ) &&
2640          ( Dali::DALI_KEY_VOLUME_DOWN != keyCode ) )
2641     {
2642       // Should not change the state if the key is the shift send by the InputMethodContext.
2643       // Otherwise, when the state is SELECTING the text controller can't send the right
2644       // surrounding info to the InputMethodContext.
2645       mImpl->ChangeState( EventData::EDITING );
2646
2647       // Will request for relayout.
2648       relayoutNeeded = true;
2649     }
2650
2651     if( relayoutNeeded )
2652     {
2653       mImpl->RequestRelayout();
2654     }
2655   }
2656
2657   if( textChanged &&
2658       ( NULL != mImpl->mEditableControlInterface ) )
2659   {
2660     // Do this last since it provides callbacks into application code
2661     mImpl->mEditableControlInterface->TextChanged();
2662   }
2663
2664   return true;
2665 }
2666
2667 void Controller::TapEvent( unsigned int tapCount, float x, float y )
2668 {
2669   DALI_ASSERT_DEBUG( mImpl->mEventData && "Unexpected TapEvent" );
2670
2671   if( NULL != mImpl->mEventData )
2672   {
2673     DALI_LOG_INFO( gLogFilter, Debug::Concise, "TapEvent state:%d \n", mImpl->mEventData->mState );
2674     EventData::State state( mImpl->mEventData->mState );
2675     bool relayoutNeeded( false );   // to avoid unnecessary relayouts when tapping an empty text-field
2676
2677     if( mImpl->IsClipboardVisible() )
2678     {
2679       if( EventData::INACTIVE == state || EventData::EDITING == state)
2680       {
2681         mImpl->ChangeState( EventData::EDITING_WITH_GRAB_HANDLE );
2682       }
2683       relayoutNeeded = true;
2684     }
2685     else if( 1u == tapCount )
2686     {
2687       if( EventData::EDITING_WITH_POPUP == state || EventData::EDITING_WITH_PASTE_POPUP == state )
2688       {
2689         mImpl->ChangeState( EventData::EDITING_WITH_GRAB_HANDLE );  // If Popup shown hide it here so can be shown again if required.
2690       }
2691
2692       if( mImpl->IsShowingRealText() && ( EventData::INACTIVE != state ) )
2693       {
2694         mImpl->ChangeState( EventData::EDITING_WITH_GRAB_HANDLE );
2695         relayoutNeeded = true;
2696       }
2697       else
2698       {
2699         if( mImpl->IsShowingPlaceholderText() && !mImpl->IsFocusedPlaceholderAvailable() )
2700         {
2701           // Hide placeholder text
2702           ResetText();
2703         }
2704
2705         if( EventData::INACTIVE == state )
2706         {
2707           mImpl->ChangeState( EventData::EDITING );
2708         }
2709         else if( !mImpl->IsClipboardEmpty() )
2710         {
2711           mImpl->ChangeState( EventData::EDITING_WITH_POPUP );
2712         }
2713         relayoutNeeded = true;
2714       }
2715     }
2716     else if( 2u == tapCount )
2717     {
2718       if( mImpl->mEventData->mSelectionEnabled &&
2719           mImpl->IsShowingRealText() )
2720       {
2721         relayoutNeeded = true;
2722         mImpl->mEventData->mIsLeftHandleSelected = true;
2723         mImpl->mEventData->mIsRightHandleSelected = true;
2724       }
2725     }
2726
2727     // Handles & cursors must be repositioned after Relayout() i.e. after the Model has been updated
2728     if( relayoutNeeded )
2729     {
2730       Event event( Event::TAP_EVENT );
2731       event.p1.mUint = tapCount;
2732       event.p2.mFloat = x;
2733       event.p3.mFloat = y;
2734       mImpl->mEventData->mEventQueue.push_back( event );
2735
2736       mImpl->RequestRelayout();
2737     }
2738   }
2739
2740   // Reset keyboard as tap event has occurred.
2741   mImpl->ResetInputMethodContext();
2742 }
2743
2744 void Controller::PanEvent( Gesture::State state, const Vector2& displacement )
2745 {
2746   DALI_ASSERT_DEBUG( mImpl->mEventData && "Unexpected PanEvent" );
2747
2748   if( NULL != mImpl->mEventData )
2749   {
2750     Event event( Event::PAN_EVENT );
2751     event.p1.mInt = state;
2752     event.p2.mFloat = displacement.x;
2753     event.p3.mFloat = displacement.y;
2754     mImpl->mEventData->mEventQueue.push_back( event );
2755
2756     mImpl->RequestRelayout();
2757   }
2758 }
2759
2760 void Controller::LongPressEvent( Gesture::State state, float x, float y  )
2761 {
2762   DALI_ASSERT_DEBUG( mImpl->mEventData && "Unexpected LongPressEvent" );
2763
2764   if( ( state == Gesture::Started ) &&
2765       ( NULL != mImpl->mEventData ) )
2766   {
2767     // The 1st long-press on inactive text-field is treated as tap
2768     if( EventData::INACTIVE == mImpl->mEventData->mState )
2769     {
2770       mImpl->ChangeState( EventData::EDITING );
2771
2772       Event event( Event::TAP_EVENT );
2773       event.p1.mUint = 1;
2774       event.p2.mFloat = x;
2775       event.p3.mFloat = y;
2776       mImpl->mEventData->mEventQueue.push_back( event );
2777
2778       mImpl->RequestRelayout();
2779     }
2780     else if( !mImpl->IsShowingRealText() )
2781     {
2782       Event event( Event::LONG_PRESS_EVENT );
2783       event.p1.mInt = state;
2784       event.p2.mFloat = x;
2785       event.p3.mFloat = y;
2786       mImpl->mEventData->mEventQueue.push_back( event );
2787       mImpl->RequestRelayout();
2788     }
2789     else if( !mImpl->IsClipboardVisible() )
2790     {
2791       // Reset the InputMethodContext to commit the pre-edit before selecting the text.
2792       mImpl->ResetInputMethodContext();
2793
2794       Event event( Event::LONG_PRESS_EVENT );
2795       event.p1.mInt = state;
2796       event.p2.mFloat = x;
2797       event.p3.mFloat = y;
2798       mImpl->mEventData->mEventQueue.push_back( event );
2799       mImpl->RequestRelayout();
2800
2801       mImpl->mEventData->mIsLeftHandleSelected = true;
2802       mImpl->mEventData->mIsRightHandleSelected = true;
2803     }
2804   }
2805 }
2806
2807 InputMethodContext::CallbackData Controller::OnInputMethodContextEvent( InputMethodContext& inputMethodContext, const InputMethodContext::EventData& inputMethodContextEvent )
2808 {
2809   // Whether the text needs to be relaid-out.
2810   bool requestRelayout = false;
2811
2812   // Whether to retrieve the text and cursor position to be sent to the InputMethodContext.
2813   bool retrieveText = false;
2814   bool retrieveCursor = false;
2815
2816   switch( inputMethodContextEvent.eventName )
2817   {
2818     case InputMethodContext::COMMIT:
2819     {
2820       InsertText( inputMethodContextEvent.predictiveString, Text::Controller::COMMIT );
2821       requestRelayout = true;
2822       retrieveCursor = true;
2823       break;
2824     }
2825     case InputMethodContext::PRE_EDIT:
2826     {
2827       InsertText( inputMethodContextEvent.predictiveString, Text::Controller::PRE_EDIT );
2828       requestRelayout = true;
2829       retrieveCursor = true;
2830       break;
2831     }
2832     case InputMethodContext::DELETE_SURROUNDING:
2833     {
2834       const bool textDeleted = RemoveText( inputMethodContextEvent.cursorOffset,
2835                                            inputMethodContextEvent.numberOfChars,
2836                                            DONT_UPDATE_INPUT_STYLE );
2837
2838       if( textDeleted )
2839       {
2840         if( ( 0u != mImpl->mModel->mLogicalModel->mText.Count() ) ||
2841             !mImpl->IsPlaceholderAvailable() )
2842         {
2843           mImpl->QueueModifyEvent( ModifyEvent::TEXT_DELETED );
2844         }
2845         else
2846         {
2847           ShowPlaceholderText();
2848         }
2849         mImpl->mEventData->mUpdateCursorPosition = true;
2850         mImpl->mEventData->mScrollAfterDelete = true;
2851
2852         requestRelayout = true;
2853       }
2854       break;
2855     }
2856     case InputMethodContext::GET_SURROUNDING:
2857     {
2858       retrieveText = true;
2859       retrieveCursor = true;
2860       break;
2861     }
2862     case InputMethodContext::PRIVATE_COMMAND:
2863     {
2864       // PRIVATECOMMAND event is just for getting the private command message
2865       retrieveText = true;
2866       retrieveCursor = true;
2867       break;
2868     }
2869     case InputMethodContext::VOID:
2870     {
2871       // do nothing
2872       break;
2873     }
2874   } // end switch
2875
2876   if( requestRelayout )
2877   {
2878     mImpl->mOperationsPending = ALL_OPERATIONS;
2879     mImpl->RequestRelayout();
2880   }
2881
2882   std::string text;
2883   CharacterIndex cursorPosition = 0u;
2884   Length numberOfWhiteSpaces = 0u;
2885
2886   if( retrieveCursor )
2887   {
2888     numberOfWhiteSpaces = mImpl->GetNumberOfWhiteSpaces( 0u );
2889
2890     cursorPosition = mImpl->GetLogicalCursorPosition();
2891
2892     if( cursorPosition < numberOfWhiteSpaces )
2893     {
2894       cursorPosition = 0u;
2895     }
2896     else
2897     {
2898       cursorPosition -= numberOfWhiteSpaces;
2899     }
2900   }
2901
2902   if( retrieveText )
2903   {
2904     if( !mImpl->IsShowingPlaceholderText() )
2905     {
2906       // Retrieves the normal text string.
2907       mImpl->GetText( numberOfWhiteSpaces, text );
2908     }
2909     else
2910     {
2911       // When the current text is Placeholder Text, the surrounding text should be empty string.
2912       // It means DALi should send empty string ("") to IME.
2913       text = "";
2914     }
2915   }
2916
2917   InputMethodContext::CallbackData callbackData( ( retrieveText || retrieveCursor ), cursorPosition, text, false );
2918
2919   if( requestRelayout &&
2920       ( NULL != mImpl->mEditableControlInterface ) )
2921   {
2922     // Do this last since it provides callbacks into application code
2923     mImpl->mEditableControlInterface->TextChanged();
2924   }
2925
2926   return callbackData;
2927 }
2928
2929 void Controller::PasteClipboardItemEvent()
2930 {
2931   // Retrieve the clipboard contents first
2932   ClipboardEventNotifier notifier( ClipboardEventNotifier::Get() );
2933   std::string stringToPaste( notifier.GetContent() );
2934
2935   // Commit the current pre-edit text; the contents of the clipboard should be appended
2936   mImpl->ResetInputMethodContext();
2937
2938   // Temporary disable hiding clipboard
2939   mImpl->SetClipboardHideEnable( false );
2940
2941   // Paste
2942   PasteText( stringToPaste );
2943
2944   mImpl->SetClipboardHideEnable( true );
2945 }
2946
2947 // protected : Inherit from Text::Decorator::ControllerInterface.
2948
2949 void Controller::GetTargetSize( Vector2& targetSize )
2950 {
2951   targetSize = mImpl->mModel->mVisualModel->mControlSize;
2952 }
2953
2954 void Controller::AddDecoration( Actor& actor, bool needsClipping )
2955 {
2956   if( NULL != mImpl->mEditableControlInterface )
2957   {
2958     mImpl->mEditableControlInterface->AddDecoration( actor, needsClipping );
2959   }
2960 }
2961
2962 void Controller::DecorationEvent( HandleType handleType, HandleState state, float x, float y )
2963 {
2964   DALI_ASSERT_DEBUG( mImpl->mEventData && "Unexpected DecorationEvent" );
2965
2966   if( NULL != mImpl->mEventData )
2967   {
2968     switch( handleType )
2969     {
2970       case GRAB_HANDLE:
2971       {
2972         Event event( Event::GRAB_HANDLE_EVENT );
2973         event.p1.mUint  = state;
2974         event.p2.mFloat = x;
2975         event.p3.mFloat = y;
2976
2977         mImpl->mEventData->mEventQueue.push_back( event );
2978         break;
2979       }
2980       case LEFT_SELECTION_HANDLE:
2981       {
2982         Event event( Event::LEFT_SELECTION_HANDLE_EVENT );
2983         event.p1.mUint  = state;
2984         event.p2.mFloat = x;
2985         event.p3.mFloat = y;
2986
2987         mImpl->mEventData->mEventQueue.push_back( event );
2988         break;
2989       }
2990       case RIGHT_SELECTION_HANDLE:
2991       {
2992         Event event( Event::RIGHT_SELECTION_HANDLE_EVENT );
2993         event.p1.mUint  = state;
2994         event.p2.mFloat = x;
2995         event.p3.mFloat = y;
2996
2997         mImpl->mEventData->mEventQueue.push_back( event );
2998         break;
2999       }
3000       case LEFT_SELECTION_HANDLE_MARKER:
3001       case RIGHT_SELECTION_HANDLE_MARKER:
3002       {
3003         // Markers do not move the handles.
3004         break;
3005       }
3006       case HANDLE_TYPE_COUNT:
3007       {
3008         DALI_ASSERT_DEBUG( !"Controller::HandleEvent. Unexpected handle type" );
3009       }
3010     }
3011
3012     mImpl->RequestRelayout();
3013   }
3014 }
3015
3016 // protected : Inherit from TextSelectionPopup::TextPopupButtonCallbackInterface.
3017
3018 void Controller::TextPopupButtonTouched( Dali::Toolkit::TextSelectionPopup::Buttons button )
3019 {
3020   if( NULL == mImpl->mEventData )
3021   {
3022     return;
3023   }
3024
3025   switch( button )
3026   {
3027     case Toolkit::TextSelectionPopup::CUT:
3028     {
3029       mImpl->SendSelectionToClipboard( true ); // Synchronous call to modify text
3030       mImpl->mOperationsPending = ALL_OPERATIONS;
3031
3032       if( ( 0u != mImpl->mModel->mLogicalModel->mText.Count() ) ||
3033           !mImpl->IsPlaceholderAvailable() )
3034       {
3035         mImpl->QueueModifyEvent( ModifyEvent::TEXT_DELETED );
3036       }
3037       else
3038       {
3039         ShowPlaceholderText();
3040       }
3041
3042       mImpl->mEventData->mUpdateCursorPosition = true;
3043       mImpl->mEventData->mScrollAfterDelete = true;
3044
3045       mImpl->RequestRelayout();
3046
3047       if( NULL != mImpl->mEditableControlInterface )
3048       {
3049         mImpl->mEditableControlInterface->TextChanged();
3050       }
3051       break;
3052     }
3053     case Toolkit::TextSelectionPopup::COPY:
3054     {
3055       mImpl->SendSelectionToClipboard( false ); // Text not modified
3056
3057       mImpl->mEventData->mUpdateCursorPosition = true;
3058
3059       mImpl->RequestRelayout(); // Cursor, Handles, Selection Highlight, Popup
3060       break;
3061     }
3062     case Toolkit::TextSelectionPopup::PASTE:
3063     {
3064       mImpl->RequestGetTextFromClipboard(); // Request clipboard service to retrieve an item
3065       break;
3066     }
3067     case Toolkit::TextSelectionPopup::SELECT:
3068     {
3069       const Vector2& currentCursorPosition = mImpl->mEventData->mDecorator->GetPosition( PRIMARY_CURSOR );
3070
3071       if( mImpl->mEventData->mSelectionEnabled )
3072       {
3073         // Creates a SELECT event.
3074         SelectEvent( currentCursorPosition.x, currentCursorPosition.y, false );
3075       }
3076       break;
3077     }
3078     case Toolkit::TextSelectionPopup::SELECT_ALL:
3079     {
3080       // Creates a SELECT_ALL event
3081       SelectEvent( 0.f, 0.f, true );
3082       break;
3083     }
3084     case Toolkit::TextSelectionPopup::CLIPBOARD:
3085     {
3086       mImpl->ShowClipboard();
3087       break;
3088     }
3089     case Toolkit::TextSelectionPopup::NONE:
3090     {
3091       // Nothing to do.
3092       break;
3093     }
3094   }
3095 }
3096
3097 void Controller::DisplayTimeExpired()
3098 {
3099   mImpl->mEventData->mUpdateCursorPosition = true;
3100   // Apply modifications to the model
3101   mImpl->mOperationsPending = ALL_OPERATIONS;
3102
3103   mImpl->RequestRelayout();
3104 }
3105
3106 // private : Update.
3107
3108 void Controller::InsertText( const std::string& text, Controller::InsertType type )
3109 {
3110   bool removedPrevious = false;
3111   bool removedSelected = false;
3112   bool maxLengthReached = false;
3113
3114   DALI_ASSERT_DEBUG( NULL != mImpl->mEventData && "Unexpected InsertText" )
3115
3116   if( NULL == mImpl->mEventData )
3117   {
3118     return;
3119   }
3120
3121   DALI_LOG_INFO( gLogFilter, Debug::Verbose, "Controller::InsertText %p %s (%s) mPrimaryCursorPosition %d mPreEditFlag %d mPreEditStartPosition %d mPreEditLength %d\n",
3122                  this, text.c_str(), (COMMIT == type ? "COMMIT" : "PRE_EDIT"),
3123                  mImpl->mEventData->mPrimaryCursorPosition, mImpl->mEventData->mPreEditFlag, mImpl->mEventData->mPreEditStartPosition, mImpl->mEventData->mPreEditLength );
3124
3125   // TODO: At the moment the underline runs are only for pre-edit.
3126   mImpl->mModel->mVisualModel->mUnderlineRuns.Clear();
3127
3128   // Remove the previous InputMethodContext pre-edit.
3129   if( mImpl->mEventData->mPreEditFlag && ( 0u != mImpl->mEventData->mPreEditLength ) )
3130   {
3131     removedPrevious = RemoveText( -static_cast<int>( mImpl->mEventData->mPrimaryCursorPosition - mImpl->mEventData->mPreEditStartPosition ),
3132                                   mImpl->mEventData->mPreEditLength,
3133                                   DONT_UPDATE_INPUT_STYLE );
3134
3135     mImpl->mEventData->mPrimaryCursorPosition = mImpl->mEventData->mPreEditStartPosition;
3136     mImpl->mEventData->mPreEditLength = 0u;
3137   }
3138   else
3139   {
3140     // Remove the previous Selection.
3141     removedSelected = RemoveSelectedText();
3142
3143   }
3144
3145   Vector<Character> utf32Characters;
3146   Length characterCount = 0u;
3147
3148   if( !text.empty() )
3149   {
3150     //  Convert text into UTF-32
3151     utf32Characters.Resize( text.size() );
3152
3153     // This is a bit horrible but std::string returns a (signed) char*
3154     const uint8_t* utf8 = reinterpret_cast<const uint8_t*>( text.c_str() );
3155
3156     // Transform a text array encoded in utf8 into an array encoded in utf32.
3157     // It returns the actual number of characters.
3158     characterCount = Utf8ToUtf32( utf8, text.size(), utf32Characters.Begin() );
3159     utf32Characters.Resize( characterCount );
3160
3161     DALI_ASSERT_DEBUG( text.size() >= utf32Characters.Count() && "Invalid UTF32 conversion length" );
3162     DALI_LOG_INFO( gLogFilter, Debug::Verbose, "UTF8 size %d, UTF32 size %d\n", text.size(), utf32Characters.Count() );
3163   }
3164
3165   if( 0u != utf32Characters.Count() ) // Check if Utf8ToUtf32 conversion succeeded
3166   {
3167     // The placeholder text is no longer needed
3168     if( mImpl->IsShowingPlaceholderText() )
3169     {
3170       ResetText();
3171     }
3172
3173     mImpl->ChangeState( EventData::EDITING );
3174
3175     // Handle the InputMethodContext (predicitive text) state changes
3176     if( COMMIT == type )
3177     {
3178       // InputMethodContext is no longer handling key-events
3179       mImpl->ClearPreEditFlag();
3180     }
3181     else // PRE_EDIT
3182     {
3183       if( !mImpl->mEventData->mPreEditFlag )
3184       {
3185         DALI_LOG_INFO( gLogFilter, Debug::Verbose, "Entered PreEdit state\n" );
3186
3187         // Record the start of the pre-edit text
3188         mImpl->mEventData->mPreEditStartPosition = mImpl->mEventData->mPrimaryCursorPosition;
3189       }
3190
3191       mImpl->mEventData->mPreEditLength = utf32Characters.Count();
3192       mImpl->mEventData->mPreEditFlag = true;
3193
3194       DALI_LOG_INFO( gLogFilter, Debug::Verbose, "mPreEditStartPosition %d mPreEditLength %d\n", mImpl->mEventData->mPreEditStartPosition, mImpl->mEventData->mPreEditLength );
3195     }
3196
3197     const Length numberOfCharactersInModel = mImpl->mModel->mLogicalModel->mText.Count();
3198
3199     // Restrict new text to fit within Maximum characters setting.
3200     Length maxSizeOfNewText = std::min( ( mImpl->mMaximumNumberOfCharacters - numberOfCharactersInModel ), characterCount );
3201     maxLengthReached = ( characterCount > maxSizeOfNewText );
3202
3203     // The cursor position.
3204     CharacterIndex& cursorIndex = mImpl->mEventData->mPrimaryCursorPosition;
3205
3206     // Update the text's style.
3207
3208     // Updates the text style runs by adding characters.
3209     mImpl->mModel->mLogicalModel->UpdateTextStyleRuns( cursorIndex, maxSizeOfNewText );
3210
3211     // Get the character index from the cursor index.
3212     const CharacterIndex styleIndex = ( cursorIndex > 0u ) ? cursorIndex - 1u : 0u;
3213
3214     // Retrieve the text's style for the given index.
3215     InputStyle style;
3216     mImpl->RetrieveDefaultInputStyle( style );
3217     mImpl->mModel->mLogicalModel->RetrieveStyle( styleIndex, style );
3218
3219     // Whether to add a new text color run.
3220     const bool addColorRun = ( style.textColor != mImpl->mEventData->mInputStyle.textColor );
3221
3222     // Whether to add a new font run.
3223     const bool addFontNameRun = style.familyName != mImpl->mEventData->mInputStyle.familyName;
3224     const bool addFontWeightRun = style.weight != mImpl->mEventData->mInputStyle.weight;
3225     const bool addFontWidthRun = style.width != mImpl->mEventData->mInputStyle.width;
3226     const bool addFontSlantRun = style.slant != mImpl->mEventData->mInputStyle.slant;
3227     const bool addFontSizeRun = style.size != mImpl->mEventData->mInputStyle.size;
3228
3229     // Add style runs.
3230     if( addColorRun )
3231     {
3232       const VectorBase::SizeType numberOfRuns = mImpl->mModel->mLogicalModel->mColorRuns.Count();
3233       mImpl->mModel->mLogicalModel->mColorRuns.Resize( numberOfRuns + 1u );
3234
3235       ColorRun& colorRun = *( mImpl->mModel->mLogicalModel->mColorRuns.Begin() + numberOfRuns );
3236       colorRun.color = mImpl->mEventData->mInputStyle.textColor;
3237       colorRun.characterRun.characterIndex = cursorIndex;
3238       colorRun.characterRun.numberOfCharacters = maxSizeOfNewText;
3239     }
3240
3241     if( addFontNameRun   ||
3242         addFontWeightRun ||
3243         addFontWidthRun  ||
3244         addFontSlantRun  ||
3245         addFontSizeRun )
3246     {
3247       const VectorBase::SizeType numberOfRuns = mImpl->mModel->mLogicalModel->mFontDescriptionRuns.Count();
3248       mImpl->mModel->mLogicalModel->mFontDescriptionRuns.Resize( numberOfRuns + 1u );
3249
3250       FontDescriptionRun& fontDescriptionRun = *( mImpl->mModel->mLogicalModel->mFontDescriptionRuns.Begin() + numberOfRuns );
3251
3252       if( addFontNameRun )
3253       {
3254         fontDescriptionRun.familyLength = mImpl->mEventData->mInputStyle.familyName.size();
3255         fontDescriptionRun.familyName = new char[fontDescriptionRun.familyLength];
3256         memcpy( fontDescriptionRun.familyName, mImpl->mEventData->mInputStyle.familyName.c_str(), fontDescriptionRun.familyLength );
3257         fontDescriptionRun.familyDefined = true;
3258
3259         // The memory allocated for the font family name is freed when the font description is removed from the logical model.
3260       }
3261
3262       if( addFontWeightRun )
3263       {
3264         fontDescriptionRun.weight = mImpl->mEventData->mInputStyle.weight;
3265         fontDescriptionRun.weightDefined = true;
3266       }
3267
3268       if( addFontWidthRun )
3269       {
3270         fontDescriptionRun.width = mImpl->mEventData->mInputStyle.width;
3271         fontDescriptionRun.widthDefined = true;
3272       }
3273
3274       if( addFontSlantRun )
3275       {
3276         fontDescriptionRun.slant = mImpl->mEventData->mInputStyle.slant;
3277         fontDescriptionRun.slantDefined = true;
3278       }
3279
3280       if( addFontSizeRun )
3281       {
3282         fontDescriptionRun.size = static_cast<PointSize26Dot6>( mImpl->mEventData->mInputStyle.size * 64.f );
3283         fontDescriptionRun.sizeDefined = true;
3284       }
3285
3286       fontDescriptionRun.characterRun.characterIndex = cursorIndex;
3287       fontDescriptionRun.characterRun.numberOfCharacters = maxSizeOfNewText;
3288     }
3289
3290     // Insert at current cursor position.
3291     Vector<Character>& modifyText = mImpl->mModel->mLogicalModel->mText;
3292
3293     if( cursorIndex < numberOfCharactersInModel )
3294     {
3295       modifyText.Insert( modifyText.Begin() + cursorIndex, utf32Characters.Begin(), utf32Characters.Begin() + maxSizeOfNewText );
3296     }
3297     else
3298     {
3299       modifyText.Insert( modifyText.End(), utf32Characters.Begin(), utf32Characters.Begin() + maxSizeOfNewText );
3300     }
3301
3302     // Mark the first paragraph to be updated.
3303     if( Layout::Engine::SINGLE_LINE_BOX == mImpl->mLayoutEngine.GetLayout() )
3304     {
3305       mImpl->mTextUpdateInfo.mCharacterIndex = 0;
3306       mImpl->mTextUpdateInfo.mNumberOfCharactersToRemove = mImpl->mTextUpdateInfo.mPreviousNumberOfCharacters;
3307       mImpl->mTextUpdateInfo.mNumberOfCharactersToAdd = numberOfCharactersInModel + maxSizeOfNewText;
3308       mImpl->mTextUpdateInfo.mClearAll = true;
3309     }
3310     else
3311     {
3312       mImpl->mTextUpdateInfo.mCharacterIndex = std::min( cursorIndex, mImpl->mTextUpdateInfo.mCharacterIndex );
3313       mImpl->mTextUpdateInfo.mNumberOfCharactersToAdd += maxSizeOfNewText;
3314     }
3315
3316     // Update the cursor index.
3317     cursorIndex += maxSizeOfNewText;
3318
3319     DALI_LOG_INFO( gLogFilter, Debug::Verbose, "Inserted %d characters, new size %d new cursor %d\n", maxSizeOfNewText, mImpl->mModel->mLogicalModel->mText.Count(), mImpl->mEventData->mPrimaryCursorPosition );
3320   }
3321
3322   if( ( 0u == mImpl->mModel->mLogicalModel->mText.Count() ) &&
3323       mImpl->IsPlaceholderAvailable() )
3324   {
3325     // Show place-holder if empty after removing the pre-edit text
3326     ShowPlaceholderText();
3327     mImpl->mEventData->mUpdateCursorPosition = true;
3328     mImpl->ClearPreEditFlag();
3329   }
3330   else if( removedPrevious ||
3331            removedSelected ||
3332            ( 0 != utf32Characters.Count() ) )
3333   {
3334     // Queue an inserted event
3335     mImpl->QueueModifyEvent( ModifyEvent::TEXT_INSERTED );
3336
3337     mImpl->mEventData->mUpdateCursorPosition = true;
3338     if( removedSelected )
3339     {
3340       mImpl->mEventData->mScrollAfterDelete = true;
3341     }
3342     else
3343     {
3344       mImpl->mEventData->mScrollAfterUpdatePosition = true;
3345     }
3346   }
3347
3348   if( maxLengthReached )
3349   {
3350     DALI_LOG_INFO( gLogFilter, Debug::Verbose, "MaxLengthReached (%d)\n", mImpl->mModel->mLogicalModel->mText.Count() );
3351
3352     mImpl->ResetInputMethodContext();
3353
3354     if( NULL != mImpl->mEditableControlInterface )
3355     {
3356       // Do this last since it provides callbacks into application code
3357       mImpl->mEditableControlInterface->MaxLengthReached();
3358     }
3359   }
3360 }
3361
3362 void Controller::PasteText( const std::string& stringToPaste )
3363 {
3364   InsertText( stringToPaste, Text::Controller::COMMIT );
3365   mImpl->ChangeState( EventData::EDITING );
3366   mImpl->RequestRelayout();
3367
3368   if( NULL != mImpl->mEditableControlInterface )
3369   {
3370     // Do this last since it provides callbacks into application code
3371     mImpl->mEditableControlInterface->TextChanged();
3372   }
3373 }
3374
3375 bool Controller::RemoveText( int cursorOffset,
3376                              int numberOfCharacters,
3377                              UpdateInputStyleType type )
3378 {
3379   bool removed = false;
3380
3381   if( NULL == mImpl->mEventData )
3382   {
3383     return removed;
3384   }
3385
3386   DALI_LOG_INFO( gLogFilter, Debug::General, "Controller::RemoveText %p mText.Count() %d cursor %d cursorOffset %d numberOfCharacters %d\n",
3387                  this, mImpl->mModel->mLogicalModel->mText.Count(), mImpl->mEventData->mPrimaryCursorPosition, cursorOffset, numberOfCharacters );
3388
3389   if( !mImpl->IsShowingPlaceholderText() )
3390   {
3391     // Delete at current cursor position
3392     Vector<Character>& currentText = mImpl->mModel->mLogicalModel->mText;
3393     CharacterIndex& oldCursorIndex = mImpl->mEventData->mPrimaryCursorPosition;
3394
3395     CharacterIndex cursorIndex = 0;
3396
3397     // Validate the cursor position & number of characters
3398     if( ( static_cast< int >( mImpl->mEventData->mPrimaryCursorPosition ) + cursorOffset ) >= 0 )
3399     {
3400       cursorIndex = mImpl->mEventData->mPrimaryCursorPosition + cursorOffset;
3401     }
3402
3403     if( ( cursorIndex + numberOfCharacters ) > currentText.Count() )
3404     {
3405       numberOfCharacters = currentText.Count() - cursorIndex;
3406     }
3407
3408     if( mImpl->mEventData->mPreEditFlag || // If the preedit flag is enabled, it means two (or more) of them came together i.e. when two keys have been pressed at the same time.
3409         ( ( cursorIndex + numberOfCharacters ) <= mImpl->mTextUpdateInfo.mPreviousNumberOfCharacters ) )
3410     {
3411       // Mark the paragraphs to be updated.
3412       if( Layout::Engine::SINGLE_LINE_BOX == mImpl->mLayoutEngine.GetLayout() )
3413       {
3414         mImpl->mTextUpdateInfo.mCharacterIndex = 0;
3415         mImpl->mTextUpdateInfo.mNumberOfCharactersToRemove = mImpl->mTextUpdateInfo.mPreviousNumberOfCharacters;
3416         mImpl->mTextUpdateInfo.mNumberOfCharactersToAdd = mImpl->mTextUpdateInfo.mPreviousNumberOfCharacters - numberOfCharacters;
3417         mImpl->mTextUpdateInfo.mClearAll = true;
3418       }
3419       else
3420       {
3421         mImpl->mTextUpdateInfo.mCharacterIndex = std::min( cursorIndex, mImpl->mTextUpdateInfo.mCharacterIndex );
3422         mImpl->mTextUpdateInfo.mNumberOfCharactersToRemove += numberOfCharacters;
3423       }
3424
3425       // Update the input style and remove the text's style before removing the text.
3426
3427       if( UPDATE_INPUT_STYLE == type )
3428       {
3429         // Keep a copy of the current input style.
3430         InputStyle currentInputStyle;
3431         currentInputStyle.Copy( mImpl->mEventData->mInputStyle );
3432
3433         // Set first the default input style.
3434         mImpl->RetrieveDefaultInputStyle( mImpl->mEventData->mInputStyle );
3435
3436         // Update the input style.
3437         mImpl->mModel->mLogicalModel->RetrieveStyle( cursorIndex, mImpl->mEventData->mInputStyle );
3438
3439         // Compare if the input style has changed.
3440         const bool hasInputStyleChanged = !currentInputStyle.Equal( mImpl->mEventData->mInputStyle );
3441
3442         if( hasInputStyleChanged )
3443         {
3444           const InputStyle::Mask styleChangedMask = currentInputStyle.GetInputStyleChangeMask( mImpl->mEventData->mInputStyle );
3445           // Queue the input style changed signal.
3446           mImpl->mEventData->mInputStyleChangedQueue.PushBack( styleChangedMask );
3447         }
3448       }
3449
3450       // Updates the text style runs by removing characters. Runs with no characters are removed.
3451       mImpl->mModel->mLogicalModel->UpdateTextStyleRuns( cursorIndex, -numberOfCharacters );
3452
3453       // Remove the characters.
3454       Vector<Character>::Iterator first = currentText.Begin() + cursorIndex;
3455       Vector<Character>::Iterator last  = first + numberOfCharacters;
3456
3457       currentText.Erase( first, last );
3458
3459       // Cursor position retreat
3460       oldCursorIndex = cursorIndex;
3461
3462       mImpl->mEventData->mScrollAfterDelete = true;
3463
3464       DALI_LOG_INFO( gLogFilter, Debug::General, "Controller::RemoveText %p removed %d\n", this, numberOfCharacters );
3465       removed = true;
3466     }
3467   }
3468
3469   return removed;
3470 }
3471
3472 bool Controller::RemoveSelectedText()
3473 {
3474   bool textRemoved( false );
3475
3476   if( EventData::SELECTING == mImpl->mEventData->mState )
3477   {
3478     std::string removedString;
3479     mImpl->RetrieveSelection( removedString, true );
3480
3481     if( !removedString.empty() )
3482     {
3483       textRemoved = true;
3484       mImpl->ChangeState( EventData::EDITING );
3485     }
3486   }
3487
3488   return textRemoved;
3489 }
3490
3491 // private : Relayout.
3492
3493 bool Controller::DoRelayout( const Size& size,
3494                              OperationsMask operationsRequired,
3495                              Size& layoutSize )
3496 {
3497   DALI_LOG_INFO( gLogFilter, Debug::Verbose, "-->Controller::DoRelayout %p size %f,%f\n", this, size.width, size.height );
3498   bool viewUpdated( false );
3499
3500   // Calculate the operations to be done.
3501   const OperationsMask operations = static_cast<OperationsMask>( mImpl->mOperationsPending & operationsRequired );
3502
3503   const CharacterIndex startIndex = mImpl->mTextUpdateInfo.mParagraphCharacterIndex;
3504   const Length requestedNumberOfCharacters = mImpl->mTextUpdateInfo.mRequestedNumberOfCharacters;
3505
3506   // Get the current layout size.
3507   layoutSize = mImpl->mModel->mVisualModel->GetLayoutSize();
3508
3509   if( NO_OPERATION != ( LAYOUT & operations ) )
3510   {
3511     DALI_LOG_INFO( gLogFilter, Debug::Verbose, "-->Controller::DoRelayout LAYOUT & operations\n");
3512
3513     // Some vectors with data needed to layout and reorder may be void
3514     // after the first time the text has been laid out.
3515     // Fill the vectors again.
3516
3517     // Calculate the number of glyphs to layout.
3518     const Vector<GlyphIndex>& charactersToGlyph = mImpl->mModel->mVisualModel->mCharactersToGlyph;
3519     const Vector<Length>& glyphsPerCharacter = mImpl->mModel->mVisualModel->mGlyphsPerCharacter;
3520     const GlyphIndex* const charactersToGlyphBuffer = charactersToGlyph.Begin();
3521     const Length* const glyphsPerCharacterBuffer = glyphsPerCharacter.Begin();
3522
3523     const CharacterIndex lastIndex = startIndex + ( ( requestedNumberOfCharacters > 0u ) ? requestedNumberOfCharacters - 1u : 0u );
3524     const GlyphIndex startGlyphIndex = mImpl->mTextUpdateInfo.mStartGlyphIndex;
3525
3526     // Make sure the index is not out of bound
3527     if ( charactersToGlyph.Count() != glyphsPerCharacter.Count() ||
3528          requestedNumberOfCharacters > charactersToGlyph.Count() ||
3529          ( lastIndex >= charactersToGlyph.Count() && charactersToGlyph.Count() > 0u ) )
3530     {
3531       std::string currentText;
3532       GetText( currentText );
3533
3534       DALI_LOG_ERROR( "Controller::DoRelayout: Attempting to access invalid buffer\n" );
3535       DALI_LOG_ERROR( "Current text is: %s\n", currentText.c_str() );
3536       DALI_LOG_ERROR( "startIndex: %u, lastIndex: %u, requestedNumberOfCharacters: %u, charactersToGlyph.Count = %lu, glyphsPerCharacter.Count = %lu\n", startIndex, lastIndex, requestedNumberOfCharacters, charactersToGlyph.Count(), glyphsPerCharacter.Count());
3537
3538       return false;
3539     }
3540
3541     const Length numberOfGlyphs = ( requestedNumberOfCharacters > 0u ) ? *( charactersToGlyphBuffer + lastIndex ) + *( glyphsPerCharacterBuffer + lastIndex ) - startGlyphIndex : 0u;
3542     const Length totalNumberOfGlyphs = mImpl->mModel->mVisualModel->mGlyphs.Count();
3543
3544     if( 0u == totalNumberOfGlyphs )
3545     {
3546       if( NO_OPERATION != ( UPDATE_LAYOUT_SIZE & operations ) )
3547       {
3548         mImpl->mModel->mVisualModel->SetLayoutSize( Size::ZERO );
3549       }
3550
3551       // Nothing else to do if there is no glyphs.
3552       DALI_LOG_INFO( gLogFilter, Debug::Verbose, "<--Controller::DoRelayout no glyphs, view updated true\n" );
3553       return true;
3554     }
3555
3556     const Vector<LineBreakInfo>& lineBreakInfo = mImpl->mModel->mLogicalModel->mLineBreakInfo;
3557     const Vector<WordBreakInfo>& wordBreakInfo = mImpl->mModel->mLogicalModel->mWordBreakInfo;
3558     const Vector<CharacterDirection>& characterDirection = mImpl->mModel->mLogicalModel->mCharacterDirections;
3559     const Vector<GlyphInfo>& glyphs = mImpl->mModel->mVisualModel->mGlyphs;
3560     const Vector<CharacterIndex>& glyphsToCharactersMap = mImpl->mModel->mVisualModel->mGlyphsToCharacters;
3561     const Vector<Length>& charactersPerGlyph = mImpl->mModel->mVisualModel->mCharactersPerGlyph;
3562     const Character* const textBuffer = mImpl->mModel->mLogicalModel->mText.Begin();
3563     const float outlineWidth = static_cast<float>( mImpl->mModel->GetOutlineWidth() );
3564
3565     // Set the layout parameters.
3566     Layout::Parameters layoutParameters( size,
3567                                          textBuffer,
3568                                          lineBreakInfo.Begin(),
3569                                          wordBreakInfo.Begin(),
3570                                          ( 0u != characterDirection.Count() ) ? characterDirection.Begin() : NULL,
3571                                          glyphs.Begin(),
3572                                          glyphsToCharactersMap.Begin(),
3573                                          charactersPerGlyph.Begin(),
3574                                          charactersToGlyphBuffer,
3575                                          glyphsPerCharacterBuffer,
3576                                          totalNumberOfGlyphs,
3577                                          mImpl->mModel->mHorizontalAlignment,
3578                                          mImpl->mModel->mLineWrapMode,
3579                                          outlineWidth,
3580                                          mImpl->mModel->mIgnoreSpacesAfterText,
3581                                          mImpl->mModel->mMatchSystemLanguageDirection );
3582
3583     // Resize the vector of positions to have the same size than the vector of glyphs.
3584     Vector<Vector2>& glyphPositions = mImpl->mModel->mVisualModel->mGlyphPositions;
3585     glyphPositions.Resize( totalNumberOfGlyphs );
3586
3587     // Whether the last character is a new paragraph character.
3588     mImpl->mTextUpdateInfo.mIsLastCharacterNewParagraph =  TextAbstraction::IsNewParagraph( *( textBuffer + ( mImpl->mModel->mLogicalModel->mText.Count() - 1u ) ) );
3589     layoutParameters.isLastNewParagraph = mImpl->mTextUpdateInfo.mIsLastCharacterNewParagraph;
3590
3591     // The initial glyph and the number of glyphs to layout.
3592     layoutParameters.startGlyphIndex = startGlyphIndex;
3593     layoutParameters.numberOfGlyphs = numberOfGlyphs;
3594     layoutParameters.startLineIndex = mImpl->mTextUpdateInfo.mStartLineIndex;
3595     layoutParameters.estimatedNumberOfLines = mImpl->mTextUpdateInfo.mEstimatedNumberOfLines;
3596
3597     // Update the ellipsis
3598     bool elideTextEnabled = mImpl->mModel->mElideEnabled;
3599
3600     if( NULL != mImpl->mEventData )
3601     {
3602       if( mImpl->mEventData->mPlaceholderEllipsisFlag && mImpl->IsShowingPlaceholderText() )
3603       {
3604         elideTextEnabled = mImpl->mEventData->mIsPlaceholderElideEnabled;
3605       }
3606       else if( EventData::INACTIVE != mImpl->mEventData->mState )
3607       {
3608         // Disable ellipsis when editing
3609         elideTextEnabled = false;
3610       }
3611
3612       // Reset the scroll position in inactive state
3613       if( elideTextEnabled && ( mImpl->mEventData->mState == EventData::INACTIVE ) )
3614       {
3615         ResetScrollPosition();
3616       }
3617     }
3618
3619     // Update the visual model.
3620     bool isAutoScrollEnabled = mImpl->mIsAutoScrollEnabled;
3621     Size newLayoutSize;
3622     viewUpdated = mImpl->mLayoutEngine.LayoutText( layoutParameters,
3623                                                    glyphPositions,
3624                                                    mImpl->mModel->mVisualModel->mLines,
3625                                                    newLayoutSize,
3626                                                    elideTextEnabled,
3627                                                    isAutoScrollEnabled );
3628     mImpl->mIsAutoScrollEnabled = isAutoScrollEnabled;
3629
3630     viewUpdated = viewUpdated || ( newLayoutSize != layoutSize );
3631
3632     if( viewUpdated )
3633     {
3634       layoutSize = newLayoutSize;
3635
3636       if( NO_OPERATION != ( UPDATE_DIRECTION & operations ) )
3637       {
3638         mImpl->mIsTextDirectionRTL = false;
3639       }
3640
3641       // Reorder the lines
3642       if( NO_OPERATION != ( REORDER & operations ) )
3643       {
3644         Vector<BidirectionalParagraphInfoRun>& bidirectionalInfo = mImpl->mModel->mLogicalModel->mBidirectionalParagraphInfo;
3645         Vector<BidirectionalLineInfoRun>& bidirectionalLineInfo = mImpl->mModel->mLogicalModel->mBidirectionalLineInfo;
3646
3647         // Check first if there are paragraphs with bidirectional info.
3648         if( 0u != bidirectionalInfo.Count() )
3649         {
3650           // Get the lines
3651           const Length numberOfLines = mImpl->mModel->mVisualModel->mLines.Count();
3652
3653           // Reorder the lines.
3654           bidirectionalLineInfo.Reserve( numberOfLines ); // Reserve because is not known yet how many lines have right to left characters.
3655           ReorderLines( bidirectionalInfo,
3656                         startIndex,
3657                         requestedNumberOfCharacters,
3658                         mImpl->mModel->mVisualModel->mLines,
3659                         bidirectionalLineInfo );
3660
3661           // Set the bidirectional info per line into the layout parameters.
3662           layoutParameters.lineBidirectionalInfoRunsBuffer = bidirectionalLineInfo.Begin();
3663           layoutParameters.numberOfBidirectionalInfoRuns = bidirectionalLineInfo.Count();
3664
3665           // Re-layout the text. Reorder those lines with right to left characters.
3666           mImpl->mLayoutEngine.ReLayoutRightToLeftLines( layoutParameters,
3667                                                          startIndex,
3668                                                          requestedNumberOfCharacters,
3669                                                          glyphPositions );
3670
3671           if ( ( NO_OPERATION != ( UPDATE_DIRECTION & operations ) ) && ( numberOfLines > 0 ) )
3672           {
3673             const LineRun* const firstline = mImpl->mModel->mVisualModel->mLines.Begin();
3674             if ( firstline )
3675             {
3676               mImpl->mIsTextDirectionRTL = firstline->direction;
3677             }
3678           }
3679         }
3680       } // REORDER
3681
3682       // Sets the layout size.
3683       if( NO_OPERATION != ( UPDATE_LAYOUT_SIZE & operations ) )
3684       {
3685         mImpl->mModel->mVisualModel->SetLayoutSize( layoutSize );
3686       }
3687     } // view updated
3688   }
3689
3690   if( NO_OPERATION != ( ALIGN & operations ) )
3691   {
3692     // The laid-out lines.
3693     Vector<LineRun>& lines = mImpl->mModel->mVisualModel->mLines;
3694
3695     // Need to align with the control's size as the text may contain lines
3696     // starting either with left to right text or right to left.
3697     mImpl->mLayoutEngine.Align( size,
3698                                 startIndex,
3699                                 requestedNumberOfCharacters,
3700                                 mImpl->mModel->mHorizontalAlignment,
3701                                 lines,
3702                                 mImpl->mModel->mAlignmentOffset,
3703                                 mImpl->mLayoutDirection,
3704                                 mImpl->mModel->mMatchSystemLanguageDirection );
3705
3706     viewUpdated = true;
3707   }
3708 #if defined(DEBUG_ENABLED)
3709   std::string currentText;
3710   GetText( currentText );
3711   DALI_LOG_INFO( gLogFilter, Debug::Concise, "Controller::DoRelayout [%p] mImpl->mIsTextDirectionRTL[%s] [%s]\n", this, (mImpl->mIsTextDirectionRTL)?"true":"false",  currentText.c_str() );
3712 #endif
3713   DALI_LOG_INFO( gLogFilter, Debug::Verbose, "<--Controller::DoRelayout, view updated %s\n", ( viewUpdated ? "true" : "false" ) );
3714   return viewUpdated;
3715 }
3716
3717 void Controller::CalculateVerticalOffset( const Size& controlSize )
3718 {
3719   Size layoutSize = mImpl->mModel->mVisualModel->GetLayoutSize();
3720
3721   if( fabsf( layoutSize.height ) < Math::MACHINE_EPSILON_1000 )
3722   {
3723     // Get the line height of the default font.
3724     layoutSize.height = mImpl->GetDefaultFontLineHeight();
3725   }
3726
3727   switch( mImpl->mModel->mVerticalAlignment )
3728   {
3729     case VerticalAlignment::TOP:
3730     {
3731       mImpl->mModel->mScrollPosition.y = 0.f;
3732       break;
3733     }
3734     case VerticalAlignment::CENTER:
3735     {
3736       mImpl->mModel->mScrollPosition.y = floorf( 0.5f * ( controlSize.height - layoutSize.height ) ); // try to avoid pixel alignment.
3737       break;
3738     }
3739     case VerticalAlignment::BOTTOM:
3740     {
3741       mImpl->mModel->mScrollPosition.y = controlSize.height - layoutSize.height;
3742       break;
3743     }
3744   }
3745 }
3746
3747 // private : Events.
3748
3749 void Controller::ProcessModifyEvents()
3750 {
3751   Vector<ModifyEvent>& events = mImpl->mModifyEvents;
3752
3753   if( 0u == events.Count() )
3754   {
3755     // Nothing to do.
3756     return;
3757   }
3758
3759   for( Vector<ModifyEvent>::ConstIterator it = events.Begin(),
3760          endIt = events.End();
3761        it != endIt;
3762        ++it )
3763   {
3764     const ModifyEvent& event = *it;
3765
3766     if( ModifyEvent::TEXT_REPLACED == event.type )
3767     {
3768       // A (single) replace event should come first, otherwise we wasted time processing NOOP events
3769       DALI_ASSERT_DEBUG( it == events.Begin() && "Unexpected TEXT_REPLACED event" );
3770
3771       TextReplacedEvent();
3772     }
3773     else if( ModifyEvent::TEXT_INSERTED == event.type )
3774     {
3775       TextInsertedEvent();
3776     }
3777     else if( ModifyEvent::TEXT_DELETED == event.type )
3778     {
3779       // Placeholder-text cannot be deleted
3780       if( !mImpl->IsShowingPlaceholderText() )
3781       {
3782         TextDeletedEvent();
3783       }
3784     }
3785   }
3786
3787   if( NULL != mImpl->mEventData )
3788   {
3789     // When the text is being modified, delay cursor blinking
3790     mImpl->mEventData->mDecorator->DelayCursorBlink();
3791
3792     // Update selection position after modifying the text
3793     mImpl->mEventData->mLeftSelectionPosition = mImpl->mEventData->mPrimaryCursorPosition;
3794     mImpl->mEventData->mRightSelectionPosition = mImpl->mEventData->mPrimaryCursorPosition;
3795   }
3796
3797   // Discard temporary text
3798   events.Clear();
3799 }
3800
3801 void Controller::TextReplacedEvent()
3802 {
3803   // The natural size needs to be re-calculated.
3804   mImpl->mRecalculateNaturalSize = true;
3805
3806   // The text direction needs to be updated.
3807   mImpl->mUpdateTextDirection = true;
3808
3809   // Apply modifications to the model
3810   mImpl->mOperationsPending = ALL_OPERATIONS;
3811 }
3812
3813 void Controller::TextInsertedEvent()
3814 {
3815   DALI_ASSERT_DEBUG( NULL != mImpl->mEventData && "Unexpected TextInsertedEvent" );
3816
3817   if( NULL == mImpl->mEventData )
3818   {
3819     return;
3820   }
3821
3822   mImpl->mEventData->mCheckScrollAmount = true;
3823
3824   // The natural size needs to be re-calculated.
3825   mImpl->mRecalculateNaturalSize = true;
3826
3827   // The text direction needs to be updated.
3828   mImpl->mUpdateTextDirection = true;
3829
3830   // Apply modifications to the model; TODO - Optimize this
3831   mImpl->mOperationsPending = ALL_OPERATIONS;
3832 }
3833
3834 void Controller::TextDeletedEvent()
3835 {
3836   DALI_ASSERT_DEBUG( NULL != mImpl->mEventData && "Unexpected TextDeletedEvent" );
3837
3838   if( NULL == mImpl->mEventData )
3839   {
3840     return;
3841   }
3842
3843   mImpl->mEventData->mCheckScrollAmount = true;
3844
3845   // The natural size needs to be re-calculated.
3846   mImpl->mRecalculateNaturalSize = true;
3847
3848   // The text direction needs to be updated.
3849   mImpl->mUpdateTextDirection = true;
3850
3851   // Apply modifications to the model; TODO - Optimize this
3852   mImpl->mOperationsPending = ALL_OPERATIONS;
3853 }
3854
3855 void Controller::SelectEvent( float x, float y, bool selectAll )
3856 {
3857   DALI_LOG_INFO( gLogFilter, Debug::Verbose, "Controller::SelectEvent\n" );
3858
3859   if( NULL != mImpl->mEventData )
3860   {
3861     if( selectAll )
3862     {
3863       Event event( Event::SELECT_ALL );
3864       mImpl->mEventData->mEventQueue.push_back( event );
3865     }
3866     else
3867     {
3868       Event event( Event::SELECT );
3869       event.p2.mFloat = x;
3870       event.p3.mFloat = y;
3871       mImpl->mEventData->mEventQueue.push_back( event );
3872     }
3873
3874     mImpl->mEventData->mCheckScrollAmount = true;
3875     mImpl->mEventData->mIsLeftHandleSelected = true;
3876     mImpl->mEventData->mIsRightHandleSelected = true;
3877     mImpl->RequestRelayout();
3878   }
3879 }
3880
3881 bool Controller::DeleteEvent( int keyCode )
3882 {
3883   DALI_LOG_INFO( gLogFilter, Debug::Verbose, "Controller::KeyEvent %p KeyCode : %d \n", this, keyCode );
3884
3885   bool removed = false;
3886
3887   if( NULL == mImpl->mEventData )
3888   {
3889     return removed;
3890   }
3891
3892   // InputMethodContext is no longer handling key-events
3893   mImpl->ClearPreEditFlag();
3894
3895   if( EventData::SELECTING == mImpl->mEventData->mState )
3896   {
3897     removed = RemoveSelectedText();
3898   }
3899   else if( ( mImpl->mEventData->mPrimaryCursorPosition > 0 ) && ( keyCode == Dali::DALI_KEY_BACKSPACE) )
3900   {
3901     // Remove the character before the current cursor position
3902     removed = RemoveText( -1,
3903                           1,
3904                           UPDATE_INPUT_STYLE );
3905   }
3906   else if( keyCode == Dali::DevelKey::DALI_KEY_DELETE )
3907   {
3908     // Remove the character after the current cursor position
3909     removed = RemoveText( 0,
3910                           1,
3911                           UPDATE_INPUT_STYLE );
3912   }
3913
3914   if( removed )
3915   {
3916     if( ( 0u != mImpl->mModel->mLogicalModel->mText.Count() ) ||
3917         !mImpl->IsPlaceholderAvailable() )
3918     {
3919       mImpl->QueueModifyEvent( ModifyEvent::TEXT_DELETED );
3920     }
3921     else
3922     {
3923       ShowPlaceholderText();
3924     }
3925     mImpl->mEventData->mUpdateCursorPosition = true;
3926     mImpl->mEventData->mScrollAfterDelete = true;
3927   }
3928
3929   return removed;
3930 }
3931
3932 // private : Helpers.
3933
3934 void Controller::ResetText()
3935 {
3936   // Reset buffers.
3937   mImpl->mModel->mLogicalModel->mText.Clear();
3938
3939   // We have cleared everything including the placeholder-text
3940   mImpl->PlaceholderCleared();
3941
3942   mImpl->mTextUpdateInfo.mCharacterIndex = 0u;
3943   mImpl->mTextUpdateInfo.mNumberOfCharactersToRemove = mImpl->mTextUpdateInfo.mPreviousNumberOfCharacters;
3944   mImpl->mTextUpdateInfo.mNumberOfCharactersToAdd = 0u;
3945
3946   // Clear any previous text.
3947   mImpl->mTextUpdateInfo.mClearAll = true;
3948
3949   // The natural size needs to be re-calculated.
3950   mImpl->mRecalculateNaturalSize = true;
3951
3952   // The text direction needs to be updated.
3953   mImpl->mUpdateTextDirection = true;
3954
3955   // Apply modifications to the model
3956   mImpl->mOperationsPending = ALL_OPERATIONS;
3957 }
3958
3959 void Controller::ShowPlaceholderText()
3960 {
3961   if( mImpl->IsPlaceholderAvailable() )
3962   {
3963     DALI_ASSERT_DEBUG( mImpl->mEventData && "No placeholder text available" );
3964
3965     if( NULL == mImpl->mEventData )
3966     {
3967       return;
3968     }
3969
3970     mImpl->mEventData->mIsShowingPlaceholderText = true;
3971
3972     // Disable handles when showing place-holder text
3973     mImpl->mEventData->mDecorator->SetHandleActive( GRAB_HANDLE, false );
3974     mImpl->mEventData->mDecorator->SetHandleActive( LEFT_SELECTION_HANDLE, false );
3975     mImpl->mEventData->mDecorator->SetHandleActive( RIGHT_SELECTION_HANDLE, false );
3976
3977     const char* text( NULL );
3978     size_t size( 0 );
3979
3980     // TODO - Switch Placeholder text when changing state
3981     if( ( EventData::INACTIVE != mImpl->mEventData->mState ) &&
3982         ( 0u != mImpl->mEventData->mPlaceholderTextActive.c_str() ) )
3983     {
3984       text = mImpl->mEventData->mPlaceholderTextActive.c_str();
3985       size = mImpl->mEventData->mPlaceholderTextActive.size();
3986     }
3987     else
3988     {
3989       text = mImpl->mEventData->mPlaceholderTextInactive.c_str();
3990       size = mImpl->mEventData->mPlaceholderTextInactive.size();
3991     }
3992
3993     mImpl->mTextUpdateInfo.mCharacterIndex = 0u;
3994     mImpl->mTextUpdateInfo.mNumberOfCharactersToRemove = mImpl->mTextUpdateInfo.mPreviousNumberOfCharacters;
3995
3996     // Reset model for showing placeholder.
3997     mImpl->mModel->mLogicalModel->mText.Clear();
3998     mImpl->mModel->mVisualModel->SetTextColor( mImpl->mEventData->mPlaceholderTextColor );
3999
4000     // Convert text into UTF-32
4001     Vector<Character>& utf32Characters = mImpl->mModel->mLogicalModel->mText;
4002     utf32Characters.Resize( size );
4003
4004     // This is a bit horrible but std::string returns a (signed) char*
4005     const uint8_t* utf8 = reinterpret_cast<const uint8_t*>( text );
4006
4007     // Transform a text array encoded in utf8 into an array encoded in utf32.
4008     // It returns the actual number of characters.
4009     const Length characterCount = Utf8ToUtf32( utf8, size, utf32Characters.Begin() );
4010     utf32Characters.Resize( characterCount );
4011
4012     // The characters to be added.
4013     mImpl->mTextUpdateInfo.mNumberOfCharactersToAdd = characterCount;
4014
4015     // Reset the cursor position
4016     mImpl->mEventData->mPrimaryCursorPosition = 0;
4017
4018     // The natural size needs to be re-calculated.
4019     mImpl->mRecalculateNaturalSize = true;
4020
4021     // The text direction needs to be updated.
4022     mImpl->mUpdateTextDirection = true;
4023
4024     // Apply modifications to the model
4025     mImpl->mOperationsPending = ALL_OPERATIONS;
4026
4027     // Update the rest of the model during size negotiation
4028     mImpl->QueueModifyEvent( ModifyEvent::TEXT_REPLACED );
4029   }
4030 }
4031
4032 void Controller::ClearFontData()
4033 {
4034   if( mImpl->mFontDefaults )
4035   {
4036     mImpl->mFontDefaults->mFontId = 0u; // Remove old font ID
4037   }
4038
4039   // Set flags to update the model.
4040   mImpl->mTextUpdateInfo.mCharacterIndex = 0u;
4041   mImpl->mTextUpdateInfo.mNumberOfCharactersToRemove = mImpl->mTextUpdateInfo.mPreviousNumberOfCharacters;
4042   mImpl->mTextUpdateInfo.mNumberOfCharactersToAdd = mImpl->mModel->mLogicalModel->mText.Count();
4043
4044   mImpl->mTextUpdateInfo.mClearAll = true;
4045   mImpl->mTextUpdateInfo.mFullRelayoutNeeded = true;
4046   mImpl->mRecalculateNaturalSize = true;
4047
4048   mImpl->mOperationsPending = static_cast<OperationsMask>( mImpl->mOperationsPending |
4049                                                            VALIDATE_FONTS            |
4050                                                            SHAPE_TEXT                |
4051                                                            BIDI_INFO                 |
4052                                                            GET_GLYPH_METRICS         |
4053                                                            LAYOUT                    |
4054                                                            UPDATE_LAYOUT_SIZE        |
4055                                                            REORDER                   |
4056                                                            ALIGN );
4057 }
4058
4059 void Controller::ClearStyleData()
4060 {
4061   mImpl->mModel->mLogicalModel->mColorRuns.Clear();
4062   mImpl->mModel->mLogicalModel->ClearFontDescriptionRuns();
4063 }
4064
4065 void Controller::ResetCursorPosition( CharacterIndex cursorIndex )
4066 {
4067   // Reset the cursor position
4068   if( NULL != mImpl->mEventData )
4069   {
4070     mImpl->mEventData->mPrimaryCursorPosition = cursorIndex;
4071
4072     // Update the cursor if it's in editing mode.
4073     if( EventData::IsEditingState( mImpl->mEventData->mState )  )
4074     {
4075       mImpl->mEventData->mUpdateCursorPosition = true;
4076     }
4077   }
4078 }
4079
4080 void Controller::ResetScrollPosition()
4081 {
4082   if( NULL != mImpl->mEventData )
4083   {
4084     // Reset the scroll position.
4085     mImpl->mModel->mScrollPosition = Vector2::ZERO;
4086     mImpl->mEventData->mScrollAfterUpdatePosition = true;
4087   }
4088 }
4089
4090 void Controller::SetControlInterface( ControlInterface* controlInterface )
4091 {
4092   mImpl->mControlInterface = controlInterface;
4093 }
4094
4095 bool Controller::ShouldClearFocusOnEscape() const
4096 {
4097   return mImpl->mShouldClearFocusOnEscape;
4098 }
4099
4100 // private : Private contructors & copy operator.
4101
4102 Controller::Controller()
4103 : mImpl( NULL )
4104 {
4105   mImpl = new Controller::Impl( NULL, NULL );
4106 }
4107
4108 Controller::Controller( ControlInterface* controlInterface )
4109 {
4110   mImpl = new Controller::Impl( controlInterface, NULL );
4111 }
4112
4113 Controller::Controller( ControlInterface* controlInterface,
4114                         EditableControlInterface* editableControlInterface )
4115 {
4116   mImpl = new Controller::Impl( controlInterface,
4117                                 editableControlInterface );
4118 }
4119
4120 // The copy constructor and operator are left unimplemented.
4121
4122 // protected : Destructor.
4123
4124 Controller::~Controller()
4125 {
4126   delete mImpl;
4127 }
4128
4129 } // namespace Text
4130
4131 } // namespace Toolkit
4132
4133 } // namespace Dali