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