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