[Tizen] We also need to change the cursor position when the layout direction changes.
[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       if( mImpl->mEventData )
2573       {
2574         mImpl->mEventData->mUpdateAlignment = true;
2575         mImpl->mEventData->mUpdateCursorPosition = true;
2576       }
2577     }
2578   }
2579
2580   // Make sure the model is up-to-date before layouting.
2581   ProcessModifyEvents();
2582   bool updated = mImpl->UpdateModel( mImpl->mOperationsPending );
2583
2584   // Layout the text.
2585   Size layoutSize;
2586   updated = DoRelayout( size,
2587                         mImpl->mOperationsPending,
2588                         layoutSize ) || updated;
2589
2590
2591   if( updated )
2592   {
2593     updateTextType = MODEL_UPDATED;
2594   }
2595
2596   // Do not re-do any operation until something changes.
2597   mImpl->mOperationsPending = NO_OPERATION;
2598   mImpl->mModel->mScrollPositionLast = mImpl->mModel->mScrollPosition;
2599
2600   // Whether the text control is editable
2601   const bool isEditable = NULL != mImpl->mEventData;
2602
2603   // Keep the current offset as it will be used to update the decorator's positions (if the size changes).
2604   Vector2 offset;
2605   if( newSize && isEditable )
2606   {
2607     offset = mImpl->mModel->mScrollPosition;
2608   }
2609
2610   if( !isEditable || !IsMultiLineEnabled() )
2611   {
2612     // After doing the text layout, the vertical offset to place the actor in the desired position can be calculated.
2613     CalculateVerticalOffset( size );
2614   }
2615
2616   if( isEditable )
2617   {
2618     if( newSize )
2619     {
2620       // If there is a new size, the scroll position needs to be clamped.
2621       mImpl->ClampHorizontalScroll( layoutSize );
2622
2623       // Update the decorator's positions is needed if there is a new size.
2624       mImpl->mEventData->mDecorator->UpdatePositions( mImpl->mModel->mScrollPosition - offset );
2625     }
2626
2627     // Move the cursor, grab handle etc.
2628     if( mImpl->ProcessInputEvents() )
2629     {
2630       updateTextType = static_cast<UpdateTextType>( updateTextType | DECORATOR_UPDATED );
2631     }
2632   }
2633
2634   // Clear the update info. This info will be set the next time the text is updated.
2635   mImpl->mTextUpdateInfo.Clear();
2636   DALI_LOG_INFO( gLogFilter, Debug::Verbose, "<--Controller::Relayout\n" );
2637
2638   return updateTextType;
2639 }
2640
2641 void Controller::RequestRelayout()
2642 {
2643   mImpl->RequestRelayout();
2644 }
2645
2646 // public : Input style change signals.
2647
2648 bool Controller::IsInputStyleChangedSignalsQueueEmpty()
2649 {
2650   return ( NULL == mImpl->mEventData ) || ( 0u == mImpl->mEventData->mInputStyleChangedQueue.Count() );
2651 }
2652
2653 void Controller::ProcessInputStyleChangedSignals()
2654 {
2655   if( NULL == mImpl->mEventData )
2656   {
2657     // Nothing to do.
2658     return;
2659   }
2660
2661   for( Vector<InputStyle::Mask>::ConstIterator it = mImpl->mEventData->mInputStyleChangedQueue.Begin(),
2662          endIt = mImpl->mEventData->mInputStyleChangedQueue.End();
2663        it != endIt;
2664        ++it )
2665   {
2666     const InputStyle::Mask mask = *it;
2667
2668     if( NULL != mImpl->mEditableControlInterface )
2669     {
2670       // Emit the input style changed signal.
2671       mImpl->mEditableControlInterface->InputStyleChanged( mask );
2672     }
2673   }
2674
2675   mImpl->mEventData->mInputStyleChangedQueue.Clear();
2676 }
2677
2678 // public : Text-input Event Queuing.
2679
2680 void Controller::KeyboardFocusGainEvent()
2681 {
2682   DALI_ASSERT_DEBUG( mImpl->mEventData && "Unexpected KeyboardFocusGainEvent" );
2683
2684   if( NULL != mImpl->mEventData )
2685   {
2686     if( ( EventData::INACTIVE == mImpl->mEventData->mState ) ||
2687         ( EventData::INTERRUPTED == mImpl->mEventData->mState ) )
2688     {
2689       mImpl->ChangeState( EventData::EDITING );
2690       mImpl->mEventData->mUpdateCursorPosition = true; //If editing started without tap event, cursor update must be triggered.
2691       mImpl->mEventData->mUpdateInputStyle = true;
2692       mImpl->mEventData->mScrollAfterUpdatePosition = true;
2693     }
2694     mImpl->NotifyInputMethodContextMultiLineStatus();
2695     if( mImpl->IsShowingPlaceholderText() )
2696     {
2697       // Show alternative placeholder-text when editing
2698       ShowPlaceholderText();
2699     }
2700
2701     mImpl->RequestRelayout();
2702   }
2703 }
2704
2705 void Controller::KeyboardFocusLostEvent()
2706 {
2707   DALI_ASSERT_DEBUG( mImpl->mEventData && "Unexpected KeyboardFocusLostEvent" );
2708
2709   if( NULL != mImpl->mEventData )
2710   {
2711     if( EventData::INTERRUPTED != mImpl->mEventData->mState )
2712     {
2713       mImpl->ChangeState( EventData::INACTIVE );
2714
2715       if( !mImpl->IsShowingRealText() )
2716       {
2717         // Revert to regular placeholder-text when not editing
2718         ShowPlaceholderText();
2719       }
2720     }
2721   }
2722   mImpl->RequestRelayout();
2723 }
2724
2725 bool Controller::KeyEvent( const Dali::KeyEvent& keyEvent )
2726 {
2727   DALI_ASSERT_DEBUG( mImpl->mEventData && "Unexpected KeyEvent" );
2728
2729   bool textChanged = false;
2730   bool relayoutNeeded = false;
2731
2732   if( ( NULL != mImpl->mEventData ) &&
2733       ( keyEvent.state == KeyEvent::Down ) )
2734   {
2735     int keyCode = keyEvent.keyCode;
2736     const std::string& keyString = keyEvent.keyPressed;
2737     const std::string keyName = keyEvent.keyPressedName;
2738
2739     const bool isNullKey = ( 0 == keyCode ) && ( keyString.empty() );
2740
2741     // Pre-process to separate modifying events from non-modifying input events.
2742     if( isNullKey )
2743     {
2744       // In some platforms arrive key events with no key code.
2745       // Do nothing.
2746       return false;
2747     }
2748     else if( Dali::DALI_KEY_ESCAPE == keyCode || Dali::DALI_KEY_BACK == keyCode  || Dali::DALI_KEY_SEARCH == keyCode )
2749     {
2750       // Do nothing
2751       return false;
2752     }
2753     else if( ( Dali::DALI_KEY_CURSOR_LEFT  == keyCode ) ||
2754              ( Dali::DALI_KEY_CURSOR_RIGHT == keyCode ) ||
2755              ( Dali::DALI_KEY_CURSOR_UP    == keyCode ) ||
2756              ( Dali::DALI_KEY_CURSOR_DOWN  == keyCode ) )
2757     {
2758       // If don't have any text, do nothing.
2759       if( !mImpl->mTextUpdateInfo.mPreviousNumberOfCharacters )
2760       {
2761         return false;
2762       }
2763
2764       uint32_t cursorPosition = mImpl->mEventData->mPrimaryCursorPosition;
2765       uint32_t numberOfCharacters = mImpl->mTextUpdateInfo.mPreviousNumberOfCharacters;
2766       uint32_t cursorLine = mImpl->mModel->mVisualModel->GetLineOfCharacter( cursorPosition );
2767       uint32_t numberOfLines = mImpl->mModel->GetNumberOfLines();
2768
2769       // Logic to determine whether this text control will lose focus or not.
2770       if( ( Dali::DALI_KEY_CURSOR_LEFT == keyCode && 0 == cursorPosition && !keyEvent.IsShiftModifier() ) ||
2771           ( Dali::DALI_KEY_CURSOR_RIGHT == keyCode && numberOfCharacters == cursorPosition && !keyEvent.IsShiftModifier() ) ||
2772           ( Dali::DALI_KEY_CURSOR_DOWN == keyCode && cursorLine == numberOfLines -1 ) ||
2773           ( Dali::DALI_KEY_CURSOR_DOWN == keyCode && numberOfCharacters == cursorPosition && cursorLine -1 == numberOfLines -1 ) ||
2774           ( Dali::DALI_KEY_CURSOR_UP == keyCode && cursorLine == 0 ) ||
2775           ( Dali::DALI_KEY_CURSOR_UP == keyCode && numberOfCharacters == cursorPosition && cursorLine == 1 ) )
2776       {
2777         // Release the active highlight.
2778         if( mImpl->mEventData->mState == EventData::SELECTING )
2779         {
2780           mImpl->ChangeState( EventData::EDITING );
2781
2782           // Update selection position.
2783           mImpl->mEventData->mLeftSelectionPosition = mImpl->mEventData->mPrimaryCursorPosition;
2784           mImpl->mEventData->mRightSelectionPosition = mImpl->mEventData->mPrimaryCursorPosition;
2785           mImpl->mEventData->mUpdateCursorPosition = true;
2786           mImpl->RequestRelayout();
2787         }
2788         return false;
2789       }
2790
2791       mImpl->mEventData->mCheckScrollAmount = true;
2792       Event event( Event::CURSOR_KEY_EVENT );
2793       event.p1.mInt = keyCode;
2794       event.p2.mBool = keyEvent.IsShiftModifier();
2795       mImpl->mEventData->mEventQueue.push_back( event );
2796
2797       // Will request for relayout.
2798       relayoutNeeded = true;
2799     }
2800     else if ( Dali::DevelKey::DALI_KEY_CONTROL_LEFT == keyCode || Dali::DevelKey::DALI_KEY_CONTROL_RIGHT == keyCode )
2801     {
2802       // Left or Right Control key event is received before Ctrl-C/V/X key event is received
2803       // If not handle it here, any selected text will be deleted
2804
2805       // Do nothing
2806       return false;
2807     }
2808     else if ( keyEvent.IsCtrlModifier() )
2809     {
2810       bool consumed = false;
2811       if (keyName == KEY_C_NAME)
2812       {
2813         // Ctrl-C to copy the selected text
2814         TextPopupButtonTouched( Toolkit::TextSelectionPopup::COPY );
2815         consumed = true;
2816       }
2817       else if (keyName == KEY_V_NAME)
2818       {
2819         // Ctrl-V to paste the copied text
2820         TextPopupButtonTouched( Toolkit::TextSelectionPopup::PASTE );
2821         consumed = true;
2822       }
2823       else if (keyName == KEY_X_NAME)
2824       {
2825         // Ctrl-X to cut the selected text
2826         TextPopupButtonTouched( Toolkit::TextSelectionPopup::CUT );
2827         consumed = true;
2828       }
2829       return consumed;
2830     }
2831     else if( ( Dali::DALI_KEY_BACKSPACE == keyCode ) ||
2832              ( Dali::DevelKey::DALI_KEY_DELETE == keyCode ) )
2833     {
2834       textChanged = DeleteEvent( keyCode );
2835
2836       // Will request for relayout.
2837       relayoutNeeded = true;
2838     }
2839     else if( IsKey( keyEvent, Dali::DALI_KEY_POWER ) ||
2840              IsKey( keyEvent, Dali::DALI_KEY_MENU ) ||
2841              IsKey( keyEvent, Dali::DALI_KEY_HOME ) )
2842     {
2843       // Power key/Menu/Home key behaviour does not allow edit mode to resume.
2844       mImpl->ChangeState( EventData::INACTIVE );
2845
2846       // Will request for relayout.
2847       relayoutNeeded = true;
2848
2849       // This branch avoids calling the InsertText() method of the 'else' branch which can delete selected text.
2850     }
2851     else if( ( Dali::DALI_KEY_SHIFT_LEFT == keyCode ) || ( Dali::DALI_KEY_SHIFT_RIGHT == keyCode ) )
2852     {
2853       // 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
2854       // and a character is typed after the type of a upper case latin character.
2855
2856       // Do nothing.
2857       return false;
2858     }
2859     else if( ( Dali::DALI_KEY_VOLUME_UP == keyCode ) || ( Dali::DALI_KEY_VOLUME_DOWN == keyCode ) )
2860     {
2861       // This branch avoids calling the InsertText() method of the 'else' branch which can delete selected text.
2862       // Do nothing.
2863       return false;
2864     }
2865     else
2866     {
2867       DALI_LOG_INFO( gLogFilter, Debug::Verbose, "Controller::KeyEvent %p keyString %s\n", this, keyString.c_str() );
2868
2869       if( !keyString.empty() )
2870       {
2871         // InputMethodContext is no longer handling key-events
2872         mImpl->ClearPreEditFlag();
2873
2874         InsertText( keyString, COMMIT );
2875
2876         textChanged = true;
2877
2878         // Will request for relayout.
2879         relayoutNeeded = true;
2880       }
2881
2882     }
2883
2884     if ( ( mImpl->mEventData->mState != EventData::INTERRUPTED ) &&
2885          ( mImpl->mEventData->mState != EventData::INACTIVE ) &&
2886          ( !isNullKey ) &&
2887          ( Dali::DALI_KEY_SHIFT_LEFT != keyCode ) &&
2888          ( Dali::DALI_KEY_SHIFT_RIGHT != keyCode ) &&
2889          ( Dali::DALI_KEY_VOLUME_UP != keyCode ) &&
2890          ( Dali::DALI_KEY_VOLUME_DOWN != keyCode ) )
2891     {
2892       // Should not change the state if the key is the shift send by the InputMethodContext.
2893       // Otherwise, when the state is SELECTING the text controller can't send the right
2894       // surrounding info to the InputMethodContext.
2895       mImpl->ChangeState( EventData::EDITING );
2896
2897       // Will request for relayout.
2898       relayoutNeeded = true;
2899     }
2900
2901     if( relayoutNeeded )
2902     {
2903       mImpl->RequestRelayout();
2904     }
2905   }
2906
2907   if( textChanged &&
2908       ( NULL != mImpl->mEditableControlInterface ) )
2909   {
2910     // Do this last since it provides callbacks into application code
2911     mImpl->mEditableControlInterface->TextChanged();
2912   }
2913
2914   return true;
2915 }
2916
2917 void Controller::TapEvent( unsigned int tapCount, float x, float y )
2918 {
2919   DALI_ASSERT_DEBUG( mImpl->mEventData && "Unexpected TapEvent" );
2920
2921   if( NULL != mImpl->mEventData )
2922   {
2923     DALI_LOG_INFO( gLogFilter, Debug::Concise, "TapEvent state:%d \n", mImpl->mEventData->mState );
2924     EventData::State state( mImpl->mEventData->mState );
2925     bool relayoutNeeded( false );   // to avoid unnecessary relayouts when tapping an empty text-field
2926
2927     if( mImpl->IsClipboardVisible() )
2928     {
2929       if( EventData::INACTIVE == state || EventData::EDITING == state)
2930       {
2931         mImpl->ChangeState( EventData::EDITING_WITH_GRAB_HANDLE );
2932       }
2933       relayoutNeeded = true;
2934     }
2935     else if( 1u == tapCount )
2936     {
2937       if( EventData::EDITING_WITH_POPUP == state || EventData::EDITING_WITH_PASTE_POPUP == state )
2938       {
2939         mImpl->ChangeState( EventData::EDITING_WITH_GRAB_HANDLE );  // If Popup shown hide it here so can be shown again if required.
2940       }
2941
2942       if( mImpl->IsShowingRealText() && ( EventData::INACTIVE != state ) )
2943       {
2944         mImpl->ChangeState( EventData::EDITING_WITH_GRAB_HANDLE );
2945         relayoutNeeded = true;
2946       }
2947       else
2948       {
2949         if( mImpl->IsShowingPlaceholderText() && !mImpl->IsFocusedPlaceholderAvailable() )
2950         {
2951           // Hide placeholder text
2952           ResetText();
2953         }
2954
2955         if( EventData::INACTIVE == state )
2956         {
2957           mImpl->ChangeState( EventData::EDITING );
2958         }
2959         else if( !mImpl->IsClipboardEmpty() )
2960         {
2961           mImpl->ChangeState( EventData::EDITING_WITH_POPUP );
2962         }
2963         relayoutNeeded = true;
2964       }
2965     }
2966     else if( 2u == tapCount )
2967     {
2968       if( mImpl->mEventData->mSelectionEnabled &&
2969           mImpl->IsShowingRealText() )
2970       {
2971         relayoutNeeded = true;
2972         mImpl->mEventData->mIsLeftHandleSelected = true;
2973         mImpl->mEventData->mIsRightHandleSelected = true;
2974       }
2975     }
2976
2977     // Handles & cursors must be repositioned after Relayout() i.e. after the Model has been updated
2978     if( relayoutNeeded )
2979     {
2980       Event event( Event::TAP_EVENT );
2981       event.p1.mUint = tapCount;
2982       event.p2.mFloat = x;
2983       event.p3.mFloat = y;
2984       mImpl->mEventData->mEventQueue.push_back( event );
2985
2986       mImpl->RequestRelayout();
2987     }
2988   }
2989
2990   // Reset keyboard as tap event has occurred.
2991   mImpl->ResetInputMethodContext();
2992 }
2993
2994 void Controller::PanEvent( Gesture::State state, const Vector2& displacement )
2995 {
2996   DALI_ASSERT_DEBUG( mImpl->mEventData && "Unexpected PanEvent" );
2997
2998   if( NULL != mImpl->mEventData )
2999   {
3000     Event event( Event::PAN_EVENT );
3001     event.p1.mInt = state;
3002     event.p2.mFloat = displacement.x;
3003     event.p3.mFloat = displacement.y;
3004     mImpl->mEventData->mEventQueue.push_back( event );
3005
3006     mImpl->RequestRelayout();
3007   }
3008 }
3009
3010 void Controller::LongPressEvent( Gesture::State state, float x, float y  )
3011 {
3012   DALI_ASSERT_DEBUG( mImpl->mEventData && "Unexpected LongPressEvent" );
3013
3014   if( ( state == Gesture::Started ) &&
3015       ( NULL != mImpl->mEventData ) )
3016   {
3017     // The 1st long-press on inactive text-field is treated as tap
3018     if( EventData::INACTIVE == mImpl->mEventData->mState )
3019     {
3020       mImpl->ChangeState( EventData::EDITING );
3021
3022       Event event( Event::TAP_EVENT );
3023       event.p1.mUint = 1;
3024       event.p2.mFloat = x;
3025       event.p3.mFloat = y;
3026       mImpl->mEventData->mEventQueue.push_back( event );
3027
3028       mImpl->RequestRelayout();
3029     }
3030     else if( !mImpl->IsShowingRealText() )
3031     {
3032       Event event( Event::LONG_PRESS_EVENT );
3033       event.p1.mInt = state;
3034       event.p2.mFloat = x;
3035       event.p3.mFloat = y;
3036       mImpl->mEventData->mEventQueue.push_back( event );
3037       mImpl->RequestRelayout();
3038     }
3039     else if( !mImpl->IsClipboardVisible() )
3040     {
3041       // Reset the InputMethodContext to commit the pre-edit before selecting the text.
3042       mImpl->ResetInputMethodContext();
3043
3044       Event event( Event::LONG_PRESS_EVENT );
3045       event.p1.mInt = state;
3046       event.p2.mFloat = x;
3047       event.p3.mFloat = y;
3048       mImpl->mEventData->mEventQueue.push_back( event );
3049       mImpl->RequestRelayout();
3050
3051       mImpl->mEventData->mIsLeftHandleSelected = true;
3052       mImpl->mEventData->mIsRightHandleSelected = true;
3053     }
3054   }
3055 }
3056
3057 void Controller::SelectEvent( float x, float y, bool selectAll )
3058 {
3059   DALI_LOG_INFO( gLogFilter, Debug::Verbose, "Controller::SelectEvent\n" );
3060
3061   if( NULL != mImpl->mEventData )
3062   {
3063     if( selectAll )
3064     {
3065       Event event( Event::SELECT_ALL );
3066       mImpl->mEventData->mEventQueue.push_back( event );
3067     }
3068     else
3069     {
3070       Event event( Event::SELECT );
3071       event.p2.mFloat = x;
3072       event.p3.mFloat = y;
3073       mImpl->mEventData->mEventQueue.push_back( event );
3074     }
3075
3076     mImpl->mEventData->mCheckScrollAmount = true;
3077     mImpl->mEventData->mIsLeftHandleSelected = true;
3078     mImpl->mEventData->mIsRightHandleSelected = true;
3079     mImpl->RequestRelayout();
3080   }
3081 }
3082
3083 InputMethodContext::CallbackData Controller::OnInputMethodContextEvent( InputMethodContext& inputMethodContext, const InputMethodContext::EventData& inputMethodContextEvent )
3084 {
3085   // Whether the text needs to be relaid-out.
3086   bool requestRelayout = false;
3087
3088   // Whether to retrieve the text and cursor position to be sent to the InputMethodContext.
3089   bool retrieveText = false;
3090   bool retrieveCursor = false;
3091
3092   switch( inputMethodContextEvent.eventName )
3093   {
3094     case InputMethodContext::COMMIT:
3095     {
3096       InsertText( inputMethodContextEvent.predictiveString, Text::Controller::COMMIT );
3097       requestRelayout = true;
3098       retrieveCursor = true;
3099       break;
3100     }
3101     case InputMethodContext::PRE_EDIT:
3102     {
3103       InsertText( inputMethodContextEvent.predictiveString, Text::Controller::PRE_EDIT );
3104       requestRelayout = true;
3105       retrieveCursor = true;
3106       break;
3107     }
3108     case InputMethodContext::DELETE_SURROUNDING:
3109     {
3110       const bool textDeleted = RemoveText( inputMethodContextEvent.cursorOffset,
3111                                            inputMethodContextEvent.numberOfChars,
3112                                            DONT_UPDATE_INPUT_STYLE );
3113
3114       if( textDeleted )
3115       {
3116         if( ( 0u != mImpl->mModel->mLogicalModel->mText.Count() ) ||
3117             !mImpl->IsPlaceholderAvailable() )
3118         {
3119           mImpl->QueueModifyEvent( ModifyEvent::TEXT_DELETED );
3120         }
3121         else
3122         {
3123           ShowPlaceholderText();
3124         }
3125         mImpl->mEventData->mUpdateCursorPosition = true;
3126         mImpl->mEventData->mScrollAfterDelete = true;
3127
3128         requestRelayout = true;
3129       }
3130       break;
3131     }
3132     case InputMethodContext::GET_SURROUNDING:
3133     {
3134       retrieveText = true;
3135       retrieveCursor = true;
3136       break;
3137     }
3138     case InputMethodContext::PRIVATE_COMMAND:
3139     {
3140       // PRIVATECOMMAND event is just for getting the private command message
3141       retrieveText = true;
3142       retrieveCursor = true;
3143       break;
3144     }
3145     case InputMethodContext::VOID:
3146     {
3147       // do nothing
3148       break;
3149     }
3150   } // end switch
3151
3152   if( requestRelayout )
3153   {
3154     mImpl->mOperationsPending = ALL_OPERATIONS;
3155     mImpl->RequestRelayout();
3156   }
3157
3158   std::string text;
3159   CharacterIndex cursorPosition = 0u;
3160   Length numberOfWhiteSpaces = 0u;
3161
3162   if( retrieveCursor )
3163   {
3164     numberOfWhiteSpaces = mImpl->GetNumberOfWhiteSpaces( 0u );
3165
3166     cursorPosition = mImpl->GetLogicalCursorPosition();
3167
3168     if( cursorPosition < numberOfWhiteSpaces )
3169     {
3170       cursorPosition = 0u;
3171     }
3172     else
3173     {
3174       cursorPosition -= numberOfWhiteSpaces;
3175     }
3176   }
3177
3178   if( retrieveText )
3179   {
3180     if( !mImpl->IsShowingPlaceholderText() )
3181     {
3182       // Retrieves the normal text string.
3183       mImpl->GetText( numberOfWhiteSpaces, text );
3184     }
3185     else
3186     {
3187       // When the current text is Placeholder Text, the surrounding text should be empty string.
3188       // It means DALi should send empty string ("") to IME.
3189       text = "";
3190     }
3191   }
3192
3193   InputMethodContext::CallbackData callbackData( ( retrieveText || retrieveCursor ), cursorPosition, text, false );
3194
3195   if( requestRelayout &&
3196       ( NULL != mImpl->mEditableControlInterface ) )
3197   {
3198     // Do this last since it provides callbacks into application code
3199     mImpl->mEditableControlInterface->TextChanged();
3200   }
3201
3202   return callbackData;
3203 }
3204
3205 void Controller::PasteClipboardItemEvent()
3206 {
3207   // Retrieve the clipboard contents first
3208   ClipboardEventNotifier notifier( ClipboardEventNotifier::Get() );
3209   std::string stringToPaste( notifier.GetContent() );
3210
3211   // Commit the current pre-edit text; the contents of the clipboard should be appended
3212   mImpl->ResetInputMethodContext();
3213
3214   // Temporary disable hiding clipboard
3215   mImpl->SetClipboardHideEnable( false );
3216
3217   // Paste
3218   PasteText( stringToPaste );
3219
3220   mImpl->SetClipboardHideEnable( true );
3221 }
3222
3223 // protected : Inherit from Text::Decorator::ControllerInterface.
3224
3225 void Controller::GetTargetSize( Vector2& targetSize )
3226 {
3227   targetSize = mImpl->mModel->mVisualModel->mControlSize;
3228 }
3229
3230 void Controller::AddDecoration( Actor& actor, bool needsClipping )
3231 {
3232   if( NULL != mImpl->mEditableControlInterface )
3233   {
3234     mImpl->mEditableControlInterface->AddDecoration( actor, needsClipping );
3235   }
3236 }
3237
3238 void Controller::DecorationEvent( HandleType handleType, HandleState state, float x, float y )
3239 {
3240   DALI_ASSERT_DEBUG( mImpl->mEventData && "Unexpected DecorationEvent" );
3241
3242   if( NULL != mImpl->mEventData )
3243   {
3244     switch( handleType )
3245     {
3246       case GRAB_HANDLE:
3247       {
3248         Event event( Event::GRAB_HANDLE_EVENT );
3249         event.p1.mUint  = state;
3250         event.p2.mFloat = x;
3251         event.p3.mFloat = y;
3252
3253         mImpl->mEventData->mEventQueue.push_back( event );
3254         break;
3255       }
3256       case LEFT_SELECTION_HANDLE:
3257       {
3258         Event event( Event::LEFT_SELECTION_HANDLE_EVENT );
3259         event.p1.mUint  = state;
3260         event.p2.mFloat = x;
3261         event.p3.mFloat = y;
3262
3263         mImpl->mEventData->mEventQueue.push_back( event );
3264         break;
3265       }
3266       case RIGHT_SELECTION_HANDLE:
3267       {
3268         Event event( Event::RIGHT_SELECTION_HANDLE_EVENT );
3269         event.p1.mUint  = state;
3270         event.p2.mFloat = x;
3271         event.p3.mFloat = y;
3272
3273         mImpl->mEventData->mEventQueue.push_back( event );
3274         break;
3275       }
3276       case LEFT_SELECTION_HANDLE_MARKER:
3277       case RIGHT_SELECTION_HANDLE_MARKER:
3278       {
3279         // Markers do not move the handles.
3280         break;
3281       }
3282       case HANDLE_TYPE_COUNT:
3283       {
3284         DALI_ASSERT_DEBUG( !"Controller::HandleEvent. Unexpected handle type" );
3285       }
3286     }
3287
3288     mImpl->RequestRelayout();
3289   }
3290 }
3291
3292 // protected : Inherit from TextSelectionPopup::TextPopupButtonCallbackInterface.
3293
3294 void Controller::TextPopupButtonTouched( Dali::Toolkit::TextSelectionPopup::Buttons button )
3295 {
3296   if( NULL == mImpl->mEventData )
3297   {
3298     return;
3299   }
3300
3301   switch( button )
3302   {
3303     case Toolkit::TextSelectionPopup::CUT:
3304     {
3305       mImpl->SendSelectionToClipboard( true ); // Synchronous call to modify text
3306       mImpl->mOperationsPending = ALL_OPERATIONS;
3307
3308       if( ( 0u != mImpl->mModel->mLogicalModel->mText.Count() ) ||
3309           !mImpl->IsPlaceholderAvailable() )
3310       {
3311         mImpl->QueueModifyEvent( ModifyEvent::TEXT_DELETED );
3312       }
3313       else
3314       {
3315         ShowPlaceholderText();
3316       }
3317
3318       mImpl->mEventData->mUpdateCursorPosition = true;
3319       mImpl->mEventData->mScrollAfterDelete = true;
3320
3321       mImpl->RequestRelayout();
3322
3323       if( NULL != mImpl->mEditableControlInterface )
3324       {
3325         mImpl->mEditableControlInterface->TextChanged();
3326       }
3327       break;
3328     }
3329     case Toolkit::TextSelectionPopup::COPY:
3330     {
3331       mImpl->SendSelectionToClipboard( false ); // Text not modified
3332
3333       mImpl->mEventData->mUpdateCursorPosition = true;
3334
3335       mImpl->RequestRelayout(); // Cursor, Handles, Selection Highlight, Popup
3336       break;
3337     }
3338     case Toolkit::TextSelectionPopup::PASTE:
3339     {
3340       mImpl->RequestGetTextFromClipboard(); // Request clipboard service to retrieve an item
3341       break;
3342     }
3343     case Toolkit::TextSelectionPopup::SELECT:
3344     {
3345       const Vector2& currentCursorPosition = mImpl->mEventData->mDecorator->GetPosition( PRIMARY_CURSOR );
3346
3347       if( mImpl->mEventData->mSelectionEnabled )
3348       {
3349         // Creates a SELECT event.
3350         SelectEvent( currentCursorPosition.x, currentCursorPosition.y, false );
3351       }
3352       break;
3353     }
3354     case Toolkit::TextSelectionPopup::SELECT_ALL:
3355     {
3356       // Creates a SELECT_ALL event
3357       SelectEvent( 0.f, 0.f, true );
3358       break;
3359     }
3360     case Toolkit::TextSelectionPopup::CLIPBOARD:
3361     {
3362       mImpl->ShowClipboard();
3363       break;
3364     }
3365     case Toolkit::TextSelectionPopup::NONE:
3366     {
3367       // Nothing to do.
3368       break;
3369     }
3370   }
3371 }
3372
3373 void Controller::DisplayTimeExpired()
3374 {
3375   mImpl->mEventData->mUpdateCursorPosition = true;
3376   // Apply modifications to the model
3377   mImpl->mOperationsPending = ALL_OPERATIONS;
3378
3379   mImpl->RequestRelayout();
3380 }
3381
3382 // private : Update.
3383
3384 void Controller::InsertText( const std::string& text, Controller::InsertType type )
3385 {
3386   bool removedPrevious = false;
3387   bool removedSelected = false;
3388   bool maxLengthReached = false;
3389
3390   DALI_ASSERT_DEBUG( NULL != mImpl->mEventData && "Unexpected InsertText" )
3391
3392   if( NULL == mImpl->mEventData )
3393   {
3394     return;
3395   }
3396
3397   DALI_LOG_INFO( gLogFilter, Debug::Verbose, "Controller::InsertText %p %s (%s) mPrimaryCursorPosition %d mPreEditFlag %d mPreEditStartPosition %d mPreEditLength %d\n",
3398                  this, text.c_str(), (COMMIT == type ? "COMMIT" : "PRE_EDIT"),
3399                  mImpl->mEventData->mPrimaryCursorPosition, mImpl->mEventData->mPreEditFlag, mImpl->mEventData->mPreEditStartPosition, mImpl->mEventData->mPreEditLength );
3400
3401   // TODO: At the moment the underline runs are only for pre-edit.
3402   mImpl->mModel->mVisualModel->mUnderlineRuns.Clear();
3403
3404   // Remove the previous InputMethodContext pre-edit.
3405   if( mImpl->mEventData->mPreEditFlag && ( 0u != mImpl->mEventData->mPreEditLength ) )
3406   {
3407     removedPrevious = RemoveText( -static_cast<int>( mImpl->mEventData->mPrimaryCursorPosition - mImpl->mEventData->mPreEditStartPosition ),
3408                                   mImpl->mEventData->mPreEditLength,
3409                                   DONT_UPDATE_INPUT_STYLE );
3410
3411     mImpl->mEventData->mPrimaryCursorPosition = mImpl->mEventData->mPreEditStartPosition;
3412     mImpl->mEventData->mPreEditLength = 0u;
3413   }
3414   else
3415   {
3416     // Remove the previous Selection.
3417     removedSelected = RemoveSelectedText();
3418
3419   }
3420
3421   Vector<Character> utf32Characters;
3422   Length characterCount = 0u;
3423
3424   if( !text.empty() )
3425   {
3426     //  Convert text into UTF-32
3427     utf32Characters.Resize( text.size() );
3428
3429     // This is a bit horrible but std::string returns a (signed) char*
3430     const uint8_t* utf8 = reinterpret_cast<const uint8_t*>( text.c_str() );
3431
3432     // Transform a text array encoded in utf8 into an array encoded in utf32.
3433     // It returns the actual number of characters.
3434     characterCount = Utf8ToUtf32( utf8, text.size(), utf32Characters.Begin() );
3435     utf32Characters.Resize( characterCount );
3436
3437     DALI_ASSERT_DEBUG( text.size() >= utf32Characters.Count() && "Invalid UTF32 conversion length" );
3438     DALI_LOG_INFO( gLogFilter, Debug::Verbose, "UTF8 size %d, UTF32 size %d\n", text.size(), utf32Characters.Count() );
3439   }
3440
3441   if( 0u != utf32Characters.Count() ) // Check if Utf8ToUtf32 conversion succeeded
3442   {
3443     // The placeholder text is no longer needed
3444     if( mImpl->IsShowingPlaceholderText() )
3445     {
3446       ResetText();
3447     }
3448
3449     mImpl->ChangeState( EventData::EDITING );
3450
3451     // Handle the InputMethodContext (predicitive text) state changes
3452     if( COMMIT == type )
3453     {
3454       // InputMethodContext is no longer handling key-events
3455       mImpl->ClearPreEditFlag();
3456     }
3457     else // PRE_EDIT
3458     {
3459       if( !mImpl->mEventData->mPreEditFlag )
3460       {
3461         DALI_LOG_INFO( gLogFilter, Debug::Verbose, "Entered PreEdit state\n" );
3462
3463         // Record the start of the pre-edit text
3464         mImpl->mEventData->mPreEditStartPosition = mImpl->mEventData->mPrimaryCursorPosition;
3465       }
3466
3467       mImpl->mEventData->mPreEditLength = utf32Characters.Count();
3468       mImpl->mEventData->mPreEditFlag = true;
3469
3470       DALI_LOG_INFO( gLogFilter, Debug::Verbose, "mPreEditStartPosition %d mPreEditLength %d\n", mImpl->mEventData->mPreEditStartPosition, mImpl->mEventData->mPreEditLength );
3471     }
3472
3473     const Length numberOfCharactersInModel = mImpl->mModel->mLogicalModel->mText.Count();
3474
3475     // Restrict new text to fit within Maximum characters setting.
3476     Length maxSizeOfNewText = std::min( ( mImpl->mMaximumNumberOfCharacters - numberOfCharactersInModel ), characterCount );
3477     maxLengthReached = ( characterCount > maxSizeOfNewText );
3478
3479     // The cursor position.
3480     CharacterIndex& cursorIndex = mImpl->mEventData->mPrimaryCursorPosition;
3481
3482     // Update the text's style.
3483
3484     // Updates the text style runs by adding characters.
3485     mImpl->mModel->mLogicalModel->UpdateTextStyleRuns( cursorIndex, maxSizeOfNewText );
3486
3487     // Get the character index from the cursor index.
3488     const CharacterIndex styleIndex = ( cursorIndex > 0u ) ? cursorIndex - 1u : 0u;
3489
3490     // Retrieve the text's style for the given index.
3491     InputStyle style;
3492     mImpl->RetrieveDefaultInputStyle( style );
3493     mImpl->mModel->mLogicalModel->RetrieveStyle( styleIndex, style );
3494
3495     // Whether to add a new text color run.
3496     const bool addColorRun = ( style.textColor != mImpl->mEventData->mInputStyle.textColor ) && !mImpl->mEventData->mInputStyle.isDefaultColor;
3497
3498     // Whether to add a new font run.
3499     const bool addFontNameRun = ( style.familyName != mImpl->mEventData->mInputStyle.familyName ) && mImpl->mEventData->mInputStyle.isFamilyDefined;
3500     const bool addFontWeightRun = ( style.weight != mImpl->mEventData->mInputStyle.weight ) && mImpl->mEventData->mInputStyle.isWeightDefined;
3501     const bool addFontWidthRun = ( style.width != mImpl->mEventData->mInputStyle.width ) && mImpl->mEventData->mInputStyle.isWidthDefined;
3502     const bool addFontSlantRun = ( style.slant != mImpl->mEventData->mInputStyle.slant ) && mImpl->mEventData->mInputStyle.isSlantDefined;
3503     const bool addFontSizeRun = ( style.size != mImpl->mEventData->mInputStyle.size ) && mImpl->mEventData->mInputStyle.isSizeDefined ;
3504
3505     // Add style runs.
3506     if( addColorRun )
3507     {
3508       const VectorBase::SizeType numberOfRuns = mImpl->mModel->mLogicalModel->mColorRuns.Count();
3509       mImpl->mModel->mLogicalModel->mColorRuns.Resize( numberOfRuns + 1u );
3510
3511       ColorRun& colorRun = *( mImpl->mModel->mLogicalModel->mColorRuns.Begin() + numberOfRuns );
3512       colorRun.color = mImpl->mEventData->mInputStyle.textColor;
3513       colorRun.characterRun.characterIndex = cursorIndex;
3514       colorRun.characterRun.numberOfCharacters = maxSizeOfNewText;
3515     }
3516
3517     if( addFontNameRun   ||
3518         addFontWeightRun ||
3519         addFontWidthRun  ||
3520         addFontSlantRun  ||
3521         addFontSizeRun )
3522     {
3523       const VectorBase::SizeType numberOfRuns = mImpl->mModel->mLogicalModel->mFontDescriptionRuns.Count();
3524       mImpl->mModel->mLogicalModel->mFontDescriptionRuns.Resize( numberOfRuns + 1u );
3525
3526       FontDescriptionRun& fontDescriptionRun = *( mImpl->mModel->mLogicalModel->mFontDescriptionRuns.Begin() + numberOfRuns );
3527
3528       if( addFontNameRun )
3529       {
3530         fontDescriptionRun.familyLength = mImpl->mEventData->mInputStyle.familyName.size();
3531         fontDescriptionRun.familyName = new char[fontDescriptionRun.familyLength];
3532         memcpy( fontDescriptionRun.familyName, mImpl->mEventData->mInputStyle.familyName.c_str(), fontDescriptionRun.familyLength );
3533         fontDescriptionRun.familyDefined = true;
3534
3535         // The memory allocated for the font family name is freed when the font description is removed from the logical model.
3536       }
3537
3538       if( addFontWeightRun )
3539       {
3540         fontDescriptionRun.weight = mImpl->mEventData->mInputStyle.weight;
3541         fontDescriptionRun.weightDefined = true;
3542       }
3543
3544       if( addFontWidthRun )
3545       {
3546         fontDescriptionRun.width = mImpl->mEventData->mInputStyle.width;
3547         fontDescriptionRun.widthDefined = true;
3548       }
3549
3550       if( addFontSlantRun )
3551       {
3552         fontDescriptionRun.slant = mImpl->mEventData->mInputStyle.slant;
3553         fontDescriptionRun.slantDefined = true;
3554       }
3555
3556       if( addFontSizeRun )
3557       {
3558         fontDescriptionRun.size = static_cast<PointSize26Dot6>( mImpl->mEventData->mInputStyle.size * 64.f );
3559         fontDescriptionRun.sizeDefined = true;
3560       }
3561
3562       fontDescriptionRun.characterRun.characterIndex = cursorIndex;
3563       fontDescriptionRun.characterRun.numberOfCharacters = maxSizeOfNewText;
3564     }
3565
3566     // Insert at current cursor position.
3567     Vector<Character>& modifyText = mImpl->mModel->mLogicalModel->mText;
3568
3569     if( cursorIndex < numberOfCharactersInModel )
3570     {
3571       modifyText.Insert( modifyText.Begin() + cursorIndex, utf32Characters.Begin(), utf32Characters.Begin() + maxSizeOfNewText );
3572     }
3573     else
3574     {
3575       modifyText.Insert( modifyText.End(), utf32Characters.Begin(), utf32Characters.Begin() + maxSizeOfNewText );
3576     }
3577
3578     // Mark the first paragraph to be updated.
3579     if( Layout::Engine::SINGLE_LINE_BOX == mImpl->mLayoutEngine.GetLayout() )
3580     {
3581       mImpl->mTextUpdateInfo.mCharacterIndex = 0;
3582       mImpl->mTextUpdateInfo.mNumberOfCharactersToRemove = mImpl->mTextUpdateInfo.mPreviousNumberOfCharacters;
3583       mImpl->mTextUpdateInfo.mNumberOfCharactersToAdd = numberOfCharactersInModel + maxSizeOfNewText;
3584       mImpl->mTextUpdateInfo.mClearAll = true;
3585     }
3586     else
3587     {
3588       mImpl->mTextUpdateInfo.mCharacterIndex = std::min( cursorIndex, mImpl->mTextUpdateInfo.mCharacterIndex );
3589       mImpl->mTextUpdateInfo.mNumberOfCharactersToAdd += maxSizeOfNewText;
3590     }
3591
3592     // Update the cursor index.
3593     cursorIndex += maxSizeOfNewText;
3594
3595     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 );
3596   }
3597
3598   if( ( 0u == mImpl->mModel->mLogicalModel->mText.Count() ) &&
3599       mImpl->IsPlaceholderAvailable() )
3600   {
3601     // Show place-holder if empty after removing the pre-edit text
3602     ShowPlaceholderText();
3603     mImpl->mEventData->mUpdateCursorPosition = true;
3604     mImpl->ClearPreEditFlag();
3605   }
3606   else if( removedPrevious ||
3607            removedSelected ||
3608            ( 0 != utf32Characters.Count() ) )
3609   {
3610     // Queue an inserted event
3611     mImpl->QueueModifyEvent( ModifyEvent::TEXT_INSERTED );
3612
3613     mImpl->mEventData->mUpdateCursorPosition = true;
3614     if( removedSelected )
3615     {
3616       mImpl->mEventData->mScrollAfterDelete = true;
3617     }
3618     else
3619     {
3620       mImpl->mEventData->mScrollAfterUpdatePosition = true;
3621     }
3622   }
3623
3624   if( maxLengthReached )
3625   {
3626     DALI_LOG_INFO( gLogFilter, Debug::Verbose, "MaxLengthReached (%d)\n", mImpl->mModel->mLogicalModel->mText.Count() );
3627
3628     mImpl->ResetInputMethodContext();
3629
3630     if( NULL != mImpl->mEditableControlInterface )
3631     {
3632       // Do this last since it provides callbacks into application code
3633       mImpl->mEditableControlInterface->MaxLengthReached();
3634     }
3635   }
3636 }
3637
3638 void Controller::PasteText( const std::string& stringToPaste )
3639 {
3640   InsertText( stringToPaste, Text::Controller::COMMIT );
3641   mImpl->ChangeState( EventData::EDITING );
3642   mImpl->RequestRelayout();
3643
3644   if( NULL != mImpl->mEditableControlInterface )
3645   {
3646     // Do this last since it provides callbacks into application code
3647     mImpl->mEditableControlInterface->TextChanged();
3648   }
3649 }
3650
3651 bool Controller::RemoveText( int cursorOffset,
3652                              int numberOfCharacters,
3653                              UpdateInputStyleType type )
3654 {
3655   bool removed = false;
3656
3657   if( NULL == mImpl->mEventData )
3658   {
3659     return removed;
3660   }
3661
3662   DALI_LOG_INFO( gLogFilter, Debug::General, "Controller::RemoveText %p mText.Count() %d cursor %d cursorOffset %d numberOfCharacters %d\n",
3663                  this, mImpl->mModel->mLogicalModel->mText.Count(), mImpl->mEventData->mPrimaryCursorPosition, cursorOffset, numberOfCharacters );
3664
3665   if( !mImpl->IsShowingPlaceholderText() )
3666   {
3667     // Delete at current cursor position
3668     Vector<Character>& currentText = mImpl->mModel->mLogicalModel->mText;
3669     CharacterIndex& oldCursorIndex = mImpl->mEventData->mPrimaryCursorPosition;
3670
3671     CharacterIndex cursorIndex = 0;
3672
3673     // Validate the cursor position & number of characters
3674     if( ( static_cast< int >( mImpl->mEventData->mPrimaryCursorPosition ) + cursorOffset ) >= 0 )
3675     {
3676       cursorIndex = mImpl->mEventData->mPrimaryCursorPosition + cursorOffset;
3677     }
3678
3679     if( ( cursorIndex + numberOfCharacters ) > currentText.Count() )
3680     {
3681       numberOfCharacters = currentText.Count() - cursorIndex;
3682     }
3683
3684     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.
3685         ( ( cursorIndex + numberOfCharacters ) <= mImpl->mTextUpdateInfo.mPreviousNumberOfCharacters ) )
3686     {
3687       // Mark the paragraphs to be updated.
3688       if( Layout::Engine::SINGLE_LINE_BOX == mImpl->mLayoutEngine.GetLayout() )
3689       {
3690         mImpl->mTextUpdateInfo.mCharacterIndex = 0;
3691         mImpl->mTextUpdateInfo.mNumberOfCharactersToRemove = mImpl->mTextUpdateInfo.mPreviousNumberOfCharacters;
3692         mImpl->mTextUpdateInfo.mNumberOfCharactersToAdd = mImpl->mTextUpdateInfo.mPreviousNumberOfCharacters - numberOfCharacters;
3693         mImpl->mTextUpdateInfo.mClearAll = true;
3694       }
3695       else
3696       {
3697         mImpl->mTextUpdateInfo.mCharacterIndex = std::min( cursorIndex, mImpl->mTextUpdateInfo.mCharacterIndex );
3698         mImpl->mTextUpdateInfo.mNumberOfCharactersToRemove += numberOfCharacters;
3699       }
3700
3701       // Update the input style and remove the text's style before removing the text.
3702
3703       if( UPDATE_INPUT_STYLE == type )
3704       {
3705         // Keep a copy of the current input style.
3706         InputStyle currentInputStyle;
3707         currentInputStyle.Copy( mImpl->mEventData->mInputStyle );
3708
3709         // Set first the default input style.
3710         mImpl->RetrieveDefaultInputStyle( mImpl->mEventData->mInputStyle );
3711
3712         // Update the input style.
3713         mImpl->mModel->mLogicalModel->RetrieveStyle( cursorIndex, mImpl->mEventData->mInputStyle );
3714
3715         // Compare if the input style has changed.
3716         const bool hasInputStyleChanged = !currentInputStyle.Equal( mImpl->mEventData->mInputStyle );
3717
3718         if( hasInputStyleChanged )
3719         {
3720           const InputStyle::Mask styleChangedMask = currentInputStyle.GetInputStyleChangeMask( mImpl->mEventData->mInputStyle );
3721           // Queue the input style changed signal.
3722           mImpl->mEventData->mInputStyleChangedQueue.PushBack( styleChangedMask );
3723         }
3724       }
3725
3726       // If the number of current text and the number of characters to be deleted are same,
3727       // it means all texts should be removed and all Preedit variables should be initialized.
3728       if( ( currentText.Count() - numberOfCharacters == 0 ) && ( cursorIndex == 0 ) )
3729       {
3730         mImpl->ClearPreEditFlag();
3731       }
3732
3733       // Updates the text style runs by removing characters. Runs with no characters are removed.
3734       mImpl->mModel->mLogicalModel->UpdateTextStyleRuns( cursorIndex, -numberOfCharacters );
3735
3736       // Remove the characters.
3737       Vector<Character>::Iterator first = currentText.Begin() + cursorIndex;
3738       Vector<Character>::Iterator last  = first + numberOfCharacters;
3739
3740       currentText.Erase( first, last );
3741
3742       // Cursor position retreat
3743       oldCursorIndex = cursorIndex;
3744
3745       mImpl->mEventData->mScrollAfterDelete = true;
3746
3747       if( EventData::INACTIVE == mImpl->mEventData->mState )
3748       {
3749         mImpl->ChangeState( EventData::EDITING );
3750       }
3751
3752       DALI_LOG_INFO( gLogFilter, Debug::General, "Controller::RemoveText %p removed %d\n", this, numberOfCharacters );
3753       removed = true;
3754     }
3755   }
3756
3757   return removed;
3758 }
3759
3760 bool Controller::RemoveSelectedText()
3761 {
3762   bool textRemoved( false );
3763
3764   if( EventData::SELECTING == mImpl->mEventData->mState )
3765   {
3766     std::string removedString;
3767     mImpl->RetrieveSelection( removedString, true );
3768
3769     if( !removedString.empty() )
3770     {
3771       textRemoved = true;
3772       mImpl->ChangeState( EventData::EDITING );
3773     }
3774   }
3775
3776   return textRemoved;
3777 }
3778
3779 // private : Relayout.
3780
3781 bool Controller::DoRelayout( const Size& size,
3782                              OperationsMask operationsRequired,
3783                              Size& layoutSize )
3784 {
3785   DALI_LOG_INFO( gLogFilter, Debug::Verbose, "-->Controller::DoRelayout %p size %f,%f\n", this, size.width, size.height );
3786   bool viewUpdated( false );
3787
3788   // Calculate the operations to be done.
3789   const OperationsMask operations = static_cast<OperationsMask>( mImpl->mOperationsPending & operationsRequired );
3790
3791   const CharacterIndex startIndex = mImpl->mTextUpdateInfo.mParagraphCharacterIndex;
3792   const Length requestedNumberOfCharacters = mImpl->mTextUpdateInfo.mRequestedNumberOfCharacters;
3793
3794   // Get the current layout size.
3795   layoutSize = mImpl->mModel->mVisualModel->GetLayoutSize();
3796
3797   if( NO_OPERATION != ( LAYOUT & operations ) )
3798   {
3799     DALI_LOG_INFO( gLogFilter, Debug::Verbose, "-->Controller::DoRelayout LAYOUT & operations\n");
3800
3801     // Some vectors with data needed to layout and reorder may be void
3802     // after the first time the text has been laid out.
3803     // Fill the vectors again.
3804
3805     // Calculate the number of glyphs to layout.
3806     const Vector<GlyphIndex>& charactersToGlyph = mImpl->mModel->mVisualModel->mCharactersToGlyph;
3807     const Vector<Length>& glyphsPerCharacter = mImpl->mModel->mVisualModel->mGlyphsPerCharacter;
3808     const GlyphIndex* const charactersToGlyphBuffer = charactersToGlyph.Begin();
3809     const Length* const glyphsPerCharacterBuffer = glyphsPerCharacter.Begin();
3810
3811     const CharacterIndex lastIndex = startIndex + ( ( requestedNumberOfCharacters > 0u ) ? requestedNumberOfCharacters - 1u : 0u );
3812     const GlyphIndex startGlyphIndex = mImpl->mTextUpdateInfo.mStartGlyphIndex;
3813
3814     // Make sure the index is not out of bound
3815     if ( charactersToGlyph.Count() != glyphsPerCharacter.Count() ||
3816          requestedNumberOfCharacters > charactersToGlyph.Count() ||
3817          ( lastIndex > charactersToGlyph.Count() && charactersToGlyph.Count() > 0u ) )
3818     {
3819       std::string currentText;
3820       GetText( currentText );
3821
3822       DALI_LOG_ERROR( "Controller::DoRelayout: Attempting to access invalid buffer\n" );
3823       DALI_LOG_ERROR( "Current text is: %s\n", currentText.c_str() );
3824       DALI_LOG_ERROR( "startIndex: %u, lastIndex: %u, requestedNumberOfCharacters: %u, charactersToGlyph.Count = %lu, glyphsPerCharacter.Count = %lu\n", startIndex, lastIndex, requestedNumberOfCharacters, charactersToGlyph.Count(), glyphsPerCharacter.Count());
3825
3826       return false;
3827     }
3828
3829     const Length numberOfGlyphs = ( requestedNumberOfCharacters > 0u ) ? *( charactersToGlyphBuffer + lastIndex ) + *( glyphsPerCharacterBuffer + lastIndex ) - startGlyphIndex : 0u;
3830     const Length totalNumberOfGlyphs = mImpl->mModel->mVisualModel->mGlyphs.Count();
3831
3832     if( 0u == totalNumberOfGlyphs )
3833     {
3834       if( NO_OPERATION != ( UPDATE_LAYOUT_SIZE & operations ) )
3835       {
3836         mImpl->mModel->mVisualModel->SetLayoutSize( Size::ZERO );
3837       }
3838
3839       // Nothing else to do if there is no glyphs.
3840       DALI_LOG_INFO( gLogFilter, Debug::Verbose, "<--Controller::DoRelayout no glyphs, view updated true\n" );
3841       return true;
3842     }
3843
3844     // Set the layout parameters.
3845     Layout::Parameters layoutParameters( size,
3846                                          mImpl->mModel);
3847
3848     // Resize the vector of positions to have the same size than the vector of glyphs.
3849     Vector<Vector2>& glyphPositions = mImpl->mModel->mVisualModel->mGlyphPositions;
3850     glyphPositions.Resize( totalNumberOfGlyphs );
3851
3852     // Whether the last character is a new paragraph character.
3853     const Character* const textBuffer = mImpl->mModel->mLogicalModel->mText.Begin();
3854     mImpl->mTextUpdateInfo.mIsLastCharacterNewParagraph =  TextAbstraction::IsNewParagraph( *( textBuffer + ( mImpl->mModel->mLogicalModel->mText.Count() - 1u ) ) );
3855     layoutParameters.isLastNewParagraph = mImpl->mTextUpdateInfo.mIsLastCharacterNewParagraph;
3856
3857     // The initial glyph and the number of glyphs to layout.
3858     layoutParameters.startGlyphIndex = startGlyphIndex;
3859     layoutParameters.numberOfGlyphs = numberOfGlyphs;
3860     layoutParameters.startLineIndex = mImpl->mTextUpdateInfo.mStartLineIndex;
3861     layoutParameters.estimatedNumberOfLines = mImpl->mTextUpdateInfo.mEstimatedNumberOfLines;
3862
3863     // Update the ellipsis
3864     bool elideTextEnabled = mImpl->mModel->mElideEnabled;
3865
3866     if( NULL != mImpl->mEventData )
3867     {
3868       if( mImpl->mEventData->mPlaceholderEllipsisFlag && mImpl->IsShowingPlaceholderText() )
3869       {
3870         elideTextEnabled = mImpl->mEventData->mIsPlaceholderElideEnabled;
3871       }
3872       else if( EventData::INACTIVE != mImpl->mEventData->mState )
3873       {
3874         // Disable ellipsis when editing
3875         elideTextEnabled = false;
3876       }
3877
3878       // Reset the scroll position in inactive state
3879       if( elideTextEnabled && ( mImpl->mEventData->mState == EventData::INACTIVE ) )
3880       {
3881         ResetScrollPosition();
3882       }
3883     }
3884
3885     // Update the visual model.
3886     bool isAutoScrollEnabled = mImpl->mIsAutoScrollEnabled;
3887     Size newLayoutSize;
3888     viewUpdated = mImpl->mLayoutEngine.LayoutText( layoutParameters,
3889                                                    newLayoutSize,
3890                                                    elideTextEnabled,
3891                                                    isAutoScrollEnabled );
3892     mImpl->mIsAutoScrollEnabled = isAutoScrollEnabled;
3893
3894     viewUpdated = viewUpdated || ( newLayoutSize != layoutSize );
3895
3896     if( viewUpdated )
3897     {
3898       layoutSize = newLayoutSize;
3899
3900       if( NO_OPERATION != ( UPDATE_DIRECTION & operations ) )
3901       {
3902         mImpl->mIsTextDirectionRTL = false;
3903       }
3904
3905       if ( ( NO_OPERATION != ( UPDATE_DIRECTION & operations ) ) && !mImpl->mModel->mVisualModel->mLines.Empty() )
3906       {
3907         mImpl->mIsTextDirectionRTL = mImpl->mModel->mVisualModel->mLines[0u].direction;
3908       }
3909
3910       // Sets the layout size.
3911       if( NO_OPERATION != ( UPDATE_LAYOUT_SIZE & operations ) )
3912       {
3913         mImpl->mModel->mVisualModel->SetLayoutSize( layoutSize );
3914       }
3915     } // view updated
3916   }
3917
3918   if( NO_OPERATION != ( ALIGN & operations ) )
3919   {
3920     // The laid-out lines.
3921     Vector<LineRun>& lines = mImpl->mModel->mVisualModel->mLines;
3922
3923     CharacterIndex alignStartIndex = startIndex;
3924     Length alignRequestedNumberOfCharacters = requestedNumberOfCharacters;
3925
3926     // the whole text needs to be full aligned.
3927     // If you do not do a full aligned, only the last line of the multiline input is aligned.
3928     if(  mImpl->mEventData && mImpl->mEventData->mUpdateAlignment )
3929     {
3930       alignStartIndex = 0u;
3931       alignRequestedNumberOfCharacters = mImpl->mModel->mLogicalModel->mText.Count();
3932       mImpl->mEventData->mUpdateAlignment = false;
3933     }
3934
3935     // Need to align with the control's size as the text may contain lines
3936     // starting either with left to right text or right to left.
3937     mImpl->mLayoutEngine.Align( size,
3938                                 alignStartIndex,
3939                                 alignRequestedNumberOfCharacters,
3940                                 mImpl->mModel->mHorizontalAlignment,
3941                                 lines,
3942                                 mImpl->mModel->mAlignmentOffset,
3943                                 mImpl->mLayoutDirection,
3944                                 mImpl->mModel->mMatchSystemLanguageDirection );
3945
3946     viewUpdated = true;
3947   }
3948 #if defined(DEBUG_ENABLED)
3949   std::string currentText;
3950   GetText( currentText );
3951   DALI_LOG_INFO( gLogFilter, Debug::Concise, "Controller::DoRelayout [%p] mImpl->mIsTextDirectionRTL[%s] [%s]\n", this, (mImpl->mIsTextDirectionRTL)?"true":"false",  currentText.c_str() );
3952 #endif
3953   DALI_LOG_INFO( gLogFilter, Debug::Verbose, "<--Controller::DoRelayout, view updated %s\n", ( viewUpdated ? "true" : "false" ) );
3954   return viewUpdated;
3955 }
3956
3957 void Controller::CalculateVerticalOffset( const Size& controlSize )
3958 {
3959   Size layoutSize = mImpl->mModel->mVisualModel->GetLayoutSize();
3960
3961   if( fabsf( layoutSize.height ) < Math::MACHINE_EPSILON_1000 )
3962   {
3963     // Get the line height of the default font.
3964     layoutSize.height = mImpl->GetDefaultFontLineHeight();
3965   }
3966
3967   switch( mImpl->mModel->mVerticalAlignment )
3968   {
3969     case VerticalAlignment::TOP:
3970     {
3971       mImpl->mModel->mScrollPosition.y = 0.f;
3972       break;
3973     }
3974     case VerticalAlignment::CENTER:
3975     {
3976       mImpl->mModel->mScrollPosition.y = floorf( 0.5f * ( controlSize.height - layoutSize.height ) ); // try to avoid pixel alignment.
3977       break;
3978     }
3979     case VerticalAlignment::BOTTOM:
3980     {
3981       mImpl->mModel->mScrollPosition.y = controlSize.height - layoutSize.height;
3982       break;
3983     }
3984   }
3985 }
3986
3987 // private : Events.
3988
3989 void Controller::ProcessModifyEvents()
3990 {
3991   Vector<ModifyEvent>& events = mImpl->mModifyEvents;
3992
3993   if( 0u == events.Count() )
3994   {
3995     // Nothing to do.
3996     return;
3997   }
3998
3999   for( Vector<ModifyEvent>::ConstIterator it = events.Begin(),
4000          endIt = events.End();
4001        it != endIt;
4002        ++it )
4003   {
4004     const ModifyEvent& event = *it;
4005
4006     if( ModifyEvent::TEXT_REPLACED == event.type )
4007     {
4008       // A (single) replace event should come first, otherwise we wasted time processing NOOP events
4009       DALI_ASSERT_DEBUG( it == events.Begin() && "Unexpected TEXT_REPLACED event" );
4010
4011       TextReplacedEvent();
4012     }
4013     else if( ModifyEvent::TEXT_INSERTED == event.type )
4014     {
4015       TextInsertedEvent();
4016     }
4017     else if( ModifyEvent::TEXT_DELETED == event.type )
4018     {
4019       // Placeholder-text cannot be deleted
4020       if( !mImpl->IsShowingPlaceholderText() )
4021       {
4022         TextDeletedEvent();
4023       }
4024     }
4025   }
4026
4027   if( NULL != mImpl->mEventData )
4028   {
4029     // When the text is being modified, delay cursor blinking
4030     mImpl->mEventData->mDecorator->DelayCursorBlink();
4031
4032     // Update selection position after modifying the text
4033     mImpl->mEventData->mLeftSelectionPosition = mImpl->mEventData->mPrimaryCursorPosition;
4034     mImpl->mEventData->mRightSelectionPosition = mImpl->mEventData->mPrimaryCursorPosition;
4035   }
4036
4037   // Discard temporary text
4038   events.Clear();
4039 }
4040
4041 void Controller::TextReplacedEvent()
4042 {
4043   // The natural size needs to be re-calculated.
4044   mImpl->mRecalculateNaturalSize = true;
4045
4046   // The text direction needs to be updated.
4047   mImpl->mUpdateTextDirection = true;
4048
4049   // Apply modifications to the model
4050   mImpl->mOperationsPending = ALL_OPERATIONS;
4051 }
4052
4053 void Controller::TextInsertedEvent()
4054 {
4055   DALI_ASSERT_DEBUG( NULL != mImpl->mEventData && "Unexpected TextInsertedEvent" );
4056
4057   if( NULL == mImpl->mEventData )
4058   {
4059     return;
4060   }
4061
4062   mImpl->mEventData->mCheckScrollAmount = true;
4063
4064   // The natural size needs to be re-calculated.
4065   mImpl->mRecalculateNaturalSize = true;
4066
4067   // The text direction needs to be updated.
4068   mImpl->mUpdateTextDirection = true;
4069
4070   // Apply modifications to the model; TODO - Optimize this
4071   mImpl->mOperationsPending = ALL_OPERATIONS;
4072 }
4073
4074 void Controller::TextDeletedEvent()
4075 {
4076   DALI_ASSERT_DEBUG( NULL != mImpl->mEventData && "Unexpected TextDeletedEvent" );
4077
4078   if( NULL == mImpl->mEventData )
4079   {
4080     return;
4081   }
4082
4083   mImpl->mEventData->mCheckScrollAmount = true;
4084
4085   // The natural size needs to be re-calculated.
4086   mImpl->mRecalculateNaturalSize = true;
4087
4088   // The text direction needs to be updated.
4089   mImpl->mUpdateTextDirection = true;
4090
4091   // Apply modifications to the model; TODO - Optimize this
4092   mImpl->mOperationsPending = ALL_OPERATIONS;
4093 }
4094
4095 bool Controller::DeleteEvent( int keyCode )
4096 {
4097   DALI_LOG_INFO( gLogFilter, Debug::Verbose, "Controller::KeyEvent %p KeyCode : %d \n", this, keyCode );
4098
4099   bool removed = false;
4100
4101   if( NULL == mImpl->mEventData )
4102   {
4103     return removed;
4104   }
4105
4106   // InputMethodContext is no longer handling key-events
4107   mImpl->ClearPreEditFlag();
4108
4109   if( EventData::SELECTING == mImpl->mEventData->mState )
4110   {
4111     removed = RemoveSelectedText();
4112   }
4113   else if( ( mImpl->mEventData->mPrimaryCursorPosition > 0 ) && ( keyCode == Dali::DALI_KEY_BACKSPACE) )
4114   {
4115     // Remove the character before the current cursor position
4116     removed = RemoveText( -1,
4117                           1,
4118                           UPDATE_INPUT_STYLE );
4119   }
4120   else if( keyCode == Dali::DevelKey::DALI_KEY_DELETE )
4121   {
4122     // Remove the character after the current cursor position
4123     removed = RemoveText( 0,
4124                           1,
4125                           UPDATE_INPUT_STYLE );
4126   }
4127
4128   if( removed )
4129   {
4130     if( ( 0u != mImpl->mModel->mLogicalModel->mText.Count() ) ||
4131         !mImpl->IsPlaceholderAvailable() )
4132     {
4133       mImpl->QueueModifyEvent( ModifyEvent::TEXT_DELETED );
4134     }
4135     else
4136     {
4137       ShowPlaceholderText();
4138     }
4139     mImpl->mEventData->mUpdateCursorPosition = true;
4140     mImpl->mEventData->mScrollAfterDelete = true;
4141   }
4142
4143   return removed;
4144 }
4145
4146 // private : Helpers.
4147
4148 void Controller::ResetText()
4149 {
4150   // Reset buffers.
4151   mImpl->mModel->mLogicalModel->mText.Clear();
4152
4153   // Reset the embedded images buffer.
4154   mImpl->mModel->mLogicalModel->ClearEmbeddedImages();
4155
4156   // We have cleared everything including the placeholder-text
4157   mImpl->PlaceholderCleared();
4158
4159   mImpl->mTextUpdateInfo.mCharacterIndex = 0u;
4160   mImpl->mTextUpdateInfo.mNumberOfCharactersToRemove = mImpl->mTextUpdateInfo.mPreviousNumberOfCharacters;
4161   mImpl->mTextUpdateInfo.mNumberOfCharactersToAdd = 0u;
4162
4163   // Clear any previous text.
4164   mImpl->mTextUpdateInfo.mClearAll = true;
4165
4166   // The natural size needs to be re-calculated.
4167   mImpl->mRecalculateNaturalSize = true;
4168
4169   // The text direction needs to be updated.
4170   mImpl->mUpdateTextDirection = true;
4171
4172   // Apply modifications to the model
4173   mImpl->mOperationsPending = ALL_OPERATIONS;
4174 }
4175
4176 void Controller::ShowPlaceholderText()
4177 {
4178   if( mImpl->IsPlaceholderAvailable() )
4179   {
4180     DALI_ASSERT_DEBUG( mImpl->mEventData && "No placeholder text available" );
4181
4182     if( NULL == mImpl->mEventData )
4183     {
4184       return;
4185     }
4186
4187     mImpl->mEventData->mIsShowingPlaceholderText = true;
4188
4189     // Disable handles when showing place-holder text
4190     mImpl->mEventData->mDecorator->SetHandleActive( GRAB_HANDLE, false );
4191     mImpl->mEventData->mDecorator->SetHandleActive( LEFT_SELECTION_HANDLE, false );
4192     mImpl->mEventData->mDecorator->SetHandleActive( RIGHT_SELECTION_HANDLE, false );
4193
4194     const char* text( NULL );
4195     size_t size( 0 );
4196
4197     // TODO - Switch Placeholder text when changing state
4198     if( ( EventData::INACTIVE != mImpl->mEventData->mState ) &&
4199         ( 0u != mImpl->mEventData->mPlaceholderTextActive.c_str() ) )
4200     {
4201       text = mImpl->mEventData->mPlaceholderTextActive.c_str();
4202       size = mImpl->mEventData->mPlaceholderTextActive.size();
4203     }
4204     else
4205     {
4206       text = mImpl->mEventData->mPlaceholderTextInactive.c_str();
4207       size = mImpl->mEventData->mPlaceholderTextInactive.size();
4208     }
4209
4210     mImpl->mTextUpdateInfo.mCharacterIndex = 0u;
4211     mImpl->mTextUpdateInfo.mNumberOfCharactersToRemove = mImpl->mTextUpdateInfo.mPreviousNumberOfCharacters;
4212
4213     // Reset model for showing placeholder.
4214     mImpl->mModel->mLogicalModel->mText.Clear();
4215     mImpl->mModel->mVisualModel->SetTextColor( mImpl->mEventData->mPlaceholderTextColor );
4216
4217     // Convert text into UTF-32
4218     Vector<Character>& utf32Characters = mImpl->mModel->mLogicalModel->mText;
4219     utf32Characters.Resize( size );
4220
4221     // This is a bit horrible but std::string returns a (signed) char*
4222     const uint8_t* utf8 = reinterpret_cast<const uint8_t*>( text );
4223
4224     // Transform a text array encoded in utf8 into an array encoded in utf32.
4225     // It returns the actual number of characters.
4226     const Length characterCount = Utf8ToUtf32( utf8, size, utf32Characters.Begin() );
4227     utf32Characters.Resize( characterCount );
4228
4229     // The characters to be added.
4230     mImpl->mTextUpdateInfo.mNumberOfCharactersToAdd = characterCount;
4231
4232     // Reset the cursor position
4233     mImpl->mEventData->mPrimaryCursorPosition = 0;
4234
4235     // The natural size needs to be re-calculated.
4236     mImpl->mRecalculateNaturalSize = true;
4237
4238     // The text direction needs to be updated.
4239     mImpl->mUpdateTextDirection = true;
4240
4241     // Apply modifications to the model
4242     mImpl->mOperationsPending = ALL_OPERATIONS;
4243
4244     // Update the rest of the model during size negotiation
4245     mImpl->QueueModifyEvent( ModifyEvent::TEXT_REPLACED );
4246   }
4247 }
4248
4249 void Controller::ClearFontData()
4250 {
4251   if( mImpl->mFontDefaults )
4252   {
4253     mImpl->mFontDefaults->mFontId = 0u; // Remove old font ID
4254   }
4255
4256   // Set flags to update the model.
4257   mImpl->mTextUpdateInfo.mCharacterIndex = 0u;
4258   mImpl->mTextUpdateInfo.mNumberOfCharactersToRemove = mImpl->mTextUpdateInfo.mPreviousNumberOfCharacters;
4259   mImpl->mTextUpdateInfo.mNumberOfCharactersToAdd = mImpl->mModel->mLogicalModel->mText.Count();
4260
4261   mImpl->mTextUpdateInfo.mClearAll = true;
4262   mImpl->mTextUpdateInfo.mFullRelayoutNeeded = true;
4263   mImpl->mRecalculateNaturalSize = true;
4264
4265   mImpl->mOperationsPending = static_cast<OperationsMask>( mImpl->mOperationsPending |
4266                                                            VALIDATE_FONTS            |
4267                                                            SHAPE_TEXT                |
4268                                                            BIDI_INFO                 |
4269                                                            GET_GLYPH_METRICS         |
4270                                                            LAYOUT                    |
4271                                                            UPDATE_LAYOUT_SIZE        |
4272                                                            REORDER                   |
4273                                                            ALIGN );
4274 }
4275
4276 void Controller::ClearStyleData()
4277 {
4278   mImpl->mModel->mLogicalModel->mColorRuns.Clear();
4279   mImpl->mModel->mLogicalModel->ClearFontDescriptionRuns();
4280 }
4281
4282 void Controller::ResetCursorPosition( CharacterIndex cursorIndex )
4283 {
4284   // Reset the cursor position
4285   if( NULL != mImpl->mEventData )
4286   {
4287     mImpl->mEventData->mPrimaryCursorPosition = cursorIndex;
4288
4289     // Update the cursor if it's in editing mode.
4290     if( EventData::IsEditingState( mImpl->mEventData->mState )  )
4291     {
4292       mImpl->mEventData->mUpdateCursorPosition = true;
4293     }
4294   }
4295 }
4296
4297 void Controller::ResetScrollPosition()
4298 {
4299   if( NULL != mImpl->mEventData )
4300   {
4301     // Reset the scroll position.
4302     mImpl->mModel->mScrollPosition = Vector2::ZERO;
4303     mImpl->mEventData->mScrollAfterUpdatePosition = true;
4304   }
4305 }
4306
4307 void Controller::SetControlInterface( ControlInterface* controlInterface )
4308 {
4309   mImpl->mControlInterface = controlInterface;
4310 }
4311
4312 bool Controller::ShouldClearFocusOnEscape() const
4313 {
4314   return mImpl->mShouldClearFocusOnEscape;
4315 }
4316
4317 Actor Controller::CreateBackgroundActor()
4318 {
4319   return mImpl->CreateBackgroundActor();
4320 }
4321
4322 // private : Private contructors & copy operator.
4323
4324 Controller::Controller()
4325 : mImpl( NULL )
4326 {
4327   mImpl = new Controller::Impl( NULL, NULL );
4328 }
4329
4330 Controller::Controller( ControlInterface* controlInterface )
4331 {
4332   mImpl = new Controller::Impl( controlInterface, NULL );
4333 }
4334
4335 Controller::Controller( ControlInterface* controlInterface,
4336                         EditableControlInterface* editableControlInterface )
4337 {
4338   mImpl = new Controller::Impl( controlInterface,
4339                                 editableControlInterface );
4340 }
4341
4342 // The copy constructor and operator are left unimplemented.
4343
4344 // protected : Destructor.
4345
4346 Controller::~Controller()
4347 {
4348   delete mImpl;
4349 }
4350
4351 } // namespace Text
4352
4353 } // namespace Toolkit
4354
4355 } // namespace Dali