Vertical scrolling for text-editor.
[platform/core/uifw/dali-toolkit.git] / dali-toolkit / internal / text / text-controller.cpp
1 /*
2  * Copyright (c) 2015 Samsung Electronics Co., Ltd.
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  * http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  *
16  */
17
18 // CLASS HEADER
19 #include <dali-toolkit/internal/text/text-controller.h>
20
21 // EXTERNAL INCLUDES
22 #include <limits>
23 #include <memory.h>
24 #include <dali/public-api/adaptor-framework/key.h>
25 #include <dali/integration-api/debug.h>
26 #include <dali/devel-api/adaptor-framework/clipboard-event-notifier.h>
27
28 // INTERNAL INCLUDES
29 #include <dali-toolkit/internal/text/bidirectional-support.h>
30 #include <dali-toolkit/internal/text/character-set-conversion.h>
31 #include <dali-toolkit/internal/text/layouts/layout-parameters.h>
32 #include <dali-toolkit/internal/text/markup-processor.h>
33 #include <dali-toolkit/internal/text/text-controller-impl.h>
34
35 namespace
36 {
37
38 #if defined(DEBUG_ENABLED)
39   Debug::Filter* gLogFilter = Debug::Filter::New(Debug::NoLogging, true, "LOG_TEXT_CONTROLS");
40 #endif
41
42 const float MAX_FLOAT = std::numeric_limits<float>::max();
43
44 const std::string EMPTY_STRING("");
45
46 float ConvertToEven( float value )
47 {
48   int intValue(static_cast<int>( value ));
49   return static_cast<float>(intValue % 2 == 0) ? intValue : (intValue + 1);
50 }
51
52 } // namespace
53
54 namespace Dali
55 {
56
57 namespace Toolkit
58 {
59
60 namespace Text
61 {
62
63 /**
64  * @brief Adds a new font description run for the selected text.
65  *
66  * The new font parameters are added after the call to this method.
67  *
68  * @param[in] eventData The event data pointer.
69  * @param[in] logicalModel The logical model where to add the new font description run.
70  * @param[out] startOfSelectedText Index to the first selected character.
71  * @param[out] lengthOfSelectedText Number of selected characters.
72  */
73 FontDescriptionRun& UpdateSelectionFontStyleRun( EventData* eventData,
74                                                  LogicalModelPtr logicalModel,
75                                                  CharacterIndex& startOfSelectedText,
76                                                  Length& lengthOfSelectedText )
77 {
78   const bool handlesCrossed = eventData->mLeftSelectionPosition > eventData->mRightSelectionPosition;
79
80   // Get start and end position of selection
81   startOfSelectedText = handlesCrossed ? eventData->mRightSelectionPosition : eventData->mLeftSelectionPosition;
82   lengthOfSelectedText = ( handlesCrossed ? eventData->mLeftSelectionPosition : eventData->mRightSelectionPosition ) - startOfSelectedText;
83
84   // Add the font run.
85   const VectorBase::SizeType numberOfRuns = logicalModel->mFontDescriptionRuns.Count();
86   logicalModel->mFontDescriptionRuns.Resize( numberOfRuns + 1u );
87
88   FontDescriptionRun& fontDescriptionRun = *( logicalModel->mFontDescriptionRuns.Begin() + numberOfRuns );
89
90   fontDescriptionRun.characterRun.characterIndex = startOfSelectedText;
91   fontDescriptionRun.characterRun.numberOfCharacters = lengthOfSelectedText;
92
93   // Recalculate the selection highlight as the metrics may have changed.
94   eventData->mUpdateLeftSelectionPosition = true;
95   eventData->mUpdateRightSelectionPosition = true;
96   eventData->mUpdateHighlightBox = true;
97
98   return fontDescriptionRun;
99 }
100
101 ControllerPtr Controller::New( ControlInterface& controlInterface )
102 {
103   return ControllerPtr( new Controller( controlInterface ) );
104 }
105
106 void Controller::EnableTextInput( DecoratorPtr decorator )
107 {
108   if( NULL == mImpl->mEventData )
109   {
110     mImpl->mEventData = new EventData( decorator );
111   }
112 }
113
114 void Controller::SetGlyphType( TextAbstraction::GlyphType glyphType )
115 {
116   // Metrics for bitmap & vector based glyphs are different
117   mImpl->mMetrics->SetGlyphType( glyphType );
118
119   // Clear the font-specific data
120   ClearFontData();
121
122   mImpl->RequestRelayout();
123 }
124
125 void Controller::SetMarkupProcessorEnabled( bool enable )
126 {
127   mImpl->mMarkupProcessorEnabled = enable;
128 }
129
130 bool Controller::IsMarkupProcessorEnabled() const
131 {
132   return mImpl->mMarkupProcessorEnabled;
133 }
134
135 void Controller::SetAutoScrollEnabled( bool enable )
136 {
137   DALI_LOG_INFO( gLogFilter, Debug::General, "Controller::SetAutoScrollEnabled[%s] SingleBox[%s]-> [%p]\n", (enable)?"true":"false", ( mImpl->mLayoutEngine.GetLayout() == LayoutEngine::SINGLE_LINE_BOX)?"true":"false", this );
138
139   if ( mImpl->mLayoutEngine.GetLayout() == LayoutEngine::SINGLE_LINE_BOX )
140   {
141     if ( enable )
142     {
143       DALI_LOG_INFO( gLogFilter, Debug::General, "Controller::SetAutoScrollEnabled for SINGLE_LINE_BOX\n" );
144       mImpl->mOperationsPending = static_cast<OperationsMask>( mImpl->mOperationsPending |
145                                                                LAYOUT                    |
146                                                                ALIGN                     |
147                                                                UPDATE_ACTUAL_SIZE        |
148                                                                UPDATE_DIRECTION          |
149                                                                REORDER );
150
151     }
152     else
153     {
154       DALI_LOG_INFO( gLogFilter, Debug::General, "Controller::SetAutoScrollEnabled Disabling autoscroll\n");
155       mImpl->mOperationsPending = static_cast<OperationsMask>( mImpl->mOperationsPending |
156                                                                LAYOUT                    |
157                                                                ALIGN                     |
158                                                                UPDATE_ACTUAL_SIZE        |
159                                                                REORDER );
160     }
161
162     mImpl->mAutoScrollEnabled = enable;
163     mImpl->RequestRelayout();
164   }
165   else
166   {
167     DALI_LOG_WARNING( "Attempted AutoScrolling on a non SINGLE_LINE_BOX, request ignored" );
168     mImpl->mAutoScrollEnabled = false;
169   }
170 }
171
172 bool Controller::IsAutoScrollEnabled() const
173 {
174   DALI_LOG_INFO( gLogFilter, Debug::Verbose, "Controller::IsAutoScrollEnabled[%s]\n", (mImpl->mAutoScrollEnabled)?"true":"false" );
175
176   return mImpl->mAutoScrollEnabled;
177 }
178
179 CharacterDirection Controller::GetAutoScrollDirection() const
180 {
181   return mImpl->mAutoScrollDirectionRTL;
182 }
183
184 float Controller::GetAutoScrollLineAlignment() const
185 {
186   float offset = 0.f;
187
188   if( mImpl->mVisualModel &&
189       ( 0u != mImpl->mVisualModel->mLines.Count() ) )
190   {
191     offset = ( *mImpl->mVisualModel->mLines.Begin() ).alignmentOffset;
192   }
193
194   return offset;
195 }
196
197 void Controller::SetHorizontalScrollEnabled( bool enable )
198 {
199   if( ( NULL != mImpl->mEventData ) &&
200       mImpl->mEventData->mDecorator )
201   {
202     mImpl->mEventData->mDecorator->SetHorizontalScrollEnabled( enable );
203   }
204 }
205
206 bool Controller::IsHorizontalScrollEnabled() const
207 {
208   if( ( NULL != mImpl->mEventData ) &&
209       mImpl->mEventData->mDecorator )
210   {
211     return mImpl->mEventData->mDecorator->IsHorizontalScrollEnabled();
212   }
213
214   return false;
215 }
216
217 void Controller::SetVerticalScrollEnabled( bool enable )
218 {
219   if( ( NULL != mImpl->mEventData ) &&
220       mImpl->mEventData->mDecorator )
221   {
222     if( mImpl->mEventData->mDecorator )
223     {
224       mImpl->mEventData->mDecorator->SetVerticalScrollEnabled( enable );
225     }
226   }
227 }
228
229 bool Controller::IsVerticalScrollEnabled() const
230 {
231   if( ( NULL != mImpl->mEventData ) &&
232       mImpl->mEventData->mDecorator )
233   {
234     return mImpl->mEventData->mDecorator->IsVerticalScrollEnabled();
235   }
236
237   return false;
238 }
239
240 void Controller::SetSmoothHandlePanEnabled( bool enable )
241 {
242   if( ( NULL != mImpl->mEventData ) &&
243       mImpl->mEventData->mDecorator )
244   {
245     mImpl->mEventData->mDecorator->SetSmoothHandlePanEnabled( enable );
246   }
247 }
248
249 bool Controller::IsSmoothHandlePanEnabled() const
250 {
251   if( ( NULL != mImpl->mEventData ) &&
252       mImpl->mEventData->mDecorator )
253   {
254     return mImpl->mEventData->mDecorator->IsSmoothHandlePanEnabled();
255   }
256
257   return false;
258 }
259
260 void Controller::SetText( const std::string& text )
261 {
262   DALI_LOG_INFO( gLogFilter, Debug::Verbose, "Controller::SetText\n" );
263
264   // Reset keyboard as text changed
265   mImpl->ResetImfManager();
266
267   // Remove the previously set text and style.
268   ResetText();
269
270   // Remove the style.
271   ClearStyleData();
272
273   CharacterIndex lastCursorIndex = 0u;
274
275   if( NULL != mImpl->mEventData )
276   {
277     // If popup shown then hide it by switching to Editing state
278     if( ( EventData::SELECTING == mImpl->mEventData->mState )          ||
279         ( EventData::EDITING_WITH_POPUP == mImpl->mEventData->mState ) ||
280         ( EventData::EDITING_WITH_GRAB_HANDLE == mImpl->mEventData->mState ) ||
281         ( EventData::EDITING_WITH_PASTE_POPUP == mImpl->mEventData->mState ) )
282     {
283       mImpl->ChangeState( EventData::EDITING );
284     }
285   }
286
287   if( !text.empty() )
288   {
289     mImpl->mVisualModel->SetTextColor( mImpl->mTextColor );
290
291     MarkupProcessData markupProcessData( mImpl->mLogicalModel->mColorRuns,
292                                          mImpl->mLogicalModel->mFontDescriptionRuns );
293
294     Length textSize = 0u;
295     const uint8_t* utf8 = NULL;
296     if( mImpl->mMarkupProcessorEnabled )
297     {
298       ProcessMarkupString( text, markupProcessData );
299       textSize = markupProcessData.markupProcessedText.size();
300
301       // This is a bit horrible but std::string returns a (signed) char*
302       utf8 = reinterpret_cast<const uint8_t*>( markupProcessData.markupProcessedText.c_str() );
303     }
304     else
305     {
306       textSize = text.size();
307
308       // This is a bit horrible but std::string returns a (signed) char*
309       utf8 = reinterpret_cast<const uint8_t*>( text.c_str() );
310     }
311
312     //  Convert text into UTF-32
313     Vector<Character>& utf32Characters = mImpl->mLogicalModel->mText;
314     utf32Characters.Resize( textSize );
315
316     // Transform a text array encoded in utf8 into an array encoded in utf32.
317     // It returns the actual number of characters.
318     Length characterCount = Utf8ToUtf32( utf8, textSize, utf32Characters.Begin() );
319     utf32Characters.Resize( characterCount );
320
321     DALI_ASSERT_DEBUG( textSize >= characterCount && "Invalid UTF32 conversion length" );
322     DALI_LOG_INFO( gLogFilter, Debug::Verbose, "Controller::SetText %p UTF8 size %d, UTF32 size %d\n", this, textSize, mImpl->mLogicalModel->mText.Count() );
323
324     // The characters to be added.
325     mImpl->mTextUpdateInfo.mNumberOfCharactersToAdd = mImpl->mLogicalModel->mText.Count();
326
327     // To reset the cursor position
328     lastCursorIndex = characterCount;
329
330     // Update the rest of the model during size negotiation
331     mImpl->QueueModifyEvent( ModifyEvent::TEXT_REPLACED );
332
333     // The natural size needs to be re-calculated.
334     mImpl->mRecalculateNaturalSize = true;
335
336     // Apply modifications to the model
337     mImpl->mOperationsPending = ALL_OPERATIONS;
338   }
339   else
340   {
341     ShowPlaceholderText();
342   }
343
344   // Resets the cursor position.
345   ResetCursorPosition( lastCursorIndex );
346
347   // Scrolls the text to make the cursor visible.
348   ResetScrollPosition();
349
350   mImpl->RequestRelayout();
351
352   if( NULL != mImpl->mEventData )
353   {
354     // Cancel previously queued events
355     mImpl->mEventData->mEventQueue.clear();
356   }
357
358   // Do this last since it provides callbacks into application code
359   mImpl->mControlInterface.TextChanged();
360 }
361
362 void Controller::GetText( std::string& text ) const
363 {
364   if( !mImpl->IsShowingPlaceholderText() )
365   {
366     // Retrieves the text string.
367     mImpl->GetText( 0u, text );
368   }
369   else
370   {
371     DALI_LOG_INFO( gLogFilter, Debug::Verbose, "Controller::GetText %p empty (but showing placeholder)\n", this );
372   }
373 }
374
375 void Controller::SetPlaceholderText( PlaceholderType type, const std::string& text )
376 {
377   if( NULL != mImpl->mEventData )
378   {
379     if( PLACEHOLDER_TYPE_INACTIVE == type )
380     {
381       mImpl->mEventData->mPlaceholderTextInactive = text;
382     }
383     else
384     {
385       mImpl->mEventData->mPlaceholderTextActive = text;
386     }
387
388     // Update placeholder if there is no text
389     if( mImpl->IsShowingPlaceholderText() ||
390         ( 0u == mImpl->mLogicalModel->mText.Count() ) )
391     {
392       ShowPlaceholderText();
393     }
394   }
395 }
396
397 void Controller::GetPlaceholderText( PlaceholderType type, std::string& text ) const
398 {
399   if( NULL != mImpl->mEventData )
400   {
401     if( PLACEHOLDER_TYPE_INACTIVE == type )
402     {
403       text = mImpl->mEventData->mPlaceholderTextInactive;
404     }
405     else
406     {
407       text = mImpl->mEventData->mPlaceholderTextActive;
408     }
409   }
410 }
411
412 void Controller::SetMaximumNumberOfCharacters( Length maxCharacters )
413 {
414   mImpl->mMaximumNumberOfCharacters = maxCharacters;
415 }
416
417 int Controller::GetMaximumNumberOfCharacters()
418 {
419   return mImpl->mMaximumNumberOfCharacters;
420 }
421
422 void Controller::SetDefaultFontFamily( const std::string& defaultFontFamily )
423 {
424   if( NULL == mImpl->mFontDefaults )
425   {
426     mImpl->mFontDefaults = new FontDefaults();
427   }
428
429   mImpl->mFontDefaults->mFontDescription.family = defaultFontFamily;
430   DALI_LOG_INFO( gLogFilter, Debug::General, "Controller::SetDefaultFontFamily %s\n", defaultFontFamily.c_str());
431   mImpl->mFontDefaults->familyDefined = true;
432
433   // Clear the font-specific data
434   ClearFontData();
435
436   mImpl->RequestRelayout();
437 }
438
439 const std::string& Controller::GetDefaultFontFamily() const
440 {
441   if( NULL != mImpl->mFontDefaults )
442   {
443     return mImpl->mFontDefaults->mFontDescription.family;
444   }
445
446   return EMPTY_STRING;
447 }
448
449 void Controller::SetDefaultFontStyle( const std::string& style )
450 {
451   if( NULL == mImpl->mFontDefaults )
452   {
453     mImpl->mFontDefaults = new FontDefaults();
454   }
455
456   mImpl->mFontDefaults->mFontStyle = style;
457 }
458
459 const std::string& Controller::GetDefaultFontStyle() const
460 {
461   if( NULL != mImpl->mFontDefaults )
462   {
463     return mImpl->mFontDefaults->mFontStyle;
464   }
465
466   return EMPTY_STRING;
467 }
468
469 void Controller::SetDefaultFontWeight( FontWeight weight )
470 {
471   if( NULL == mImpl->mFontDefaults )
472   {
473     mImpl->mFontDefaults = new FontDefaults();
474   }
475
476   mImpl->mFontDefaults->mFontDescription.weight = weight;
477   mImpl->mFontDefaults->weightDefined = true;
478
479   // Clear the font-specific data
480   ClearFontData();
481
482   mImpl->RequestRelayout();
483 }
484
485 FontWeight Controller::GetDefaultFontWeight() const
486 {
487   if( NULL != mImpl->mFontDefaults )
488   {
489     return mImpl->mFontDefaults->mFontDescription.weight;
490   }
491
492   return TextAbstraction::FontWeight::NORMAL;
493 }
494
495 void Controller::SetDefaultFontWidth( FontWidth width )
496 {
497   if( NULL == mImpl->mFontDefaults )
498   {
499     mImpl->mFontDefaults = new FontDefaults();
500   }
501
502   mImpl->mFontDefaults->mFontDescription.width = width;
503   mImpl->mFontDefaults->widthDefined = true;
504
505   // Clear the font-specific data
506   ClearFontData();
507
508   mImpl->RequestRelayout();
509 }
510
511 FontWidth Controller::GetDefaultFontWidth() const
512 {
513   if( NULL != mImpl->mFontDefaults )
514   {
515     return mImpl->mFontDefaults->mFontDescription.width;
516   }
517
518   return TextAbstraction::FontWidth::NORMAL;
519 }
520
521 void Controller::SetDefaultFontSlant( FontSlant slant )
522 {
523   if( NULL == mImpl->mFontDefaults )
524   {
525     mImpl->mFontDefaults = new FontDefaults();
526   }
527
528   mImpl->mFontDefaults->mFontDescription.slant = slant;
529   mImpl->mFontDefaults->slantDefined = true;
530
531   // Clear the font-specific data
532   ClearFontData();
533
534   mImpl->RequestRelayout();
535 }
536
537 FontSlant Controller::GetDefaultFontSlant() const
538 {
539   if( NULL != mImpl->mFontDefaults )
540   {
541     return mImpl->mFontDefaults->mFontDescription.slant;
542   }
543
544   return TextAbstraction::FontSlant::NORMAL;
545 }
546
547 void Controller::SetDefaultPointSize( float pointSize )
548 {
549   if( NULL == mImpl->mFontDefaults )
550   {
551     mImpl->mFontDefaults = new FontDefaults();
552   }
553
554   mImpl->mFontDefaults->mDefaultPointSize = pointSize;
555   mImpl->mFontDefaults->sizeDefined = true;
556
557   // Clear the font-specific data
558   ClearFontData();
559
560   mImpl->RequestRelayout();
561 }
562
563 float Controller::GetDefaultPointSize() const
564 {
565   if( NULL != mImpl->mFontDefaults )
566   {
567     return mImpl->mFontDefaults->mDefaultPointSize;
568   }
569
570   return 0.0f;
571 }
572
573 void Controller::UpdateAfterFontChange( const std::string& newDefaultFont )
574 {
575   DALI_LOG_INFO( gLogFilter, Debug::Verbose, "Controller::UpdateAfterFontChange");
576
577   if( !mImpl->mFontDefaults->familyDefined ) // If user defined font then should not update when system font changes
578   {
579     DALI_LOG_INFO( gLogFilter, Debug::Concise, "Controller::UpdateAfterFontChange newDefaultFont(%s)\n", newDefaultFont.c_str() );
580     mImpl->mFontDefaults->mFontDescription.family = newDefaultFont;
581
582     ClearFontData();
583
584     mImpl->RequestRelayout();
585   }
586 }
587
588 void Controller::SetTextColor( const Vector4& textColor )
589 {
590   mImpl->mTextColor = textColor;
591
592   if( !mImpl->IsShowingPlaceholderText() )
593   {
594     mImpl->mVisualModel->SetTextColor( textColor );
595
596     mImpl->RequestRelayout();
597   }
598 }
599
600 const Vector4& Controller::GetTextColor() const
601 {
602   return mImpl->mTextColor;
603 }
604
605 bool Controller::RemoveText( int cursorOffset,
606                              int numberOfCharacters,
607                              UpdateInputStyleType type )
608 {
609   bool removed = false;
610
611   if( NULL == mImpl->mEventData )
612   {
613     return removed;
614   }
615
616   DALI_LOG_INFO( gLogFilter, Debug::General, "Controller::RemoveText %p mText.Count() %d cursor %d cursorOffset %d numberOfCharacters %d\n",
617                  this, mImpl->mLogicalModel->mText.Count(), mImpl->mEventData->mPrimaryCursorPosition, cursorOffset, numberOfCharacters );
618
619   if( !mImpl->IsShowingPlaceholderText() )
620   {
621     // Delete at current cursor position
622     Vector<Character>& currentText = mImpl->mLogicalModel->mText;
623     CharacterIndex& oldCursorIndex = mImpl->mEventData->mPrimaryCursorPosition;
624
625     CharacterIndex cursorIndex = oldCursorIndex;
626
627     // Validate the cursor position & number of characters
628     if( static_cast< CharacterIndex >( std::abs( cursorOffset ) ) <= cursorIndex )
629     {
630       cursorIndex = oldCursorIndex + cursorOffset;
631     }
632
633     if( ( cursorIndex + numberOfCharacters ) > currentText.Count() )
634     {
635       numberOfCharacters = currentText.Count() - cursorIndex;
636     }
637
638     if( ( cursorIndex + numberOfCharacters ) <= mImpl->mTextUpdateInfo.mPreviousNumberOfCharacters )
639     {
640       // Mark the paragraphs to be updated.
641       mImpl->mTextUpdateInfo.mCharacterIndex = std::min( cursorIndex, mImpl->mTextUpdateInfo.mCharacterIndex );
642       mImpl->mTextUpdateInfo.mNumberOfCharactersToRemove += numberOfCharacters;
643
644       // Update the input style and remove the text's style before removing the text.
645
646       if( UPDATE_INPUT_STYLE == type )
647       {
648         // Set first the default input style.
649         mImpl->RetrieveDefaultInputStyle( mImpl->mEventData->mInputStyle );
650
651         // Update the input style.
652         mImpl->mLogicalModel->RetrieveStyle( cursorIndex, mImpl->mEventData->mInputStyle );
653       }
654
655       // Updates the text style runs by removing characters. Runs with no characters are removed.
656       mImpl->mLogicalModel->UpdateTextStyleRuns( cursorIndex, -numberOfCharacters );
657
658       // Remove the characters.
659       Vector<Character>::Iterator first = currentText.Begin() + cursorIndex;
660       Vector<Character>::Iterator last  = first + numberOfCharacters;
661
662       currentText.Erase( first, last );
663
664       // Cursor position retreat
665       oldCursorIndex = cursorIndex;
666
667       mImpl->mEventData->mScrollAfterDelete = true;
668
669       DALI_LOG_INFO( gLogFilter, Debug::General, "Controller::RemoveText %p removed %d\n", this, numberOfCharacters );
670       removed = true;
671     }
672   }
673
674   return removed;
675 }
676
677 void Controller::SetPlaceholderTextColor( const Vector4& textColor )
678 {
679   if( NULL != mImpl->mEventData )
680   {
681     mImpl->mEventData->mPlaceholderTextColor = textColor;
682   }
683
684   if( mImpl->IsShowingPlaceholderText() )
685   {
686     mImpl->mVisualModel->SetTextColor( textColor );
687     mImpl->RequestRelayout();
688   }
689 }
690
691 const Vector4& Controller::GetPlaceholderTextColor() const
692 {
693   if( NULL != mImpl->mEventData )
694   {
695     return mImpl->mEventData->mPlaceholderTextColor;
696   }
697
698   return Color::BLACK;
699 }
700
701 void Controller::SetShadowOffset( const Vector2& shadowOffset )
702 {
703   mImpl->mVisualModel->SetShadowOffset( shadowOffset );
704
705   mImpl->RequestRelayout();
706 }
707
708 const Vector2& Controller::GetShadowOffset() const
709 {
710   return mImpl->mVisualModel->GetShadowOffset();
711 }
712
713 void Controller::SetShadowColor( const Vector4& shadowColor )
714 {
715   mImpl->mVisualModel->SetShadowColor( shadowColor );
716
717   mImpl->RequestRelayout();
718 }
719
720 const Vector4& Controller::GetShadowColor() const
721 {
722   return mImpl->mVisualModel->GetShadowColor();
723 }
724
725 void Controller::SetDefaultShadowProperties( const std::string& shadowProperties )
726 {
727   if( NULL == mImpl->mShadowDefaults )
728   {
729     mImpl->mShadowDefaults = new ShadowDefaults();
730   }
731
732   mImpl->mShadowDefaults->properties = shadowProperties;
733 }
734
735 const std::string& Controller::GetDefaultShadowProperties() const
736 {
737   if( NULL != mImpl->mShadowDefaults )
738   {
739     return mImpl->mShadowDefaults->properties;
740   }
741
742   return EMPTY_STRING;
743 }
744
745 void Controller::SetUnderlineColor( const Vector4& color )
746 {
747   mImpl->mVisualModel->SetUnderlineColor( color );
748
749   mImpl->RequestRelayout();
750 }
751
752 const Vector4& Controller::GetUnderlineColor() const
753 {
754   return mImpl->mVisualModel->GetUnderlineColor();
755 }
756
757 void Controller::SetUnderlineEnabled( bool enabled )
758 {
759   mImpl->mVisualModel->SetUnderlineEnabled( enabled );
760
761   mImpl->RequestRelayout();
762 }
763
764 bool Controller::IsUnderlineEnabled() const
765 {
766   return mImpl->mVisualModel->IsUnderlineEnabled();
767 }
768
769 void Controller::SetUnderlineHeight( float height )
770 {
771   mImpl->mVisualModel->SetUnderlineHeight( height );
772
773   mImpl->RequestRelayout();
774 }
775
776 float Controller::GetUnderlineHeight() const
777 {
778   return mImpl->mVisualModel->GetUnderlineHeight();
779 }
780
781 void Controller::SetDefaultUnderlineProperties( const std::string& underlineProperties )
782 {
783   if( NULL == mImpl->mUnderlineDefaults )
784   {
785     mImpl->mUnderlineDefaults = new UnderlineDefaults();
786   }
787
788   mImpl->mUnderlineDefaults->properties = underlineProperties;
789 }
790
791 const std::string& Controller::GetDefaultUnderlineProperties() const
792 {
793   if( NULL != mImpl->mUnderlineDefaults )
794   {
795     return mImpl->mUnderlineDefaults->properties;
796   }
797
798   return EMPTY_STRING;
799 }
800
801 void Controller::SetDefaultEmbossProperties( const std::string& embossProperties )
802 {
803   if( NULL == mImpl->mEmbossDefaults )
804   {
805     mImpl->mEmbossDefaults = new EmbossDefaults();
806   }
807
808   mImpl->mEmbossDefaults->properties = embossProperties;
809 }
810
811 const std::string& Controller::GetDefaultEmbossProperties() const
812 {
813   if( NULL != mImpl->mEmbossDefaults )
814   {
815     return mImpl->mEmbossDefaults->properties;
816   }
817
818   return EMPTY_STRING;
819 }
820
821 void Controller::SetDefaultOutlineProperties( const std::string& outlineProperties )
822 {
823   if( NULL == mImpl->mOutlineDefaults )
824   {
825     mImpl->mOutlineDefaults = new OutlineDefaults();
826   }
827
828   mImpl->mOutlineDefaults->properties = outlineProperties;
829 }
830
831 const std::string& Controller::GetDefaultOutlineProperties() const
832 {
833   if( NULL != mImpl->mOutlineDefaults )
834   {
835     return mImpl->mOutlineDefaults->properties;
836   }
837
838   return EMPTY_STRING;
839 }
840
841 void Controller::SetDefaultLineSpacing( float lineSpacing )
842 {
843   //TODO finish implementation
844   mImpl->mLayoutEngine.SetDefaultLineSpacing( lineSpacing );
845 }
846
847 float Controller::GetDefaultLineSpacing() const
848 {
849   return mImpl->mLayoutEngine.GetDefaultLineSpacing();
850 }
851
852 void Controller::SetInputColor( const Vector4& color )
853 {
854   if( NULL != mImpl->mEventData )
855   {
856     mImpl->mEventData->mInputStyle.textColor = color;
857     mImpl->mEventData->mInputStyle.isDefaultColor = false;
858
859     if( EventData::SELECTING == mImpl->mEventData->mState )
860     {
861       const bool handlesCrossed = mImpl->mEventData->mLeftSelectionPosition > mImpl->mEventData->mRightSelectionPosition;
862
863       // Get start and end position of selection
864       const CharacterIndex startOfSelectedText = handlesCrossed ? mImpl->mEventData->mRightSelectionPosition : mImpl->mEventData->mLeftSelectionPosition;
865       const Length lengthOfSelectedText = ( handlesCrossed ? mImpl->mEventData->mLeftSelectionPosition : mImpl->mEventData->mRightSelectionPosition ) - startOfSelectedText;
866
867       // Add the color run.
868       const VectorBase::SizeType numberOfRuns = mImpl->mLogicalModel->mColorRuns.Count();
869       mImpl->mLogicalModel->mColorRuns.Resize( numberOfRuns + 1u );
870
871       ColorRun& colorRun = *( mImpl->mLogicalModel->mColorRuns.Begin() + numberOfRuns );
872       colorRun.color = color;
873       colorRun.characterRun.characterIndex = startOfSelectedText;
874       colorRun.characterRun.numberOfCharacters = lengthOfSelectedText;
875
876       // Request to relayout.
877       mImpl->mOperationsPending = static_cast<OperationsMask>( mImpl->mOperationsPending | COLOR );
878       mImpl->RequestRelayout();
879
880       mImpl->mTextUpdateInfo.mCharacterIndex = startOfSelectedText;
881       mImpl->mTextUpdateInfo.mNumberOfCharactersToRemove = lengthOfSelectedText;
882       mImpl->mTextUpdateInfo.mNumberOfCharactersToAdd = lengthOfSelectedText;
883     }
884   }
885 }
886
887 const Vector4& Controller::GetInputColor() const
888 {
889   if( NULL != mImpl->mEventData )
890   {
891     return mImpl->mEventData->mInputStyle.textColor;
892   }
893
894   // Return the default text's color if there is no EventData.
895   return mImpl->mTextColor;
896
897 }
898
899 void Controller::SetInputFontFamily( const std::string& fontFamily )
900 {
901   if( NULL != mImpl->mEventData )
902   {
903     mImpl->mEventData->mInputStyle.familyName = fontFamily;
904     mImpl->mEventData->mInputStyle.familyDefined = true;
905
906     if( EventData::SELECTING == mImpl->mEventData->mState )
907     {
908       CharacterIndex startOfSelectedText = 0u;
909       Length lengthOfSelectedText = 0u;
910       FontDescriptionRun& fontDescriptionRun = UpdateSelectionFontStyleRun( mImpl->mEventData,
911                                                                             mImpl->mLogicalModel,
912                                                                             startOfSelectedText,
913                                                                             lengthOfSelectedText );
914
915       fontDescriptionRun.familyLength = fontFamily.size();
916       fontDescriptionRun.familyName = new char[fontDescriptionRun.familyLength];
917       memcpy( fontDescriptionRun.familyName, fontFamily.c_str(), fontDescriptionRun.familyLength );
918       fontDescriptionRun.familyDefined = true;
919
920       // The memory allocated for the font family name is freed when the font description is removed from the logical model.
921
922       // Request to relayout.
923       mImpl->mOperationsPending = static_cast<OperationsMask>( mImpl->mOperationsPending |
924                                                                VALIDATE_FONTS            |
925                                                                SHAPE_TEXT                |
926                                                                GET_GLYPH_METRICS         |
927                                                                LAYOUT                    |
928                                                                UPDATE_ACTUAL_SIZE        |
929                                                                REORDER                   |
930                                                                ALIGN );
931       mImpl->mRecalculateNaturalSize = true;
932       mImpl->RequestRelayout();
933
934       mImpl->mTextUpdateInfo.mCharacterIndex = startOfSelectedText;
935       mImpl->mTextUpdateInfo.mNumberOfCharactersToRemove = lengthOfSelectedText;
936       mImpl->mTextUpdateInfo.mNumberOfCharactersToAdd = lengthOfSelectedText;
937
938       // As the font changes, recalculate the handle positions is needed.
939       mImpl->mEventData->mUpdateLeftSelectionPosition = true;
940       mImpl->mEventData->mUpdateRightSelectionPosition = true;
941       mImpl->mEventData->mUpdateHighlightBox = true;
942       mImpl->mEventData->mScrollAfterUpdatePosition = true;
943     }
944   }
945 }
946
947 const std::string& Controller::GetInputFontFamily() const
948 {
949   if( NULL != mImpl->mEventData )
950   {
951     return mImpl->mEventData->mInputStyle.familyName;
952   }
953
954   // Return the default font's family if there is no EventData.
955   return GetDefaultFontFamily();
956 }
957
958 void Controller::SetInputFontStyle( const std::string& fontStyle )
959 {
960   if( NULL != mImpl->mEventData )
961   {
962     mImpl->mEventData->mInputStyle.fontStyle = fontStyle;
963   }
964 }
965
966 const std::string& Controller::GetInputFontStyle() const
967 {
968   if( NULL != mImpl->mEventData )
969   {
970     return mImpl->mEventData->mInputStyle.fontStyle;
971   }
972
973   // Return the default font's style if there is no EventData.
974   return GetDefaultFontStyle();
975 }
976
977 void Controller::SetInputFontWeight( FontWeight weight )
978 {
979   if( NULL != mImpl->mEventData )
980   {
981     mImpl->mEventData->mInputStyle.weight = weight;
982     mImpl->mEventData->mInputStyle.weightDefined = true;
983
984     if( EventData::SELECTING == mImpl->mEventData->mState )
985     {
986       CharacterIndex startOfSelectedText = 0u;
987       Length lengthOfSelectedText = 0u;
988       FontDescriptionRun& fontDescriptionRun = UpdateSelectionFontStyleRun( mImpl->mEventData,
989                                                                             mImpl->mLogicalModel,
990                                                                             startOfSelectedText,
991                                                                             lengthOfSelectedText );
992
993       fontDescriptionRun.weight = weight;
994       fontDescriptionRun.weightDefined = true;
995
996       // Request to relayout.
997       mImpl->mOperationsPending = static_cast<OperationsMask>( mImpl->mOperationsPending |
998                                                                VALIDATE_FONTS            |
999                                                                SHAPE_TEXT                |
1000                                                                GET_GLYPH_METRICS         |
1001                                                                LAYOUT                    |
1002                                                                UPDATE_ACTUAL_SIZE        |
1003                                                                REORDER                   |
1004                                                                ALIGN );
1005       mImpl->mRecalculateNaturalSize = true;
1006       mImpl->RequestRelayout();
1007
1008       mImpl->mTextUpdateInfo.mCharacterIndex = startOfSelectedText;
1009       mImpl->mTextUpdateInfo.mNumberOfCharactersToRemove = lengthOfSelectedText;
1010       mImpl->mTextUpdateInfo.mNumberOfCharactersToAdd = lengthOfSelectedText;
1011
1012       // As the font might change, recalculate the handle positions is needed.
1013       mImpl->mEventData->mUpdateLeftSelectionPosition = true;
1014       mImpl->mEventData->mUpdateRightSelectionPosition = true;
1015       mImpl->mEventData->mUpdateHighlightBox = true;
1016       mImpl->mEventData->mScrollAfterUpdatePosition = true;
1017     }
1018   }
1019 }
1020
1021 FontWeight Controller::GetInputFontWeight() const
1022 {
1023   if( NULL != mImpl->mEventData )
1024   {
1025     return mImpl->mEventData->mInputStyle.weight;
1026   }
1027
1028   return GetDefaultFontWeight();
1029 }
1030
1031 void Controller::SetInputFontWidth( FontWidth width )
1032 {
1033   if( NULL != mImpl->mEventData )
1034   {
1035     mImpl->mEventData->mInputStyle.width = width;
1036     mImpl->mEventData->mInputStyle.widthDefined = true;
1037
1038     if( EventData::SELECTING == mImpl->mEventData->mState )
1039     {
1040       CharacterIndex startOfSelectedText = 0u;
1041       Length lengthOfSelectedText = 0u;
1042       FontDescriptionRun& fontDescriptionRun = UpdateSelectionFontStyleRun( mImpl->mEventData,
1043                                                                             mImpl->mLogicalModel,
1044                                                                             startOfSelectedText,
1045                                                                             lengthOfSelectedText );
1046
1047       fontDescriptionRun.width = width;
1048       fontDescriptionRun.widthDefined = true;
1049
1050       // Request to relayout.
1051       mImpl->mOperationsPending = static_cast<OperationsMask>( mImpl->mOperationsPending |
1052                                                                VALIDATE_FONTS            |
1053                                                                SHAPE_TEXT                |
1054                                                                GET_GLYPH_METRICS         |
1055                                                                LAYOUT                    |
1056                                                                UPDATE_ACTUAL_SIZE        |
1057                                                                REORDER                   |
1058                                                                ALIGN );
1059       mImpl->mRecalculateNaturalSize = true;
1060       mImpl->RequestRelayout();
1061
1062       mImpl->mTextUpdateInfo.mCharacterIndex = startOfSelectedText;
1063       mImpl->mTextUpdateInfo.mNumberOfCharactersToRemove = lengthOfSelectedText;
1064       mImpl->mTextUpdateInfo.mNumberOfCharactersToAdd = lengthOfSelectedText;
1065
1066       // As the font might change, recalculate the handle positions is needed.
1067       mImpl->mEventData->mUpdateLeftSelectionPosition = true;
1068       mImpl->mEventData->mUpdateRightSelectionPosition = true;
1069       mImpl->mEventData->mUpdateHighlightBox = true;
1070       mImpl->mEventData->mScrollAfterUpdatePosition = true;
1071     }
1072   }
1073 }
1074
1075 FontWidth Controller::GetInputFontWidth() const
1076 {
1077   if( NULL != mImpl->mEventData )
1078   {
1079     return mImpl->mEventData->mInputStyle.width;
1080   }
1081
1082   return GetDefaultFontWidth();
1083 }
1084
1085 void Controller::SetInputFontSlant( FontSlant slant )
1086 {
1087   if( NULL != mImpl->mEventData )
1088   {
1089     mImpl->mEventData->mInputStyle.slant = slant;
1090     mImpl->mEventData->mInputStyle.slantDefined = true;
1091
1092     if( EventData::SELECTING == mImpl->mEventData->mState )
1093     {
1094       CharacterIndex startOfSelectedText = 0u;
1095       Length lengthOfSelectedText = 0u;
1096       FontDescriptionRun& fontDescriptionRun = UpdateSelectionFontStyleRun( mImpl->mEventData,
1097                                                                             mImpl->mLogicalModel,
1098                                                                             startOfSelectedText,
1099                                                                             lengthOfSelectedText );
1100
1101       fontDescriptionRun.slant = slant;
1102       fontDescriptionRun.slantDefined = true;
1103
1104       // Request to relayout.
1105       mImpl->mOperationsPending = static_cast<OperationsMask>( mImpl->mOperationsPending |
1106                                                                VALIDATE_FONTS            |
1107                                                                SHAPE_TEXT                |
1108                                                                GET_GLYPH_METRICS         |
1109                                                                LAYOUT                    |
1110                                                                UPDATE_ACTUAL_SIZE        |
1111                                                                REORDER                   |
1112                                                                ALIGN );
1113       mImpl->mRecalculateNaturalSize = true;
1114       mImpl->RequestRelayout();
1115
1116       mImpl->mTextUpdateInfo.mCharacterIndex = startOfSelectedText;
1117       mImpl->mTextUpdateInfo.mNumberOfCharactersToRemove = lengthOfSelectedText;
1118       mImpl->mTextUpdateInfo.mNumberOfCharactersToAdd = lengthOfSelectedText;
1119
1120       // As the font might change, recalculate the handle positions is needed.
1121       mImpl->mEventData->mUpdateLeftSelectionPosition = true;
1122       mImpl->mEventData->mUpdateRightSelectionPosition = true;
1123       mImpl->mEventData->mUpdateHighlightBox = true;
1124       mImpl->mEventData->mScrollAfterUpdatePosition = true;
1125     }
1126   }
1127 }
1128
1129 FontSlant Controller::GetInputFontSlant() const
1130 {
1131   if( NULL != mImpl->mEventData )
1132   {
1133     return mImpl->mEventData->mInputStyle.slant;
1134   }
1135
1136   return GetDefaultFontSlant();
1137 }
1138
1139 void Controller::SetInputFontPointSize( float size )
1140 {
1141   if( NULL != mImpl->mEventData )
1142   {
1143     mImpl->mEventData->mInputStyle.size = size;
1144
1145     if( EventData::SELECTING == mImpl->mEventData->mState )
1146     {
1147       CharacterIndex startOfSelectedText = 0u;
1148       Length lengthOfSelectedText = 0u;
1149       FontDescriptionRun& fontDescriptionRun = UpdateSelectionFontStyleRun( mImpl->mEventData,
1150                                                                             mImpl->mLogicalModel,
1151                                                                             startOfSelectedText,
1152                                                                             lengthOfSelectedText );
1153
1154       fontDescriptionRun.size = static_cast<PointSize26Dot6>( size * 64.f );
1155       fontDescriptionRun.sizeDefined = true;
1156
1157       // Request to relayout.
1158       mImpl->mOperationsPending = static_cast<OperationsMask>( mImpl->mOperationsPending |
1159                                                                VALIDATE_FONTS            |
1160                                                                SHAPE_TEXT                |
1161                                                                GET_GLYPH_METRICS         |
1162                                                                LAYOUT                    |
1163                                                                UPDATE_ACTUAL_SIZE        |
1164                                                                REORDER                   |
1165                                                                ALIGN );
1166       mImpl->mRecalculateNaturalSize = true;
1167       mImpl->RequestRelayout();
1168
1169       mImpl->mTextUpdateInfo.mCharacterIndex = startOfSelectedText;
1170       mImpl->mTextUpdateInfo.mNumberOfCharactersToRemove = lengthOfSelectedText;
1171       mImpl->mTextUpdateInfo.mNumberOfCharactersToAdd = lengthOfSelectedText;
1172
1173       // As the font might change, recalculate the handle positions is needed.
1174       mImpl->mEventData->mUpdateLeftSelectionPosition = true;
1175       mImpl->mEventData->mUpdateRightSelectionPosition = true;
1176       mImpl->mEventData->mUpdateHighlightBox = true;
1177       mImpl->mEventData->mScrollAfterUpdatePosition = true;
1178     }
1179   }
1180 }
1181
1182 float Controller::GetInputFontPointSize() const
1183 {
1184   if( NULL != mImpl->mEventData )
1185   {
1186     return mImpl->mEventData->mInputStyle.size;
1187   }
1188
1189   // Return the default font's point size if there is no EventData.
1190   return GetDefaultPointSize();
1191 }
1192
1193 void Controller::SetInputLineSpacing( float lineSpacing )
1194 {
1195   if( NULL != mImpl->mEventData )
1196   {
1197     mImpl->mEventData->mInputStyle.lineSpacing = lineSpacing;
1198   }
1199 }
1200
1201 float Controller::GetInputLineSpacing() const
1202 {
1203   if( NULL != mImpl->mEventData )
1204   {
1205     return mImpl->mEventData->mInputStyle.lineSpacing;
1206   }
1207
1208   return 0.f;
1209 }
1210
1211 void Controller::SetInputShadowProperties( const std::string& shadowProperties )
1212 {
1213   if( NULL != mImpl->mEventData )
1214   {
1215     mImpl->mEventData->mInputStyle.shadowProperties = shadowProperties;
1216   }
1217 }
1218
1219 const std::string& Controller::GetInputShadowProperties() const
1220 {
1221   if( NULL != mImpl->mEventData )
1222   {
1223     return mImpl->mEventData->mInputStyle.shadowProperties;
1224   }
1225
1226   return GetDefaultShadowProperties();
1227 }
1228
1229 void Controller::SetInputUnderlineProperties( const std::string& underlineProperties )
1230 {
1231   if( NULL != mImpl->mEventData )
1232   {
1233     mImpl->mEventData->mInputStyle.underlineProperties = underlineProperties;
1234   }
1235 }
1236
1237 const std::string& Controller::GetInputUnderlineProperties() const
1238 {
1239   if( NULL != mImpl->mEventData )
1240   {
1241     return mImpl->mEventData->mInputStyle.underlineProperties;
1242   }
1243
1244   return GetDefaultUnderlineProperties();
1245 }
1246
1247 void Controller::SetInputEmbossProperties( const std::string& embossProperties )
1248 {
1249   if( NULL != mImpl->mEventData )
1250   {
1251     mImpl->mEventData->mInputStyle.embossProperties = embossProperties;
1252   }
1253 }
1254
1255 const std::string& Controller::GetInputEmbossProperties() const
1256 {
1257   if( NULL != mImpl->mEventData )
1258   {
1259     return mImpl->mEventData->mInputStyle.embossProperties;
1260   }
1261
1262   return GetDefaultEmbossProperties();
1263 }
1264
1265 void Controller::SetInputOutlineProperties( const std::string& outlineProperties )
1266 {
1267   if( NULL != mImpl->mEventData )
1268   {
1269     mImpl->mEventData->mInputStyle.outlineProperties = outlineProperties;
1270   }
1271 }
1272
1273 const std::string& Controller::GetInputOutlineProperties() const
1274 {
1275   if( NULL != mImpl->mEventData )
1276   {
1277     return mImpl->mEventData->mInputStyle.outlineProperties;
1278   }
1279
1280   return GetDefaultOutlineProperties();
1281 }
1282
1283 void Controller::SetEnableCursorBlink( bool enable )
1284 {
1285   DALI_ASSERT_DEBUG( NULL != mImpl->mEventData && "TextInput disabled" );
1286
1287   if( NULL != mImpl->mEventData )
1288   {
1289     mImpl->mEventData->mCursorBlinkEnabled = enable;
1290
1291     if( !enable &&
1292         mImpl->mEventData->mDecorator )
1293     {
1294       mImpl->mEventData->mDecorator->StopCursorBlink();
1295     }
1296   }
1297 }
1298
1299 bool Controller::GetEnableCursorBlink() const
1300 {
1301   if( NULL != mImpl->mEventData )
1302   {
1303     return mImpl->mEventData->mCursorBlinkEnabled;
1304   }
1305
1306   return false;
1307 }
1308
1309 const Vector2& Controller::GetScrollPosition() const
1310 {
1311   return mImpl->mScrollPosition;
1312 }
1313
1314 Vector3 Controller::GetNaturalSize()
1315 {
1316   DALI_LOG_INFO( gLogFilter, Debug::Verbose, "-->Controller::GetNaturalSize\n" );
1317   Vector3 naturalSize;
1318
1319   // Make sure the model is up-to-date before layouting
1320   ProcessModifyEvents();
1321
1322   if( mImpl->mRecalculateNaturalSize )
1323   {
1324     // Operations that can be done only once until the text changes.
1325     const OperationsMask onlyOnceOperations = static_cast<OperationsMask>( CONVERT_TO_UTF32  |
1326                                                                            GET_SCRIPTS       |
1327                                                                            VALIDATE_FONTS    |
1328                                                                            GET_LINE_BREAKS   |
1329                                                                            GET_WORD_BREAKS   |
1330                                                                            BIDI_INFO         |
1331                                                                            SHAPE_TEXT        |
1332                                                                            GET_GLYPH_METRICS );
1333     // Make sure the model is up-to-date before layouting
1334     mImpl->UpdateModel( onlyOnceOperations );
1335
1336     // Layout the text for the new width.
1337     mImpl->mOperationsPending = static_cast<OperationsMask>( mImpl->mOperationsPending | LAYOUT );
1338
1339     // Set the update info to relayout the whole text.
1340     mImpl->mTextUpdateInfo.mParagraphCharacterIndex = 0u;
1341     mImpl->mTextUpdateInfo.mRequestedNumberOfCharacters = mImpl->mLogicalModel->mText.Count();
1342
1343     // Store the actual control's size to restore later.
1344     const Size actualControlSize = mImpl->mVisualModel->mControlSize;
1345
1346     DoRelayout( Size( MAX_FLOAT, MAX_FLOAT ),
1347                 static_cast<OperationsMask>( onlyOnceOperations |
1348                                              LAYOUT ),
1349                 naturalSize.GetVectorXY() );
1350
1351     // Do not do again the only once operations.
1352     mImpl->mOperationsPending = static_cast<OperationsMask>( mImpl->mOperationsPending & ~onlyOnceOperations );
1353
1354     // Do the size related operations again.
1355     const OperationsMask sizeOperations =  static_cast<OperationsMask>( LAYOUT |
1356                                                                         ALIGN  |
1357                                                                         REORDER );
1358     mImpl->mOperationsPending = static_cast<OperationsMask>( mImpl->mOperationsPending | sizeOperations );
1359
1360     // Stores the natural size to avoid recalculate it again
1361     // unless the text/style changes.
1362     mImpl->mVisualModel->SetNaturalSize( naturalSize.GetVectorXY() );
1363
1364     mImpl->mRecalculateNaturalSize = false;
1365
1366     // Clear the update info. This info will be set the next time the text is updated.
1367     mImpl->mTextUpdateInfo.Clear();
1368
1369     // Restore the actual control's size.
1370     mImpl->mVisualModel->mControlSize = actualControlSize;
1371
1372     DALI_LOG_INFO( gLogFilter, Debug::Verbose, "<--Controller::GetNaturalSize calculated %f,%f,%f\n", naturalSize.x, naturalSize.y, naturalSize.z );
1373   }
1374   else
1375   {
1376     naturalSize = mImpl->mVisualModel->GetNaturalSize();
1377
1378     DALI_LOG_INFO( gLogFilter, Debug::Verbose, "<--Controller::GetNaturalSize cached %f,%f,%f\n", naturalSize.x, naturalSize.y, naturalSize.z );
1379   }
1380
1381   naturalSize.x = ConvertToEven( naturalSize.x );
1382   naturalSize.y = ConvertToEven( naturalSize.y );
1383
1384   return naturalSize;
1385 }
1386
1387 float Controller::GetHeightForWidth( float width )
1388 {
1389   DALI_LOG_INFO( gLogFilter, Debug::Verbose, "-->Controller::GetHeightForWidth %p width %f\n", this, width );
1390   // Make sure the model is up-to-date before layouting
1391   ProcessModifyEvents();
1392
1393   Size layoutSize;
1394   if( fabsf( width - mImpl->mVisualModel->mControlSize.width ) > Math::MACHINE_EPSILON_1000 )
1395   {
1396     // Operations that can be done only once until the text changes.
1397     const OperationsMask onlyOnceOperations = static_cast<OperationsMask>( CONVERT_TO_UTF32  |
1398                                                                            GET_SCRIPTS       |
1399                                                                            VALIDATE_FONTS    |
1400                                                                            GET_LINE_BREAKS   |
1401                                                                            GET_WORD_BREAKS   |
1402                                                                            BIDI_INFO         |
1403                                                                            SHAPE_TEXT        |
1404                                                                            GET_GLYPH_METRICS );
1405     // Make sure the model is up-to-date before layouting
1406     mImpl->UpdateModel( onlyOnceOperations );
1407
1408
1409     // Layout the text for the new width.
1410     mImpl->mOperationsPending = static_cast<OperationsMask>( mImpl->mOperationsPending | LAYOUT );
1411
1412     // Set the update info to relayout the whole text.
1413     mImpl->mTextUpdateInfo.mParagraphCharacterIndex = 0u;
1414     mImpl->mTextUpdateInfo.mRequestedNumberOfCharacters = mImpl->mLogicalModel->mText.Count();
1415
1416     // Store the actual control's width.
1417     const float actualControlWidth = mImpl->mVisualModel->mControlSize.width;
1418
1419     DoRelayout( Size( width, MAX_FLOAT ),
1420                 static_cast<OperationsMask>( onlyOnceOperations |
1421                                              LAYOUT ),
1422                 layoutSize );
1423
1424     // Do not do again the only once operations.
1425     mImpl->mOperationsPending = static_cast<OperationsMask>( mImpl->mOperationsPending & ~onlyOnceOperations );
1426
1427     // Do the size related operations again.
1428     const OperationsMask sizeOperations =  static_cast<OperationsMask>( LAYOUT |
1429                                                                         ALIGN  |
1430                                                                         REORDER );
1431
1432     mImpl->mOperationsPending = static_cast<OperationsMask>( mImpl->mOperationsPending | sizeOperations );
1433
1434     // Clear the update info. This info will be set the next time the text is updated.
1435     mImpl->mTextUpdateInfo.Clear();
1436
1437     // Restore the actual control's width.
1438     mImpl->mVisualModel->mControlSize.width = actualControlWidth;
1439
1440     DALI_LOG_INFO( gLogFilter, Debug::Verbose, "<--Controller::GetHeightForWidth calculated %f\n", layoutSize.height );
1441   }
1442   else
1443   {
1444     layoutSize = mImpl->mVisualModel->GetLayoutSize();
1445     DALI_LOG_INFO( gLogFilter, Debug::Verbose, "<--Controller::GetHeightForWidth cached %f\n", layoutSize.height );
1446   }
1447
1448   return layoutSize.height;
1449 }
1450
1451 Controller::UpdateTextType Controller::Relayout( const Size& size )
1452 {
1453   DALI_LOG_INFO( gLogFilter, Debug::Verbose, "-->Controller::Relayout %p size %f,%f, autoScroll[%s]\n", this, size.width, size.height, (mImpl->mAutoScrollEnabled)?"true":"false"  );
1454
1455   UpdateTextType updateTextType = NONE_UPDATED;
1456
1457   if( ( size.width < Math::MACHINE_EPSILON_1000 ) || ( size.height < Math::MACHINE_EPSILON_1000 ) )
1458   {
1459     if( 0u != mImpl->mVisualModel->mGlyphPositions.Count() )
1460     {
1461       mImpl->mVisualModel->mGlyphPositions.Clear();
1462       updateTextType = MODEL_UPDATED;
1463     }
1464
1465     // Clear the update info. This info will be set the next time the text is updated.
1466     mImpl->mTextUpdateInfo.Clear();
1467
1468     // Not worth to relayout if width or height is equal to zero.
1469     DALI_LOG_INFO( gLogFilter, Debug::Verbose, "<--Controller::Relayout (skipped)\n" );
1470
1471     return updateTextType;
1472   }
1473
1474   // Whether a new size has been set.
1475   const bool newSize = ( size != mImpl->mVisualModel->mControlSize );
1476
1477   if( newSize )
1478   {
1479     DALI_LOG_INFO( gLogFilter, Debug::Verbose, "new size (previous size %f,%f)\n", mImpl->mVisualModel->mControlSize.width, mImpl->mVisualModel->mControlSize.height );
1480
1481     // Layout operations that need to be done if the size changes.
1482     mImpl->mOperationsPending = static_cast<OperationsMask>( mImpl->mOperationsPending |
1483                                                              LAYOUT                    |
1484                                                              ALIGN                     |
1485                                                              UPDATE_ACTUAL_SIZE        |
1486                                                              REORDER );
1487     // Set the update info to relayout the whole text.
1488     mImpl->mTextUpdateInfo.mFullRelayoutNeeded = true;
1489     mImpl->mTextUpdateInfo.mCharacterIndex = 0u;
1490   }
1491
1492   // Whether there are modify events.
1493   if( 0u != mImpl->mModifyEvents.Count() )
1494   {
1495     // Style operations that need to be done if the text is modified.
1496     mImpl->mOperationsPending = static_cast<OperationsMask>( mImpl->mOperationsPending |
1497                                                              COLOR );
1498   }
1499
1500   // Make sure the model is up-to-date before layouting.
1501   ProcessModifyEvents();
1502   bool updated = mImpl->UpdateModel( mImpl->mOperationsPending );
1503
1504   // Layout the text.
1505   Size layoutSize;
1506   updated = DoRelayout( size,
1507                         mImpl->mOperationsPending,
1508                         layoutSize ) || updated;
1509
1510   if( updated )
1511   {
1512     updateTextType = MODEL_UPDATED;
1513   }
1514
1515   // Do not re-do any operation until something changes.
1516   mImpl->mOperationsPending = NO_OPERATION;
1517
1518   // Whether the text control is editable
1519   const bool isEditable = NULL != mImpl->mEventData;
1520
1521   // Keep the current offset as it will be used to update the decorator's positions (if the size changes).
1522   Vector2 offset;
1523   if( newSize && isEditable )
1524   {
1525     offset = mImpl->mScrollPosition;
1526   }
1527
1528   if( !isEditable || !IsMultiLineEnabled() )
1529   {
1530     // After doing the text layout, the vertical offset to place the actor in the desired position can be calculated.
1531     CalculateVerticalOffset( size );
1532   }
1533
1534   if( isEditable )
1535   {
1536     if( newSize )
1537     {
1538       // If there is a new size, the scroll position needs to be clamped.
1539       mImpl->ClampHorizontalScroll( layoutSize );
1540
1541       // Update the decorator's positions is needed if there is a new size.
1542       mImpl->mEventData->mDecorator->UpdatePositions( mImpl->mScrollPosition - offset );
1543     }
1544
1545     // Move the cursor, grab handle etc.
1546     if( mImpl->ProcessInputEvents() )
1547     {
1548       updateTextType = static_cast<UpdateTextType>( updateTextType | DECORATOR_UPDATED );
1549     }
1550   }
1551
1552   // Clear the update info. This info will be set the next time the text is updated.
1553   mImpl->mTextUpdateInfo.Clear();
1554   DALI_LOG_INFO( gLogFilter, Debug::Verbose, "<--Controller::Relayout\n" );
1555
1556   return updateTextType;
1557 }
1558
1559 void Controller::ProcessModifyEvents()
1560 {
1561   Vector<ModifyEvent>& events = mImpl->mModifyEvents;
1562
1563   if( 0u == events.Count() )
1564   {
1565     // Nothing to do.
1566     return;
1567   }
1568
1569   for( Vector<ModifyEvent>::ConstIterator it = events.Begin(),
1570          endIt = events.End();
1571        it != endIt;
1572        ++it )
1573   {
1574     const ModifyEvent& event = *it;
1575
1576     if( ModifyEvent::TEXT_REPLACED == event.type )
1577     {
1578       // A (single) replace event should come first, otherwise we wasted time processing NOOP events
1579       DALI_ASSERT_DEBUG( it == events.Begin() && "Unexpected TEXT_REPLACED event" );
1580
1581       TextReplacedEvent();
1582     }
1583     else if( ModifyEvent::TEXT_INSERTED == event.type )
1584     {
1585       TextInsertedEvent();
1586     }
1587     else if( ModifyEvent::TEXT_DELETED == event.type )
1588     {
1589       // Placeholder-text cannot be deleted
1590       if( !mImpl->IsShowingPlaceholderText() )
1591       {
1592         TextDeletedEvent();
1593       }
1594     }
1595   }
1596
1597   if( NULL != mImpl->mEventData )
1598   {
1599     // When the text is being modified, delay cursor blinking
1600     mImpl->mEventData->mDecorator->DelayCursorBlink();
1601   }
1602
1603   // Discard temporary text
1604   events.Clear();
1605 }
1606
1607 void Controller::ResetText()
1608 {
1609   // Reset buffers.
1610   mImpl->mLogicalModel->mText.Clear();
1611
1612   // We have cleared everything including the placeholder-text
1613   mImpl->PlaceholderCleared();
1614
1615   mImpl->mTextUpdateInfo.mCharacterIndex = 0u;
1616   mImpl->mTextUpdateInfo.mNumberOfCharactersToRemove = mImpl->mTextUpdateInfo.mPreviousNumberOfCharacters;
1617   mImpl->mTextUpdateInfo.mNumberOfCharactersToAdd = 0u;
1618
1619   // Clear any previous text.
1620   mImpl->mTextUpdateInfo.mClearAll = true;
1621
1622   // The natural size needs to be re-calculated.
1623   mImpl->mRecalculateNaturalSize = true;
1624
1625   // Apply modifications to the model
1626   mImpl->mOperationsPending = ALL_OPERATIONS;
1627 }
1628
1629 void Controller::ResetCursorPosition( CharacterIndex cursorIndex )
1630 {
1631   // Reset the cursor position
1632   if( NULL != mImpl->mEventData )
1633   {
1634     mImpl->mEventData->mPrimaryCursorPosition = cursorIndex;
1635
1636     // Update the cursor if it's in editing mode.
1637     if( EventData::IsEditingState( mImpl->mEventData->mState )  )
1638     {
1639       mImpl->mEventData->mUpdateCursorPosition = true;
1640     }
1641   }
1642 }
1643
1644 void Controller::ResetScrollPosition()
1645 {
1646   if( NULL != mImpl->mEventData )
1647   {
1648     // Reset the scroll position.
1649     mImpl->mScrollPosition = Vector2::ZERO;
1650     mImpl->mEventData->mScrollAfterUpdatePosition = true;
1651   }
1652 }
1653
1654 void Controller::TextReplacedEvent()
1655 {
1656   // The natural size needs to be re-calculated.
1657   mImpl->mRecalculateNaturalSize = true;
1658
1659   // Apply modifications to the model
1660   mImpl->mOperationsPending = ALL_OPERATIONS;
1661 }
1662
1663 void Controller::TextInsertedEvent()
1664 {
1665   DALI_ASSERT_DEBUG( NULL != mImpl->mEventData && "Unexpected TextInsertedEvent" );
1666
1667   if( NULL == mImpl->mEventData )
1668   {
1669     return;
1670   }
1671
1672   // The natural size needs to be re-calculated.
1673   mImpl->mRecalculateNaturalSize = true;
1674
1675   // Apply modifications to the model; TODO - Optimize this
1676   mImpl->mOperationsPending = ALL_OPERATIONS;
1677 }
1678
1679 void Controller::TextDeletedEvent()
1680 {
1681   DALI_ASSERT_DEBUG( NULL != mImpl->mEventData && "Unexpected TextDeletedEvent" );
1682
1683   if( NULL == mImpl->mEventData )
1684   {
1685     return;
1686   }
1687
1688   // The natural size needs to be re-calculated.
1689   mImpl->mRecalculateNaturalSize = true;
1690
1691   // Apply modifications to the model; TODO - Optimize this
1692   mImpl->mOperationsPending = ALL_OPERATIONS;
1693 }
1694
1695 bool Controller::DoRelayout( const Size& size,
1696                              OperationsMask operationsRequired,
1697                              Size& layoutSize )
1698 {
1699   DALI_LOG_INFO( gLogFilter, Debug::Verbose, "-->Controller::DoRelayout %p size %f,%f\n", this, size.width, size.height );
1700   bool viewUpdated( false );
1701
1702   // Calculate the operations to be done.
1703   const OperationsMask operations = static_cast<OperationsMask>( mImpl->mOperationsPending & operationsRequired );
1704
1705   const CharacterIndex startIndex = mImpl->mTextUpdateInfo.mParagraphCharacterIndex;
1706   const Length requestedNumberOfCharacters = mImpl->mTextUpdateInfo.mRequestedNumberOfCharacters;
1707
1708   if( NO_OPERATION != ( LAYOUT & operations ) )
1709   {
1710     DALI_LOG_INFO( gLogFilter, Debug::Verbose, "-->Controller::DoRelayout LAYOUT & operations\n");
1711
1712     // Some vectors with data needed to layout and reorder may be void
1713     // after the first time the text has been laid out.
1714     // Fill the vectors again.
1715
1716     // Calculate the number of glyphs to layout.
1717     const Vector<GlyphIndex>& charactersToGlyph = mImpl->mVisualModel->mCharactersToGlyph;
1718     const Vector<Length>& glyphsPerCharacter = mImpl->mVisualModel->mGlyphsPerCharacter;
1719     const GlyphIndex* const charactersToGlyphBuffer = charactersToGlyph.Begin();
1720     const Length* const glyphsPerCharacterBuffer = glyphsPerCharacter.Begin();
1721
1722     const CharacterIndex lastIndex = startIndex + ( ( requestedNumberOfCharacters > 0u ) ? requestedNumberOfCharacters - 1u : 0u );
1723     const GlyphIndex startGlyphIndex = mImpl->mTextUpdateInfo.mStartGlyphIndex;
1724     const Length numberOfGlyphs = ( requestedNumberOfCharacters > 0u ) ? *( charactersToGlyphBuffer + lastIndex ) + *( glyphsPerCharacterBuffer + lastIndex ) - startGlyphIndex : 0u;
1725     const Length totalNumberOfGlyphs = mImpl->mVisualModel->mGlyphs.Count();
1726
1727     if( 0u == totalNumberOfGlyphs )
1728     {
1729       if( NO_OPERATION != ( UPDATE_ACTUAL_SIZE & operations ) )
1730       {
1731         mImpl->mVisualModel->SetLayoutSize( Size::ZERO );
1732       }
1733
1734       // Nothing else to do if there is no glyphs.
1735       DALI_LOG_INFO( gLogFilter, Debug::Verbose, "<--Controller::DoRelayout no glyphs, view updated true\n" );
1736       return true;
1737     }
1738
1739     const Vector<LineBreakInfo>& lineBreakInfo = mImpl->mLogicalModel->mLineBreakInfo;
1740     const Vector<WordBreakInfo>& wordBreakInfo = mImpl->mLogicalModel->mWordBreakInfo;
1741     const Vector<CharacterDirection>& characterDirection = mImpl->mLogicalModel->mCharacterDirections;
1742     const Vector<GlyphInfo>& glyphs = mImpl->mVisualModel->mGlyphs;
1743     const Vector<CharacterIndex>& glyphsToCharactersMap = mImpl->mVisualModel->mGlyphsToCharacters;
1744     const Vector<Length>& charactersPerGlyph = mImpl->mVisualModel->mCharactersPerGlyph;
1745     const Character* const textBuffer = mImpl->mLogicalModel->mText.Begin();
1746
1747     // Set the layout parameters.
1748     LayoutParameters layoutParameters( size,
1749                                        textBuffer,
1750                                        lineBreakInfo.Begin(),
1751                                        wordBreakInfo.Begin(),
1752                                        ( 0u != characterDirection.Count() ) ? characterDirection.Begin() : NULL,
1753                                        glyphs.Begin(),
1754                                        glyphsToCharactersMap.Begin(),
1755                                        charactersPerGlyph.Begin(),
1756                                        charactersToGlyphBuffer,
1757                                        glyphsPerCharacterBuffer,
1758                                        totalNumberOfGlyphs );
1759
1760     // Resize the vector of positions to have the same size than the vector of glyphs.
1761     Vector<Vector2>& glyphPositions = mImpl->mVisualModel->mGlyphPositions;
1762     glyphPositions.Resize( totalNumberOfGlyphs );
1763
1764     // Whether the last character is a new paragraph character.
1765     mImpl->mTextUpdateInfo.mIsLastCharacterNewParagraph =  TextAbstraction::IsNewParagraph( *( textBuffer + ( mImpl->mLogicalModel->mText.Count() - 1u ) ) );
1766     layoutParameters.isLastNewParagraph = mImpl->mTextUpdateInfo.mIsLastCharacterNewParagraph;
1767
1768     // The initial glyph and the number of glyphs to layout.
1769     layoutParameters.startGlyphIndex = startGlyphIndex;
1770     layoutParameters.numberOfGlyphs = numberOfGlyphs;
1771     layoutParameters.startLineIndex = mImpl->mTextUpdateInfo.mStartLineIndex;
1772     layoutParameters.estimatedNumberOfLines = mImpl->mTextUpdateInfo.mEstimatedNumberOfLines;
1773
1774     // Update the visual model.
1775     viewUpdated = mImpl->mLayoutEngine.LayoutText( layoutParameters,
1776                                                    glyphPositions,
1777                                                    mImpl->mVisualModel->mLines,
1778                                                    layoutSize );
1779
1780
1781     if( viewUpdated )
1782     {
1783       if ( NO_OPERATION != ( UPDATE_DIRECTION & operations ) )
1784       {
1785         mImpl->mAutoScrollDirectionRTL = false;
1786       }
1787
1788       // Reorder the lines
1789       if( NO_OPERATION != ( REORDER & operations ) )
1790       {
1791         Vector<BidirectionalParagraphInfoRun>& bidirectionalInfo = mImpl->mLogicalModel->mBidirectionalParagraphInfo;
1792         Vector<BidirectionalLineInfoRun>& bidirectionalLineInfo = mImpl->mLogicalModel->mBidirectionalLineInfo;
1793
1794         // Check first if there are paragraphs with bidirectional info.
1795         if( 0u != bidirectionalInfo.Count() )
1796         {
1797           // Get the lines
1798           const Length numberOfLines = mImpl->mVisualModel->mLines.Count();
1799
1800           // Reorder the lines.
1801           bidirectionalLineInfo.Reserve( numberOfLines ); // Reserve because is not known yet how many lines have right to left characters.
1802           ReorderLines( bidirectionalInfo,
1803                         startIndex,
1804                         requestedNumberOfCharacters,
1805                         mImpl->mVisualModel->mLines,
1806                         bidirectionalLineInfo );
1807
1808           // Set the bidirectional info per line into the layout parameters.
1809           layoutParameters.lineBidirectionalInfoRunsBuffer = bidirectionalLineInfo.Begin();
1810           layoutParameters.numberOfBidirectionalInfoRuns = bidirectionalLineInfo.Count();
1811
1812           // Re-layout the text. Reorder those lines with right to left characters.
1813           mImpl->mLayoutEngine.ReLayoutRightToLeftLines( layoutParameters,
1814                                                          startIndex,
1815                                                          requestedNumberOfCharacters,
1816                                                          glyphPositions );
1817
1818           if ( ( NO_OPERATION != ( UPDATE_DIRECTION & operations ) ) && ( numberOfLines > 0 ) )
1819           {
1820             const LineRun* const firstline = mImpl->mVisualModel->mLines.Begin();
1821             if ( firstline )
1822             {
1823               mImpl->mAutoScrollDirectionRTL = firstline->direction;
1824             }
1825           }
1826         }
1827       } // REORDER
1828
1829       // Sets the actual size.
1830       if( NO_OPERATION != ( UPDATE_ACTUAL_SIZE & operations ) )
1831       {
1832         mImpl->mVisualModel->SetLayoutSize( layoutSize );
1833       }
1834     } // view updated
1835
1836     // Store the size used to layout the text.
1837     mImpl->mVisualModel->mControlSize = size;
1838   }
1839   else
1840   {
1841     layoutSize = mImpl->mVisualModel->GetLayoutSize();
1842   }
1843
1844   if( NO_OPERATION != ( ALIGN & operations ) )
1845   {
1846     // The laid-out lines.
1847     Vector<LineRun>& lines = mImpl->mVisualModel->mLines;
1848
1849     mImpl->mLayoutEngine.Align( size,
1850                                 startIndex,
1851                                 requestedNumberOfCharacters,
1852                                 lines );
1853
1854     viewUpdated = true;
1855   }
1856 #if defined(DEBUG_ENABLED)
1857   std::string currentText;
1858   GetText( currentText );
1859   DALI_LOG_INFO( gLogFilter, Debug::Concise, "Controller::DoRelayout [%p] mImpl->mAutoScrollDirectionRTL[%s] [%s]\n", this, (mImpl->mAutoScrollDirectionRTL)?"true":"false",  currentText.c_str() );
1860 #endif
1861   DALI_LOG_INFO( gLogFilter, Debug::Verbose, "<--Controller::DoRelayout, view updated %s\n", ( viewUpdated ? "true" : "false" ) );
1862   return viewUpdated;
1863 }
1864
1865 void Controller::SetMultiLineEnabled( bool enable )
1866 {
1867   const LayoutEngine::Layout layout = enable ? LayoutEngine::MULTI_LINE_BOX : LayoutEngine::SINGLE_LINE_BOX;
1868
1869   if( layout != mImpl->mLayoutEngine.GetLayout() )
1870   {
1871     // Set the layout type.
1872     mImpl->mLayoutEngine.SetLayout( layout );
1873
1874     // Set the flags to redo the layout operations
1875     const OperationsMask layoutOperations =  static_cast<OperationsMask>( LAYOUT             |
1876                                                                           UPDATE_ACTUAL_SIZE |
1877                                                                           ALIGN              |
1878                                                                           REORDER );
1879
1880     mImpl->mOperationsPending = static_cast<OperationsMask>( mImpl->mOperationsPending | layoutOperations );
1881
1882     mImpl->RequestRelayout();
1883   }
1884 }
1885
1886 bool Controller::IsMultiLineEnabled() const
1887 {
1888   return LayoutEngine::MULTI_LINE_BOX == mImpl->mLayoutEngine.GetLayout();
1889 }
1890
1891 void Controller::SetHorizontalAlignment( LayoutEngine::HorizontalAlignment alignment )
1892 {
1893   if( alignment != mImpl->mLayoutEngine.GetHorizontalAlignment() )
1894   {
1895     // Set the alignment.
1896     mImpl->mLayoutEngine.SetHorizontalAlignment( alignment );
1897
1898     // Set the flag to redo the alignment operation.
1899     mImpl->mOperationsPending = static_cast<OperationsMask>( mImpl->mOperationsPending | ALIGN );
1900
1901     mImpl->RequestRelayout();
1902   }
1903 }
1904
1905 LayoutEngine::HorizontalAlignment Controller::GetHorizontalAlignment() const
1906 {
1907   return mImpl->mLayoutEngine.GetHorizontalAlignment();
1908 }
1909
1910 void Controller::SetVerticalAlignment( LayoutEngine::VerticalAlignment alignment )
1911 {
1912   if( alignment != mImpl->mLayoutEngine.GetVerticalAlignment() )
1913   {
1914     // Set the alignment.
1915     mImpl->mLayoutEngine.SetVerticalAlignment( alignment );
1916
1917     mImpl->mOperationsPending = static_cast<OperationsMask>( mImpl->mOperationsPending | ALIGN );
1918
1919     mImpl->RequestRelayout();
1920   }
1921 }
1922
1923 LayoutEngine::VerticalAlignment Controller::GetVerticalAlignment() const
1924 {
1925   return mImpl->mLayoutEngine.GetVerticalAlignment();
1926 }
1927
1928 void Controller::CalculateVerticalOffset( const Size& controlSize )
1929 {
1930   Size layoutSize = mImpl->mVisualModel->GetLayoutSize();
1931
1932   if( fabsf( layoutSize.height ) < Math::MACHINE_EPSILON_1000 )
1933   {
1934     // Get the line height of the default font.
1935     layoutSize.height = mImpl->GetDefaultFontLineHeight();
1936   }
1937
1938   switch( mImpl->mLayoutEngine.GetVerticalAlignment() )
1939   {
1940     case LayoutEngine::VERTICAL_ALIGN_TOP:
1941     {
1942       mImpl->mScrollPosition.y = 0.f;
1943       break;
1944     }
1945     case LayoutEngine::VERTICAL_ALIGN_CENTER:
1946     {
1947       mImpl->mScrollPosition.y = floorf( 0.5f * ( controlSize.height - layoutSize.height ) ); // try to avoid pixel alignment.
1948       break;
1949     }
1950     case LayoutEngine::VERTICAL_ALIGN_BOTTOM:
1951     {
1952       mImpl->mScrollPosition.y = controlSize.height - layoutSize.height;
1953       break;
1954     }
1955   }
1956 }
1957
1958 LayoutEngine& Controller::GetLayoutEngine()
1959 {
1960   return mImpl->mLayoutEngine;
1961 }
1962
1963 View& Controller::GetView()
1964 {
1965   return mImpl->mView;
1966 }
1967
1968 void Controller::KeyboardFocusGainEvent()
1969 {
1970   DALI_ASSERT_DEBUG( mImpl->mEventData && "Unexpected KeyboardFocusGainEvent" );
1971
1972   if( NULL != mImpl->mEventData )
1973   {
1974     if( ( EventData::INACTIVE == mImpl->mEventData->mState ) ||
1975         ( EventData::INTERRUPTED == mImpl->mEventData->mState ) )
1976     {
1977       mImpl->ChangeState( EventData::EDITING );
1978       mImpl->mEventData->mUpdateCursorPosition = true; //If editing started without tap event, cursor update must be triggered.
1979     }
1980
1981     if( mImpl->IsShowingPlaceholderText() )
1982     {
1983       // Show alternative placeholder-text when editing
1984       ShowPlaceholderText();
1985     }
1986
1987     mImpl->RequestRelayout();
1988   }
1989 }
1990
1991 void Controller::KeyboardFocusLostEvent()
1992 {
1993   DALI_ASSERT_DEBUG( mImpl->mEventData && "Unexpected KeyboardFocusLostEvent" );
1994
1995   if( NULL != mImpl->mEventData )
1996   {
1997     if( EventData::INTERRUPTED != mImpl->mEventData->mState )
1998     {
1999       mImpl->ChangeState( EventData::INACTIVE );
2000
2001       if( !mImpl->IsShowingRealText() )
2002       {
2003         // Revert to regular placeholder-text when not editing
2004         ShowPlaceholderText();
2005       }
2006     }
2007   }
2008   mImpl->RequestRelayout();
2009 }
2010
2011 bool Controller::KeyEvent( const Dali::KeyEvent& keyEvent )
2012 {
2013   DALI_ASSERT_DEBUG( mImpl->mEventData && "Unexpected KeyEvent" );
2014
2015   bool textChanged( false );
2016
2017   if( ( NULL != mImpl->mEventData ) &&
2018       ( keyEvent.state == KeyEvent::Down ) )
2019   {
2020     int keyCode = keyEvent.keyCode;
2021     const std::string& keyString = keyEvent.keyPressed;
2022
2023     // Pre-process to separate modifying events from non-modifying input events.
2024     if( Dali::DALI_KEY_ESCAPE == keyCode )
2025     {
2026       // Escape key is a special case which causes focus loss
2027       KeyboardFocusLostEvent();
2028     }
2029     else if( ( Dali::DALI_KEY_CURSOR_LEFT  == keyCode ) ||
2030              ( Dali::DALI_KEY_CURSOR_RIGHT == keyCode ) ||
2031              ( Dali::DALI_KEY_CURSOR_UP    == keyCode ) ||
2032              ( Dali::DALI_KEY_CURSOR_DOWN  == keyCode ) )
2033     {
2034       Event event( Event::CURSOR_KEY_EVENT );
2035       event.p1.mInt = keyCode;
2036       mImpl->mEventData->mEventQueue.push_back( event );
2037     }
2038     else if( Dali::DALI_KEY_BACKSPACE == keyCode )
2039     {
2040       textChanged = BackspaceKeyEvent();
2041     }
2042     else if( IsKey( keyEvent,  Dali::DALI_KEY_POWER ) )
2043     {
2044       mImpl->ChangeState( EventData::INTERRUPTED ); // State is not INACTIVE as expect to return to edit mode.
2045       // Avoids calling the InsertText() method which can delete selected text
2046     }
2047     else if( IsKey( keyEvent, Dali::DALI_KEY_MENU ) ||
2048              IsKey( keyEvent, Dali::DALI_KEY_HOME ) )
2049     {
2050       mImpl->ChangeState( EventData::INACTIVE );
2051       // Menu/Home key behaviour does not allow edit mode to resume like Power key
2052       // Avoids calling the InsertText() method which can delete selected text
2053     }
2054     else if( Dali::DALI_KEY_SHIFT_LEFT == keyCode )
2055     {
2056       // DALI_KEY_SHIFT_LEFT is the key code for the Left Shift. It's sent (by the imf?) when the predictive text is enabled
2057       // and a character is typed after the type of a upper case latin character.
2058
2059       // Do nothing.
2060     }
2061     else
2062     {
2063       DALI_LOG_INFO( gLogFilter, Debug::Verbose, "Controller::KeyEvent %p keyString %s\n", this, keyString.c_str() );
2064
2065       // IMF manager is no longer handling key-events
2066       mImpl->ClearPreEditFlag();
2067
2068       InsertText( keyString, COMMIT );
2069       textChanged = true;
2070     }
2071
2072     if ( ( mImpl->mEventData->mState != EventData::INTERRUPTED ) &&
2073          ( mImpl->mEventData->mState != EventData::INACTIVE ) &&
2074          ( Dali::DALI_KEY_SHIFT_LEFT != keyCode ) )
2075     {
2076       // Should not change the state if the key is the shift send by the imf manager.
2077       // Otherwise, when the state is SELECTING the text controller can't send the right
2078       // surrounding info to the imf.
2079       mImpl->ChangeState( EventData::EDITING );
2080     }
2081
2082     mImpl->RequestRelayout();
2083   }
2084
2085   if( textChanged )
2086   {
2087     // Do this last since it provides callbacks into application code
2088     mImpl->mControlInterface.TextChanged();
2089   }
2090
2091   return true;
2092 }
2093
2094 void Controller::InsertText( const std::string& text, Controller::InsertType type )
2095 {
2096   bool removedPrevious( false );
2097   bool maxLengthReached( false );
2098
2099   DALI_ASSERT_DEBUG( NULL != mImpl->mEventData && "Unexpected InsertText" )
2100
2101   if( NULL == mImpl->mEventData )
2102   {
2103     return;
2104   }
2105
2106   DALI_LOG_INFO( gLogFilter, Debug::Verbose, "Controller::InsertText %p %s (%s) mPrimaryCursorPosition %d mPreEditFlag %d mPreEditStartPosition %d mPreEditLength %d\n",
2107                  this, text.c_str(), (COMMIT == type ? "COMMIT" : "PRE_EDIT"),
2108                  mImpl->mEventData->mPrimaryCursorPosition, mImpl->mEventData->mPreEditFlag, mImpl->mEventData->mPreEditStartPosition, mImpl->mEventData->mPreEditLength );
2109
2110   // TODO: At the moment the underline runs are only for pre-edit.
2111   mImpl->mVisualModel->mUnderlineRuns.Clear();
2112
2113   // Keep the current number of characters.
2114   const Length currentNumberOfCharacters = mImpl->IsShowingRealText() ? mImpl->mLogicalModel->mText.Count() : 0u;
2115
2116   // Remove the previous IMF pre-edit.
2117   if( mImpl->mEventData->mPreEditFlag && ( 0u != mImpl->mEventData->mPreEditLength ) )
2118   {
2119     removedPrevious = RemoveText( -static_cast<int>( mImpl->mEventData->mPrimaryCursorPosition - mImpl->mEventData->mPreEditStartPosition ),
2120                                   mImpl->mEventData->mPreEditLength,
2121                                   DONT_UPDATE_INPUT_STYLE );
2122
2123     mImpl->mEventData->mPrimaryCursorPosition = mImpl->mEventData->mPreEditStartPosition;
2124     mImpl->mEventData->mPreEditLength = 0u;
2125   }
2126   else
2127   {
2128     // Remove the previous Selection.
2129     removedPrevious = RemoveSelectedText();
2130   }
2131
2132   Vector<Character> utf32Characters;
2133   Length characterCount = 0u;
2134
2135   if( !text.empty() )
2136   {
2137     //  Convert text into UTF-32
2138     utf32Characters.Resize( text.size() );
2139
2140     // This is a bit horrible but std::string returns a (signed) char*
2141     const uint8_t* utf8 = reinterpret_cast<const uint8_t*>( text.c_str() );
2142
2143     // Transform a text array encoded in utf8 into an array encoded in utf32.
2144     // It returns the actual number of characters.
2145     characterCount = Utf8ToUtf32( utf8, text.size(), utf32Characters.Begin() );
2146     utf32Characters.Resize( characterCount );
2147
2148     DALI_ASSERT_DEBUG( text.size() >= utf32Characters.Count() && "Invalid UTF32 conversion length" );
2149     DALI_LOG_INFO( gLogFilter, Debug::Verbose, "UTF8 size %d, UTF32 size %d\n", text.size(), utf32Characters.Count() );
2150   }
2151
2152   if( 0u != utf32Characters.Count() ) // Check if Utf8ToUtf32 conversion succeeded
2153   {
2154     // The placeholder text is no longer needed
2155     if( mImpl->IsShowingPlaceholderText() )
2156     {
2157       ResetText();
2158     }
2159
2160     mImpl->ChangeState( EventData::EDITING );
2161
2162     // Handle the IMF (predicitive text) state changes
2163     if( COMMIT == type )
2164     {
2165       // IMF manager is no longer handling key-events
2166       mImpl->ClearPreEditFlag();
2167     }
2168     else // PRE_EDIT
2169     {
2170       if( !mImpl->mEventData->mPreEditFlag )
2171       {
2172         DALI_LOG_INFO( gLogFilter, Debug::Verbose, "Entered PreEdit state" );
2173
2174         // Record the start of the pre-edit text
2175         mImpl->mEventData->mPreEditStartPosition = mImpl->mEventData->mPrimaryCursorPosition;
2176       }
2177
2178       mImpl->mEventData->mPreEditLength = utf32Characters.Count();
2179       mImpl->mEventData->mPreEditFlag = true;
2180
2181       DALI_LOG_INFO( gLogFilter, Debug::Verbose, "mPreEditStartPosition %d mPreEditLength %d\n", mImpl->mEventData->mPreEditStartPosition, mImpl->mEventData->mPreEditLength );
2182     }
2183
2184     const Length numberOfCharactersInModel = mImpl->mLogicalModel->mText.Count();
2185
2186     // Restrict new text to fit within Maximum characters setting.
2187     Length maxSizeOfNewText = std::min( ( mImpl->mMaximumNumberOfCharacters - numberOfCharactersInModel ), characterCount );
2188     maxLengthReached = ( characterCount > maxSizeOfNewText );
2189
2190     // The cursor position.
2191     CharacterIndex& cursorIndex = mImpl->mEventData->mPrimaryCursorPosition;
2192
2193     // Update the text's style.
2194
2195     // Updates the text style runs by adding characters.
2196     mImpl->mLogicalModel->UpdateTextStyleRuns( cursorIndex, maxSizeOfNewText );
2197
2198     // Get the character index from the cursor index.
2199     const CharacterIndex styleIndex = ( cursorIndex > 0u ) ? cursorIndex - 1u : 0u;
2200
2201     // Retrieve the text's style for the given index.
2202     InputStyle style;
2203     mImpl->RetrieveDefaultInputStyle( style );
2204     mImpl->mLogicalModel->RetrieveStyle( styleIndex, style );
2205
2206     // Whether to add a new text color run.
2207     const bool addColorRun = ( style.textColor != mImpl->mEventData->mInputStyle.textColor );
2208
2209     // Whether to add a new font run.
2210     const bool addFontNameRun = style.familyName != mImpl->mEventData->mInputStyle.familyName;
2211     const bool addFontWeightRun = style.weight != mImpl->mEventData->mInputStyle.weight;
2212     const bool addFontWidthRun = style.width != mImpl->mEventData->mInputStyle.width;
2213     const bool addFontSlantRun = style.slant != mImpl->mEventData->mInputStyle.slant;
2214     const bool addFontSizeRun = style.size != mImpl->mEventData->mInputStyle.size;
2215
2216     // Add style runs.
2217     if( addColorRun )
2218     {
2219       const VectorBase::SizeType numberOfRuns = mImpl->mLogicalModel->mColorRuns.Count();
2220       mImpl->mLogicalModel->mColorRuns.Resize( numberOfRuns + 1u );
2221
2222       ColorRun& colorRun = *( mImpl->mLogicalModel->mColorRuns.Begin() + numberOfRuns );
2223       colorRun.color = mImpl->mEventData->mInputStyle.textColor;
2224       colorRun.characterRun.characterIndex = cursorIndex;
2225       colorRun.characterRun.numberOfCharacters = maxSizeOfNewText;
2226     }
2227
2228     if( addFontNameRun   ||
2229         addFontWeightRun ||
2230         addFontWidthRun  ||
2231         addFontSlantRun  ||
2232         addFontSizeRun )
2233     {
2234       const VectorBase::SizeType numberOfRuns = mImpl->mLogicalModel->mFontDescriptionRuns.Count();
2235       mImpl->mLogicalModel->mFontDescriptionRuns.Resize( numberOfRuns + 1u );
2236
2237       FontDescriptionRun& fontDescriptionRun = *( mImpl->mLogicalModel->mFontDescriptionRuns.Begin() + numberOfRuns );
2238
2239       if( addFontNameRun )
2240       {
2241         fontDescriptionRun.familyLength = mImpl->mEventData->mInputStyle.familyName.size();
2242         fontDescriptionRun.familyName = new char[fontDescriptionRun.familyLength];
2243         memcpy( fontDescriptionRun.familyName, mImpl->mEventData->mInputStyle.familyName.c_str(), fontDescriptionRun.familyLength );
2244         fontDescriptionRun.familyDefined = true;
2245
2246         // The memory allocated for the font family name is freed when the font description is removed from the logical model.
2247       }
2248
2249       if( addFontWeightRun )
2250       {
2251         fontDescriptionRun.weight = mImpl->mEventData->mInputStyle.weight;
2252         fontDescriptionRun.weightDefined = true;
2253       }
2254
2255       if( addFontWidthRun )
2256       {
2257         fontDescriptionRun.width = mImpl->mEventData->mInputStyle.width;
2258         fontDescriptionRun.widthDefined = true;
2259       }
2260
2261       if( addFontSlantRun )
2262       {
2263         fontDescriptionRun.slant = mImpl->mEventData->mInputStyle.slant;
2264         fontDescriptionRun.slantDefined = true;
2265       }
2266
2267       if( addFontSizeRun )
2268       {
2269         fontDescriptionRun.size = static_cast<PointSize26Dot6>( mImpl->mEventData->mInputStyle.size * 64.f );
2270         fontDescriptionRun.sizeDefined = true;
2271       }
2272
2273       fontDescriptionRun.characterRun.characterIndex = cursorIndex;
2274       fontDescriptionRun.characterRun.numberOfCharacters = maxSizeOfNewText;
2275     }
2276
2277     // Insert at current cursor position.
2278     Vector<Character>& modifyText = mImpl->mLogicalModel->mText;
2279
2280     if( cursorIndex < numberOfCharactersInModel )
2281     {
2282       modifyText.Insert( modifyText.Begin() + cursorIndex, utf32Characters.Begin(), utf32Characters.Begin() + maxSizeOfNewText );
2283     }
2284     else
2285     {
2286       modifyText.Insert( modifyText.End(), utf32Characters.Begin(), utf32Characters.Begin() + maxSizeOfNewText );
2287     }
2288
2289     // Mark the first paragraph to be updated.
2290     mImpl->mTextUpdateInfo.mCharacterIndex = std::min( cursorIndex, mImpl->mTextUpdateInfo.mCharacterIndex );
2291     mImpl->mTextUpdateInfo.mNumberOfCharactersToAdd += maxSizeOfNewText;
2292
2293     // Update the cursor index.
2294     cursorIndex += maxSizeOfNewText;
2295
2296     DALI_LOG_INFO( gLogFilter, Debug::Verbose, "Inserted %d characters, new size %d new cursor %d\n", maxSizeOfNewText, mImpl->mLogicalModel->mText.Count(), mImpl->mEventData->mPrimaryCursorPosition );
2297   }
2298
2299   const Length numberOfCharacters = mImpl->IsShowingRealText() ? mImpl->mLogicalModel->mText.Count() : 0u;
2300
2301   if( ( 0u == mImpl->mLogicalModel->mText.Count() ) &&
2302       mImpl->IsPlaceholderAvailable() )
2303   {
2304     // Show place-holder if empty after removing the pre-edit text
2305     ShowPlaceholderText();
2306     mImpl->mEventData->mUpdateCursorPosition = true;
2307     mImpl->ClearPreEditFlag();
2308   }
2309   else if( removedPrevious ||
2310            ( 0 != utf32Characters.Count() ) )
2311   {
2312     // Queue an inserted event
2313     mImpl->QueueModifyEvent( ModifyEvent::TEXT_INSERTED );
2314
2315     mImpl->mEventData->mUpdateCursorPosition = true;
2316     if( numberOfCharacters < currentNumberOfCharacters )
2317     {
2318       mImpl->mEventData->mScrollAfterDelete = true;
2319     }
2320     else
2321     {
2322       mImpl->mEventData->mScrollAfterUpdatePosition = true;
2323     }
2324   }
2325
2326   if( maxLengthReached )
2327   {
2328     DALI_LOG_INFO( gLogFilter, Debug::Verbose, "MaxLengthReached (%d)\n", mImpl->mLogicalModel->mText.Count() );
2329
2330     mImpl->ResetImfManager();
2331
2332     // Do this last since it provides callbacks into application code
2333     mImpl->mControlInterface.MaxLengthReached();
2334   }
2335 }
2336
2337 bool Controller::RemoveSelectedText()
2338 {
2339   bool textRemoved( false );
2340
2341   if( EventData::SELECTING == mImpl->mEventData->mState )
2342   {
2343     std::string removedString;
2344     mImpl->RetrieveSelection( removedString, true );
2345
2346     if( !removedString.empty() )
2347     {
2348       textRemoved = true;
2349       mImpl->ChangeState( EventData::EDITING );
2350     }
2351   }
2352
2353   return textRemoved;
2354 }
2355
2356 void Controller::TapEvent( unsigned int tapCount, float x, float y )
2357 {
2358   DALI_ASSERT_DEBUG( mImpl->mEventData && "Unexpected TapEvent" );
2359
2360   if( NULL != mImpl->mEventData )
2361   {
2362     DALI_LOG_INFO( gLogFilter, Debug::Concise, "TapEvent state:%d \n", mImpl->mEventData->mState );
2363
2364     if( 1u == tapCount )
2365     {
2366       // This is to avoid unnecessary relayouts when tapping an empty text-field
2367       bool relayoutNeeded( false );
2368
2369       if( ( EventData::EDITING_WITH_POPUP == mImpl->mEventData->mState ) ||
2370           ( EventData::EDITING_WITH_PASTE_POPUP == mImpl->mEventData->mState ) )
2371       {
2372         mImpl->ChangeState( EventData::EDITING_WITH_GRAB_HANDLE );  // If Popup shown hide it here so can be shown again if required.
2373       }
2374
2375       if( mImpl->IsShowingRealText() && ( EventData::INACTIVE != mImpl->mEventData->mState ) )
2376       {
2377         // Already in an active state so show a popup
2378         if( !mImpl->IsClipboardEmpty() )
2379         {
2380           // Shows Paste popup but could show full popup with Selection options. ( EDITING_WITH_POPUP )
2381           mImpl->ChangeState( EventData::EDITING_WITH_PASTE_POPUP );
2382         }
2383         else
2384         {
2385           // Show cursor and grabhandle on first tap, this matches the behaviour of tapping when already editing
2386           mImpl->ChangeState( EventData::EDITING_WITH_GRAB_HANDLE );
2387         }
2388         relayoutNeeded = true;
2389       }
2390       else
2391       {
2392         if( mImpl->IsShowingPlaceholderText() && !mImpl->IsFocusedPlaceholderAvailable() )
2393         {
2394           // Hide placeholder text
2395           ResetText();
2396         }
2397
2398         if( EventData::INACTIVE == mImpl->mEventData->mState )
2399         {
2400           mImpl->ChangeState( EventData::EDITING );
2401         }
2402         else if( !mImpl->IsClipboardEmpty() )
2403         {
2404           mImpl->ChangeState( EventData::EDITING_WITH_POPUP );
2405         }
2406         relayoutNeeded = true;
2407       }
2408
2409       // Handles & cursors must be repositioned after Relayout() i.e. after the Model has been updated
2410       if( relayoutNeeded )
2411       {
2412         Event event( Event::TAP_EVENT );
2413         event.p1.mUint = tapCount;
2414         event.p2.mFloat = x;
2415         event.p3.mFloat = y;
2416         mImpl->mEventData->mEventQueue.push_back( event );
2417
2418         mImpl->RequestRelayout();
2419       }
2420     }
2421     else if( 2u == tapCount )
2422     {
2423       if( mImpl->mEventData->mSelectionEnabled &&
2424           mImpl->IsShowingRealText() )
2425       {
2426         SelectEvent( x, y, false );
2427       }
2428     }
2429   }
2430
2431   // Reset keyboard as tap event has occurred.
2432   mImpl->ResetImfManager();
2433 }
2434
2435 void Controller::PanEvent( Gesture::State state, const Vector2& displacement )
2436 {
2437   DALI_ASSERT_DEBUG( mImpl->mEventData && "Unexpected PanEvent" );
2438
2439   if( NULL != mImpl->mEventData )
2440   {
2441     Event event( Event::PAN_EVENT );
2442     event.p1.mInt = state;
2443     event.p2.mFloat = displacement.x;
2444     event.p3.mFloat = displacement.y;
2445     mImpl->mEventData->mEventQueue.push_back( event );
2446
2447     mImpl->RequestRelayout();
2448   }
2449 }
2450
2451 void Controller::LongPressEvent( Gesture::State state, float x, float y  )
2452 {
2453   DALI_ASSERT_DEBUG( mImpl->mEventData && "Unexpected LongPressEvent" );
2454
2455   if( ( state == Gesture::Started ) &&
2456       ( NULL != mImpl->mEventData ) )
2457   {
2458     if( !mImpl->IsShowingRealText() )
2459     {
2460       Event event( Event::LONG_PRESS_EVENT );
2461       event.p1.mInt = state;
2462       mImpl->mEventData->mEventQueue.push_back( event );
2463       mImpl->RequestRelayout();
2464     }
2465     else
2466     {
2467       // The 1st long-press on inactive text-field is treated as tap
2468       if( EventData::INACTIVE == mImpl->mEventData->mState )
2469       {
2470         mImpl->ChangeState( EventData::EDITING );
2471
2472         Event event( Event::TAP_EVENT );
2473         event.p1.mUint = 1;
2474         event.p2.mFloat = x;
2475         event.p3.mFloat = y;
2476         mImpl->mEventData->mEventQueue.push_back( event );
2477
2478         mImpl->RequestRelayout();
2479       }
2480       else
2481       {
2482         // Reset the imf manger to commit the pre-edit before selecting the text.
2483         mImpl->ResetImfManager();
2484
2485         SelectEvent( x, y, false );
2486       }
2487     }
2488   }
2489 }
2490
2491 void Controller::SelectEvent( float x, float y, bool selectAll )
2492 {
2493   DALI_LOG_INFO( gLogFilter, Debug::Verbose, "Controller::SelectEvent\n" );
2494
2495   if( NULL != mImpl->mEventData )
2496   {
2497     mImpl->ChangeState( EventData::SELECTING );
2498
2499     if( selectAll )
2500     {
2501       Event event( Event::SELECT_ALL );
2502       mImpl->mEventData->mEventQueue.push_back( event );
2503     }
2504     else
2505     {
2506       Event event( Event::SELECT );
2507       event.p2.mFloat = x;
2508       event.p3.mFloat = y;
2509       mImpl->mEventData->mEventQueue.push_back( event );
2510     }
2511
2512     mImpl->RequestRelayout();
2513   }
2514 }
2515
2516 void Controller::GetTargetSize( Vector2& targetSize )
2517 {
2518   targetSize = mImpl->mVisualModel->mControlSize;
2519 }
2520
2521 void Controller::AddDecoration( Actor& actor, bool needsClipping )
2522 {
2523   mImpl->mControlInterface.AddDecoration( actor, needsClipping );
2524 }
2525
2526 void Controller::DecorationEvent( HandleType handleType, HandleState state, float x, float y )
2527 {
2528   DALI_ASSERT_DEBUG( mImpl->mEventData && "Unexpected DecorationEvent" );
2529
2530   if( NULL != mImpl->mEventData )
2531   {
2532     switch( handleType )
2533     {
2534       case GRAB_HANDLE:
2535       {
2536         Event event( Event::GRAB_HANDLE_EVENT );
2537         event.p1.mUint  = state;
2538         event.p2.mFloat = x;
2539         event.p3.mFloat = y;
2540
2541         mImpl->mEventData->mEventQueue.push_back( event );
2542         break;
2543       }
2544       case LEFT_SELECTION_HANDLE:
2545       {
2546         Event event( Event::LEFT_SELECTION_HANDLE_EVENT );
2547         event.p1.mUint  = state;
2548         event.p2.mFloat = x;
2549         event.p3.mFloat = y;
2550
2551         mImpl->mEventData->mEventQueue.push_back( event );
2552         break;
2553       }
2554       case RIGHT_SELECTION_HANDLE:
2555       {
2556         Event event( Event::RIGHT_SELECTION_HANDLE_EVENT );
2557         event.p1.mUint  = state;
2558         event.p2.mFloat = x;
2559         event.p3.mFloat = y;
2560
2561         mImpl->mEventData->mEventQueue.push_back( event );
2562         break;
2563       }
2564       case LEFT_SELECTION_HANDLE_MARKER:
2565       case RIGHT_SELECTION_HANDLE_MARKER:
2566       {
2567         // Markers do not move the handles.
2568         break;
2569       }
2570       case HANDLE_TYPE_COUNT:
2571       {
2572         DALI_ASSERT_DEBUG( !"Controller::HandleEvent. Unexpected handle type" );
2573       }
2574     }
2575
2576     mImpl->RequestRelayout();
2577   }
2578 }
2579
2580 void Controller::PasteText( const std::string& stringToPaste )
2581 {
2582   InsertText( stringToPaste, Text::Controller::COMMIT );
2583   mImpl->ChangeState( EventData::EDITING );
2584   mImpl->RequestRelayout();
2585
2586   // Do this last since it provides callbacks into application code
2587   mImpl->mControlInterface.TextChanged();
2588 }
2589
2590 void Controller::PasteClipboardItemEvent()
2591 {
2592   // Retrieve the clipboard contents first
2593   ClipboardEventNotifier notifier( ClipboardEventNotifier::Get() );
2594   std::string stringToPaste( notifier.GetContent() );
2595
2596   // Commit the current pre-edit text; the contents of the clipboard should be appended
2597   mImpl->ResetImfManager();
2598
2599   // Temporary disable hiding clipboard
2600   mImpl->SetClipboardHideEnable( false );
2601
2602   // Paste
2603   PasteText( stringToPaste );
2604
2605   mImpl->SetClipboardHideEnable( true );
2606 }
2607
2608 void Controller::TextPopupButtonTouched( Dali::Toolkit::TextSelectionPopup::Buttons button )
2609 {
2610   if( NULL == mImpl->mEventData )
2611   {
2612     return;
2613   }
2614
2615   switch( button )
2616   {
2617     case Toolkit::TextSelectionPopup::CUT:
2618     {
2619       mImpl->SendSelectionToClipboard( true ); // Synchronous call to modify text
2620       mImpl->mOperationsPending = ALL_OPERATIONS;
2621
2622       if( ( 0u != mImpl->mLogicalModel->mText.Count() ) ||
2623           !mImpl->IsPlaceholderAvailable() )
2624       {
2625         mImpl->QueueModifyEvent( ModifyEvent::TEXT_DELETED );
2626       }
2627       else
2628       {
2629         ShowPlaceholderText();
2630       }
2631
2632       mImpl->mEventData->mUpdateCursorPosition = true;
2633       mImpl->mEventData->mScrollAfterDelete = true;
2634
2635       mImpl->RequestRelayout();
2636       mImpl->mControlInterface.TextChanged();
2637       break;
2638     }
2639     case Toolkit::TextSelectionPopup::COPY:
2640     {
2641       mImpl->SendSelectionToClipboard( false ); // Text not modified
2642
2643       mImpl->mEventData->mUpdateCursorPosition = true;
2644
2645       mImpl->RequestRelayout(); // Cursor, Handles, Selection Highlight, Popup
2646       break;
2647     }
2648     case Toolkit::TextSelectionPopup::PASTE:
2649     {
2650       std::string stringToPaste("");
2651       mImpl->GetTextFromClipboard( 0, stringToPaste ); // Paste latest item from system clipboard
2652       PasteText( stringToPaste );
2653       break;
2654     }
2655     case Toolkit::TextSelectionPopup::SELECT:
2656     {
2657       const Vector2& currentCursorPosition = mImpl->mEventData->mDecorator->GetPosition( PRIMARY_CURSOR );
2658
2659       if( mImpl->mEventData->mSelectionEnabled )
2660       {
2661         // Creates a SELECT event.
2662         SelectEvent( currentCursorPosition.x, currentCursorPosition.y, false );
2663       }
2664       break;
2665     }
2666     case Toolkit::TextSelectionPopup::SELECT_ALL:
2667     {
2668       // Creates a SELECT_ALL event
2669       SelectEvent( 0.f, 0.f, true );
2670       break;
2671     }
2672     case Toolkit::TextSelectionPopup::CLIPBOARD:
2673     {
2674       mImpl->ShowClipboard();
2675       break;
2676     }
2677     case Toolkit::TextSelectionPopup::NONE:
2678     {
2679       // Nothing to do.
2680       break;
2681     }
2682   }
2683 }
2684
2685 ImfManager::ImfCallbackData Controller::OnImfEvent( ImfManager& imfManager, const ImfManager::ImfEventData& imfEvent )
2686 {
2687   // Whether the text needs to be relaid-out.
2688   bool requestRelayout = false;
2689
2690   // Whether to retrieve the text and cursor position to be sent to the IMF manager.
2691   bool retrieveText = false;
2692   bool retrieveCursor = false;
2693
2694   switch( imfEvent.eventName )
2695   {
2696     case ImfManager::COMMIT:
2697     {
2698       InsertText( imfEvent.predictiveString, Text::Controller::COMMIT );
2699       requestRelayout = true;
2700       retrieveCursor = true;
2701       break;
2702     }
2703     case ImfManager::PREEDIT:
2704     {
2705       InsertText( imfEvent.predictiveString, Text::Controller::PRE_EDIT );
2706       requestRelayout = true;
2707       retrieveCursor = true;
2708       break;
2709     }
2710     case ImfManager::DELETESURROUNDING:
2711     {
2712       const bool textDeleted = RemoveText( imfEvent.cursorOffset,
2713                                            imfEvent.numberOfChars,
2714                                            DONT_UPDATE_INPUT_STYLE );
2715
2716       if( textDeleted )
2717       {
2718         if( ( 0u != mImpl->mLogicalModel->mText.Count() ) ||
2719             !mImpl->IsPlaceholderAvailable() )
2720         {
2721           mImpl->QueueModifyEvent( ModifyEvent::TEXT_DELETED );
2722         }
2723         else
2724         {
2725           ShowPlaceholderText();
2726         }
2727         mImpl->mEventData->mUpdateCursorPosition = true;
2728         mImpl->mEventData->mScrollAfterDelete = true;
2729
2730         requestRelayout = true;
2731       }
2732       break;
2733     }
2734     case ImfManager::GETSURROUNDING:
2735     {
2736       retrieveText = true;
2737       retrieveCursor = true;
2738       break;
2739     }
2740     case ImfManager::VOID:
2741     {
2742       // do nothing
2743       break;
2744     }
2745   } // end switch
2746
2747   if( requestRelayout )
2748   {
2749     mImpl->mOperationsPending = ALL_OPERATIONS;
2750     mImpl->RequestRelayout();
2751
2752     // Do this last since it provides callbacks into application code
2753     mImpl->mControlInterface.TextChanged();
2754   }
2755
2756   std::string text;
2757   CharacterIndex cursorPosition = 0u;
2758   Length numberOfWhiteSpaces = 0u;
2759
2760   if( retrieveCursor )
2761   {
2762     numberOfWhiteSpaces = mImpl->GetNumberOfWhiteSpaces( 0u );
2763
2764     cursorPosition = mImpl->GetLogicalCursorPosition();
2765
2766     if( cursorPosition < numberOfWhiteSpaces )
2767     {
2768       cursorPosition = 0u;
2769     }
2770     else
2771     {
2772       cursorPosition -= numberOfWhiteSpaces;
2773     }
2774   }
2775
2776   if( retrieveText )
2777   {
2778     mImpl->GetText( numberOfWhiteSpaces, text );
2779   }
2780
2781   ImfManager::ImfCallbackData callbackData( ( retrieveText || retrieveCursor ), cursorPosition, text, false );
2782
2783   return callbackData;
2784 }
2785
2786 Controller::~Controller()
2787 {
2788   delete mImpl;
2789 }
2790
2791 bool Controller::BackspaceKeyEvent()
2792 {
2793   DALI_LOG_INFO( gLogFilter, Debug::Verbose, "Controller::KeyEvent %p DALI_KEY_BACKSPACE\n", this );
2794
2795   bool removed = false;
2796
2797   if( NULL == mImpl->mEventData )
2798   {
2799     return removed;
2800   }
2801
2802   // IMF manager is no longer handling key-events
2803   mImpl->ClearPreEditFlag();
2804
2805   if( EventData::SELECTING == mImpl->mEventData->mState )
2806   {
2807     removed = RemoveSelectedText();
2808   }
2809   else if( mImpl->mEventData->mPrimaryCursorPosition > 0 )
2810   {
2811     // Remove the character before the current cursor position
2812     removed = RemoveText( -1,
2813                           1,
2814                           UPDATE_INPUT_STYLE );
2815   }
2816
2817   if( removed )
2818   {
2819     if( ( 0u != mImpl->mLogicalModel->mText.Count() ) ||
2820         !mImpl->IsPlaceholderAvailable() )
2821     {
2822       mImpl->QueueModifyEvent( ModifyEvent::TEXT_DELETED );
2823     }
2824     else
2825     {
2826       ShowPlaceholderText();
2827     }
2828     mImpl->mEventData->mUpdateCursorPosition = true;
2829     mImpl->mEventData->mScrollAfterDelete = true;
2830   }
2831
2832   return removed;
2833 }
2834
2835 void Controller::ShowPlaceholderText()
2836 {
2837   if( mImpl->IsPlaceholderAvailable() )
2838   {
2839     DALI_ASSERT_DEBUG( mImpl->mEventData && "No placeholder text available" );
2840
2841     if( NULL == mImpl->mEventData )
2842     {
2843       return;
2844     }
2845
2846     mImpl->mEventData->mIsShowingPlaceholderText = true;
2847
2848     // Disable handles when showing place-holder text
2849     mImpl->mEventData->mDecorator->SetHandleActive( GRAB_HANDLE, false );
2850     mImpl->mEventData->mDecorator->SetHandleActive( LEFT_SELECTION_HANDLE, false );
2851     mImpl->mEventData->mDecorator->SetHandleActive( RIGHT_SELECTION_HANDLE, false );
2852
2853     const char* text( NULL );
2854     size_t size( 0 );
2855
2856     // TODO - Switch placeholder text styles when changing state
2857     if( ( EventData::INACTIVE != mImpl->mEventData->mState ) &&
2858         ( 0u != mImpl->mEventData->mPlaceholderTextActive.c_str() ) )
2859     {
2860       text = mImpl->mEventData->mPlaceholderTextActive.c_str();
2861       size = mImpl->mEventData->mPlaceholderTextActive.size();
2862     }
2863     else
2864     {
2865       text = mImpl->mEventData->mPlaceholderTextInactive.c_str();
2866       size = mImpl->mEventData->mPlaceholderTextInactive.size();
2867     }
2868
2869     mImpl->mTextUpdateInfo.mCharacterIndex = 0u;
2870     mImpl->mTextUpdateInfo.mNumberOfCharactersToRemove = mImpl->mTextUpdateInfo.mPreviousNumberOfCharacters;
2871
2872     // Reset model for showing placeholder.
2873     mImpl->mLogicalModel->mText.Clear();
2874     mImpl->mVisualModel->SetTextColor( mImpl->mEventData->mPlaceholderTextColor );
2875
2876     // Convert text into UTF-32
2877     Vector<Character>& utf32Characters = mImpl->mLogicalModel->mText;
2878     utf32Characters.Resize( size );
2879
2880     // This is a bit horrible but std::string returns a (signed) char*
2881     const uint8_t* utf8 = reinterpret_cast<const uint8_t*>( text );
2882
2883     // Transform a text array encoded in utf8 into an array encoded in utf32.
2884     // It returns the actual number of characters.
2885     const Length characterCount = Utf8ToUtf32( utf8, size, utf32Characters.Begin() );
2886     utf32Characters.Resize( characterCount );
2887
2888     // The characters to be added.
2889     mImpl->mTextUpdateInfo.mNumberOfCharactersToAdd = characterCount;
2890
2891     // Reset the cursor position
2892     mImpl->mEventData->mPrimaryCursorPosition = 0;
2893
2894     // The natural size needs to be re-calculated.
2895     mImpl->mRecalculateNaturalSize = true;
2896
2897     // Apply modifications to the model
2898     mImpl->mOperationsPending = ALL_OPERATIONS;
2899
2900     // Update the rest of the model during size negotiation
2901     mImpl->QueueModifyEvent( ModifyEvent::TEXT_REPLACED );
2902   }
2903 }
2904
2905 void Controller::ClearFontData()
2906 {
2907   if( mImpl->mFontDefaults )
2908   {
2909     mImpl->mFontDefaults->mFontId = 0u; // Remove old font ID
2910   }
2911
2912   // Set flags to update the model.
2913   mImpl->mTextUpdateInfo.mCharacterIndex = 0u;
2914   mImpl->mTextUpdateInfo.mNumberOfCharactersToRemove = mImpl->mTextUpdateInfo.mPreviousNumberOfCharacters;
2915   mImpl->mTextUpdateInfo.mNumberOfCharactersToAdd = mImpl->mLogicalModel->mText.Count();
2916
2917   mImpl->mTextUpdateInfo.mClearAll = true;
2918   mImpl->mTextUpdateInfo.mFullRelayoutNeeded = true;
2919   mImpl->mRecalculateNaturalSize = true;
2920
2921   mImpl->mOperationsPending = static_cast<OperationsMask>( mImpl->mOperationsPending |
2922                                                            VALIDATE_FONTS            |
2923                                                            SHAPE_TEXT                |
2924                                                            GET_GLYPH_METRICS         |
2925                                                            LAYOUT                    |
2926                                                            UPDATE_ACTUAL_SIZE        |
2927                                                            REORDER                   |
2928                                                            ALIGN );
2929 }
2930
2931 void Controller::ClearStyleData()
2932 {
2933   mImpl->mLogicalModel->mColorRuns.Clear();
2934   mImpl->mLogicalModel->ClearFontDescriptionRuns();
2935 }
2936
2937 Controller::Controller( ControlInterface& controlInterface )
2938 : mImpl( NULL )
2939 {
2940   mImpl = new Controller::Impl( controlInterface );
2941 }
2942
2943 } // namespace Text
2944
2945 } // namespace Toolkit
2946
2947 } // namespace Dali