Merge "Fix for the cursor position with the arabic script." into devel/master
[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_LAYOUT_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_LAYOUT_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_LAYOUT_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_LAYOUT_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_LAYOUT_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_LAYOUT_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_LAYOUT_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_LAYOUT_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   // Get the current layout size.
1709   layoutSize = mImpl->mVisualModel->GetLayoutSize();
1710
1711   if( NO_OPERATION != ( LAYOUT & operations ) )
1712   {
1713     DALI_LOG_INFO( gLogFilter, Debug::Verbose, "-->Controller::DoRelayout LAYOUT & operations\n");
1714
1715     // Some vectors with data needed to layout and reorder may be void
1716     // after the first time the text has been laid out.
1717     // Fill the vectors again.
1718
1719     // Calculate the number of glyphs to layout.
1720     const Vector<GlyphIndex>& charactersToGlyph = mImpl->mVisualModel->mCharactersToGlyph;
1721     const Vector<Length>& glyphsPerCharacter = mImpl->mVisualModel->mGlyphsPerCharacter;
1722     const GlyphIndex* const charactersToGlyphBuffer = charactersToGlyph.Begin();
1723     const Length* const glyphsPerCharacterBuffer = glyphsPerCharacter.Begin();
1724
1725     const CharacterIndex lastIndex = startIndex + ( ( requestedNumberOfCharacters > 0u ) ? requestedNumberOfCharacters - 1u : 0u );
1726     const GlyphIndex startGlyphIndex = mImpl->mTextUpdateInfo.mStartGlyphIndex;
1727     const Length numberOfGlyphs = ( requestedNumberOfCharacters > 0u ) ? *( charactersToGlyphBuffer + lastIndex ) + *( glyphsPerCharacterBuffer + lastIndex ) - startGlyphIndex : 0u;
1728     const Length totalNumberOfGlyphs = mImpl->mVisualModel->mGlyphs.Count();
1729
1730     if( 0u == totalNumberOfGlyphs )
1731     {
1732       if( NO_OPERATION != ( UPDATE_LAYOUT_SIZE & operations ) )
1733       {
1734         mImpl->mVisualModel->SetLayoutSize( Size::ZERO );
1735       }
1736
1737       // Nothing else to do if there is no glyphs.
1738       DALI_LOG_INFO( gLogFilter, Debug::Verbose, "<--Controller::DoRelayout no glyphs, view updated true\n" );
1739       return true;
1740     }
1741
1742     const Vector<LineBreakInfo>& lineBreakInfo = mImpl->mLogicalModel->mLineBreakInfo;
1743     const Vector<WordBreakInfo>& wordBreakInfo = mImpl->mLogicalModel->mWordBreakInfo;
1744     const Vector<CharacterDirection>& characterDirection = mImpl->mLogicalModel->mCharacterDirections;
1745     const Vector<GlyphInfo>& glyphs = mImpl->mVisualModel->mGlyphs;
1746     const Vector<CharacterIndex>& glyphsToCharactersMap = mImpl->mVisualModel->mGlyphsToCharacters;
1747     const Vector<Length>& charactersPerGlyph = mImpl->mVisualModel->mCharactersPerGlyph;
1748     const Character* const textBuffer = mImpl->mLogicalModel->mText.Begin();
1749
1750     // Set the layout parameters.
1751     LayoutParameters layoutParameters( size,
1752                                        textBuffer,
1753                                        lineBreakInfo.Begin(),
1754                                        wordBreakInfo.Begin(),
1755                                        ( 0u != characterDirection.Count() ) ? characterDirection.Begin() : NULL,
1756                                        glyphs.Begin(),
1757                                        glyphsToCharactersMap.Begin(),
1758                                        charactersPerGlyph.Begin(),
1759                                        charactersToGlyphBuffer,
1760                                        glyphsPerCharacterBuffer,
1761                                        totalNumberOfGlyphs );
1762
1763     // Resize the vector of positions to have the same size than the vector of glyphs.
1764     Vector<Vector2>& glyphPositions = mImpl->mVisualModel->mGlyphPositions;
1765     glyphPositions.Resize( totalNumberOfGlyphs );
1766
1767     // Whether the last character is a new paragraph character.
1768     mImpl->mTextUpdateInfo.mIsLastCharacterNewParagraph =  TextAbstraction::IsNewParagraph( *( textBuffer + ( mImpl->mLogicalModel->mText.Count() - 1u ) ) );
1769     layoutParameters.isLastNewParagraph = mImpl->mTextUpdateInfo.mIsLastCharacterNewParagraph;
1770
1771     // The initial glyph and the number of glyphs to layout.
1772     layoutParameters.startGlyphIndex = startGlyphIndex;
1773     layoutParameters.numberOfGlyphs = numberOfGlyphs;
1774     layoutParameters.startLineIndex = mImpl->mTextUpdateInfo.mStartLineIndex;
1775     layoutParameters.estimatedNumberOfLines = mImpl->mTextUpdateInfo.mEstimatedNumberOfLines;
1776
1777     // Update the visual model.
1778     Size newLayoutSize;
1779     viewUpdated = mImpl->mLayoutEngine.LayoutText( layoutParameters,
1780                                                    glyphPositions,
1781                                                    mImpl->mVisualModel->mLines,
1782                                                    newLayoutSize );
1783
1784     viewUpdated = viewUpdated || ( newLayoutSize != layoutSize );
1785
1786     if( viewUpdated )
1787     {
1788       layoutSize = newLayoutSize;
1789
1790       if ( NO_OPERATION != ( UPDATE_DIRECTION & operations ) )
1791       {
1792         mImpl->mAutoScrollDirectionRTL = false;
1793       }
1794
1795       // Reorder the lines
1796       if( NO_OPERATION != ( REORDER & operations ) )
1797       {
1798         Vector<BidirectionalParagraphInfoRun>& bidirectionalInfo = mImpl->mLogicalModel->mBidirectionalParagraphInfo;
1799         Vector<BidirectionalLineInfoRun>& bidirectionalLineInfo = mImpl->mLogicalModel->mBidirectionalLineInfo;
1800
1801         // Check first if there are paragraphs with bidirectional info.
1802         if( 0u != bidirectionalInfo.Count() )
1803         {
1804           // Get the lines
1805           const Length numberOfLines = mImpl->mVisualModel->mLines.Count();
1806
1807           // Reorder the lines.
1808           bidirectionalLineInfo.Reserve( numberOfLines ); // Reserve because is not known yet how many lines have right to left characters.
1809           ReorderLines( bidirectionalInfo,
1810                         startIndex,
1811                         requestedNumberOfCharacters,
1812                         mImpl->mVisualModel->mLines,
1813                         bidirectionalLineInfo );
1814
1815           // Set the bidirectional info per line into the layout parameters.
1816           layoutParameters.lineBidirectionalInfoRunsBuffer = bidirectionalLineInfo.Begin();
1817           layoutParameters.numberOfBidirectionalInfoRuns = bidirectionalLineInfo.Count();
1818
1819           // Re-layout the text. Reorder those lines with right to left characters.
1820           mImpl->mLayoutEngine.ReLayoutRightToLeftLines( layoutParameters,
1821                                                          startIndex,
1822                                                          requestedNumberOfCharacters,
1823                                                          glyphPositions );
1824
1825           if ( ( NO_OPERATION != ( UPDATE_DIRECTION & operations ) ) && ( numberOfLines > 0 ) )
1826           {
1827             const LineRun* const firstline = mImpl->mVisualModel->mLines.Begin();
1828             if ( firstline )
1829             {
1830               mImpl->mAutoScrollDirectionRTL = firstline->direction;
1831             }
1832           }
1833         }
1834       } // REORDER
1835
1836       // Sets the layout size.
1837       if( NO_OPERATION != ( UPDATE_LAYOUT_SIZE & operations ) )
1838       {
1839         mImpl->mVisualModel->SetLayoutSize( layoutSize );
1840       }
1841     } // view updated
1842
1843     // Store the size used to layout the text.
1844     mImpl->mVisualModel->mControlSize = size;
1845   }
1846
1847   if( NO_OPERATION != ( ALIGN & operations ) )
1848   {
1849     // The laid-out lines.
1850     Vector<LineRun>& lines = mImpl->mVisualModel->mLines;
1851
1852     mImpl->mLayoutEngine.Align( size,
1853                                 startIndex,
1854                                 requestedNumberOfCharacters,
1855                                 lines );
1856
1857     viewUpdated = true;
1858   }
1859 #if defined(DEBUG_ENABLED)
1860   std::string currentText;
1861   GetText( currentText );
1862   DALI_LOG_INFO( gLogFilter, Debug::Concise, "Controller::DoRelayout [%p] mImpl->mAutoScrollDirectionRTL[%s] [%s]\n", this, (mImpl->mAutoScrollDirectionRTL)?"true":"false",  currentText.c_str() );
1863 #endif
1864   DALI_LOG_INFO( gLogFilter, Debug::Verbose, "<--Controller::DoRelayout, view updated %s\n", ( viewUpdated ? "true" : "false" ) );
1865   return viewUpdated;
1866 }
1867
1868 void Controller::SetMultiLineEnabled( bool enable )
1869 {
1870   const LayoutEngine::Layout layout = enable ? LayoutEngine::MULTI_LINE_BOX : LayoutEngine::SINGLE_LINE_BOX;
1871
1872   if( layout != mImpl->mLayoutEngine.GetLayout() )
1873   {
1874     // Set the layout type.
1875     mImpl->mLayoutEngine.SetLayout( layout );
1876
1877     // Set the flags to redo the layout operations
1878     const OperationsMask layoutOperations =  static_cast<OperationsMask>( LAYOUT             |
1879                                                                           UPDATE_LAYOUT_SIZE |
1880                                                                           ALIGN              |
1881                                                                           REORDER );
1882
1883     mImpl->mOperationsPending = static_cast<OperationsMask>( mImpl->mOperationsPending | layoutOperations );
1884
1885     mImpl->RequestRelayout();
1886   }
1887 }
1888
1889 bool Controller::IsMultiLineEnabled() const
1890 {
1891   return LayoutEngine::MULTI_LINE_BOX == mImpl->mLayoutEngine.GetLayout();
1892 }
1893
1894 void Controller::SetHorizontalAlignment( LayoutEngine::HorizontalAlignment alignment )
1895 {
1896   if( alignment != mImpl->mLayoutEngine.GetHorizontalAlignment() )
1897   {
1898     // Set the alignment.
1899     mImpl->mLayoutEngine.SetHorizontalAlignment( alignment );
1900
1901     // Set the flag to redo the alignment operation.
1902     mImpl->mOperationsPending = static_cast<OperationsMask>( mImpl->mOperationsPending | ALIGN );
1903
1904     mImpl->RequestRelayout();
1905   }
1906 }
1907
1908 LayoutEngine::HorizontalAlignment Controller::GetHorizontalAlignment() const
1909 {
1910   return mImpl->mLayoutEngine.GetHorizontalAlignment();
1911 }
1912
1913 void Controller::SetVerticalAlignment( LayoutEngine::VerticalAlignment alignment )
1914 {
1915   if( alignment != mImpl->mLayoutEngine.GetVerticalAlignment() )
1916   {
1917     // Set the alignment.
1918     mImpl->mLayoutEngine.SetVerticalAlignment( alignment );
1919
1920     mImpl->mOperationsPending = static_cast<OperationsMask>( mImpl->mOperationsPending | ALIGN );
1921
1922     mImpl->RequestRelayout();
1923   }
1924 }
1925
1926 LayoutEngine::VerticalAlignment Controller::GetVerticalAlignment() const
1927 {
1928   return mImpl->mLayoutEngine.GetVerticalAlignment();
1929 }
1930
1931 void Controller::CalculateVerticalOffset( const Size& controlSize )
1932 {
1933   Size layoutSize = mImpl->mVisualModel->GetLayoutSize();
1934
1935   if( fabsf( layoutSize.height ) < Math::MACHINE_EPSILON_1000 )
1936   {
1937     // Get the line height of the default font.
1938     layoutSize.height = mImpl->GetDefaultFontLineHeight();
1939   }
1940
1941   switch( mImpl->mLayoutEngine.GetVerticalAlignment() )
1942   {
1943     case LayoutEngine::VERTICAL_ALIGN_TOP:
1944     {
1945       mImpl->mScrollPosition.y = 0.f;
1946       break;
1947     }
1948     case LayoutEngine::VERTICAL_ALIGN_CENTER:
1949     {
1950       mImpl->mScrollPosition.y = floorf( 0.5f * ( controlSize.height - layoutSize.height ) ); // try to avoid pixel alignment.
1951       break;
1952     }
1953     case LayoutEngine::VERTICAL_ALIGN_BOTTOM:
1954     {
1955       mImpl->mScrollPosition.y = controlSize.height - layoutSize.height;
1956       break;
1957     }
1958   }
1959 }
1960
1961 LayoutEngine& Controller::GetLayoutEngine()
1962 {
1963   return mImpl->mLayoutEngine;
1964 }
1965
1966 View& Controller::GetView()
1967 {
1968   return mImpl->mView;
1969 }
1970
1971 void Controller::KeyboardFocusGainEvent()
1972 {
1973   DALI_ASSERT_DEBUG( mImpl->mEventData && "Unexpected KeyboardFocusGainEvent" );
1974
1975   if( NULL != mImpl->mEventData )
1976   {
1977     if( ( EventData::INACTIVE == mImpl->mEventData->mState ) ||
1978         ( EventData::INTERRUPTED == mImpl->mEventData->mState ) )
1979     {
1980       mImpl->ChangeState( EventData::EDITING );
1981       mImpl->mEventData->mUpdateCursorPosition = true; //If editing started without tap event, cursor update must be triggered.
1982     }
1983
1984     if( mImpl->IsShowingPlaceholderText() )
1985     {
1986       // Show alternative placeholder-text when editing
1987       ShowPlaceholderText();
1988     }
1989
1990     mImpl->RequestRelayout();
1991   }
1992 }
1993
1994 void Controller::KeyboardFocusLostEvent()
1995 {
1996   DALI_ASSERT_DEBUG( mImpl->mEventData && "Unexpected KeyboardFocusLostEvent" );
1997
1998   if( NULL != mImpl->mEventData )
1999   {
2000     if( EventData::INTERRUPTED != mImpl->mEventData->mState )
2001     {
2002       mImpl->ChangeState( EventData::INACTIVE );
2003
2004       if( !mImpl->IsShowingRealText() )
2005       {
2006         // Revert to regular placeholder-text when not editing
2007         ShowPlaceholderText();
2008       }
2009     }
2010   }
2011   mImpl->RequestRelayout();
2012 }
2013
2014 bool Controller::KeyEvent( const Dali::KeyEvent& keyEvent )
2015 {
2016   DALI_ASSERT_DEBUG( mImpl->mEventData && "Unexpected KeyEvent" );
2017
2018   bool textChanged( false );
2019
2020   if( ( NULL != mImpl->mEventData ) &&
2021       ( keyEvent.state == KeyEvent::Down ) )
2022   {
2023     int keyCode = keyEvent.keyCode;
2024     const std::string& keyString = keyEvent.keyPressed;
2025
2026     // Pre-process to separate modifying events from non-modifying input events.
2027     if( Dali::DALI_KEY_ESCAPE == keyCode )
2028     {
2029       // Escape key is a special case which causes focus loss
2030       KeyboardFocusLostEvent();
2031     }
2032     else if( ( Dali::DALI_KEY_CURSOR_LEFT  == keyCode ) ||
2033              ( Dali::DALI_KEY_CURSOR_RIGHT == keyCode ) ||
2034              ( Dali::DALI_KEY_CURSOR_UP    == keyCode ) ||
2035              ( Dali::DALI_KEY_CURSOR_DOWN  == keyCode ) )
2036     {
2037       Event event( Event::CURSOR_KEY_EVENT );
2038       event.p1.mInt = keyCode;
2039       mImpl->mEventData->mEventQueue.push_back( event );
2040     }
2041     else if( Dali::DALI_KEY_BACKSPACE == keyCode )
2042     {
2043       textChanged = BackspaceKeyEvent();
2044     }
2045     else if( IsKey( keyEvent,  Dali::DALI_KEY_POWER ) )
2046     {
2047       mImpl->ChangeState( EventData::INTERRUPTED ); // State is not INACTIVE as expect to return to edit mode.
2048       // Avoids calling the InsertText() method which can delete selected text
2049     }
2050     else if( IsKey( keyEvent, Dali::DALI_KEY_MENU ) ||
2051              IsKey( keyEvent, Dali::DALI_KEY_HOME ) )
2052     {
2053       mImpl->ChangeState( EventData::INACTIVE );
2054       // Menu/Home key behaviour does not allow edit mode to resume like Power key
2055       // Avoids calling the InsertText() method which can delete selected text
2056     }
2057     else if( Dali::DALI_KEY_SHIFT_LEFT == keyCode )
2058     {
2059       // DALI_KEY_SHIFT_LEFT is the key code for the Left Shift. It's sent (by the imf?) when the predictive text is enabled
2060       // and a character is typed after the type of a upper case latin character.
2061
2062       // Do nothing.
2063     }
2064     else
2065     {
2066       DALI_LOG_INFO( gLogFilter, Debug::Verbose, "Controller::KeyEvent %p keyString %s\n", this, keyString.c_str() );
2067
2068       // IMF manager is no longer handling key-events
2069       mImpl->ClearPreEditFlag();
2070
2071       InsertText( keyString, COMMIT );
2072       textChanged = true;
2073     }
2074
2075     if ( ( mImpl->mEventData->mState != EventData::INTERRUPTED ) &&
2076          ( mImpl->mEventData->mState != EventData::INACTIVE ) &&
2077          ( Dali::DALI_KEY_SHIFT_LEFT != keyCode ) )
2078     {
2079       // Should not change the state if the key is the shift send by the imf manager.
2080       // Otherwise, when the state is SELECTING the text controller can't send the right
2081       // surrounding info to the imf.
2082       mImpl->ChangeState( EventData::EDITING );
2083     }
2084
2085     mImpl->RequestRelayout();
2086   }
2087
2088   if( textChanged )
2089   {
2090     // Do this last since it provides callbacks into application code
2091     mImpl->mControlInterface.TextChanged();
2092   }
2093
2094   return true;
2095 }
2096
2097 void Controller::InsertText( const std::string& text, Controller::InsertType type )
2098 {
2099   bool removedPrevious( false );
2100   bool maxLengthReached( false );
2101
2102   DALI_ASSERT_DEBUG( NULL != mImpl->mEventData && "Unexpected InsertText" )
2103
2104   if( NULL == mImpl->mEventData )
2105   {
2106     return;
2107   }
2108
2109   DALI_LOG_INFO( gLogFilter, Debug::Verbose, "Controller::InsertText %p %s (%s) mPrimaryCursorPosition %d mPreEditFlag %d mPreEditStartPosition %d mPreEditLength %d\n",
2110                  this, text.c_str(), (COMMIT == type ? "COMMIT" : "PRE_EDIT"),
2111                  mImpl->mEventData->mPrimaryCursorPosition, mImpl->mEventData->mPreEditFlag, mImpl->mEventData->mPreEditStartPosition, mImpl->mEventData->mPreEditLength );
2112
2113   // TODO: At the moment the underline runs are only for pre-edit.
2114   mImpl->mVisualModel->mUnderlineRuns.Clear();
2115
2116   // Keep the current number of characters.
2117   const Length currentNumberOfCharacters = mImpl->IsShowingRealText() ? mImpl->mLogicalModel->mText.Count() : 0u;
2118
2119   // Remove the previous IMF pre-edit.
2120   if( mImpl->mEventData->mPreEditFlag && ( 0u != mImpl->mEventData->mPreEditLength ) )
2121   {
2122     removedPrevious = RemoveText( -static_cast<int>( mImpl->mEventData->mPrimaryCursorPosition - mImpl->mEventData->mPreEditStartPosition ),
2123                                   mImpl->mEventData->mPreEditLength,
2124                                   DONT_UPDATE_INPUT_STYLE );
2125
2126     mImpl->mEventData->mPrimaryCursorPosition = mImpl->mEventData->mPreEditStartPosition;
2127     mImpl->mEventData->mPreEditLength = 0u;
2128   }
2129   else
2130   {
2131     // Remove the previous Selection.
2132     removedPrevious = RemoveSelectedText();
2133   }
2134
2135   Vector<Character> utf32Characters;
2136   Length characterCount = 0u;
2137
2138   if( !text.empty() )
2139   {
2140     //  Convert text into UTF-32
2141     utf32Characters.Resize( text.size() );
2142
2143     // This is a bit horrible but std::string returns a (signed) char*
2144     const uint8_t* utf8 = reinterpret_cast<const uint8_t*>( text.c_str() );
2145
2146     // Transform a text array encoded in utf8 into an array encoded in utf32.
2147     // It returns the actual number of characters.
2148     characterCount = Utf8ToUtf32( utf8, text.size(), utf32Characters.Begin() );
2149     utf32Characters.Resize( characterCount );
2150
2151     DALI_ASSERT_DEBUG( text.size() >= utf32Characters.Count() && "Invalid UTF32 conversion length" );
2152     DALI_LOG_INFO( gLogFilter, Debug::Verbose, "UTF8 size %d, UTF32 size %d\n", text.size(), utf32Characters.Count() );
2153   }
2154
2155   if( 0u != utf32Characters.Count() ) // Check if Utf8ToUtf32 conversion succeeded
2156   {
2157     // The placeholder text is no longer needed
2158     if( mImpl->IsShowingPlaceholderText() )
2159     {
2160       ResetText();
2161     }
2162
2163     mImpl->ChangeState( EventData::EDITING );
2164
2165     // Handle the IMF (predicitive text) state changes
2166     if( COMMIT == type )
2167     {
2168       // IMF manager is no longer handling key-events
2169       mImpl->ClearPreEditFlag();
2170     }
2171     else // PRE_EDIT
2172     {
2173       if( !mImpl->mEventData->mPreEditFlag )
2174       {
2175         DALI_LOG_INFO( gLogFilter, Debug::Verbose, "Entered PreEdit state" );
2176
2177         // Record the start of the pre-edit text
2178         mImpl->mEventData->mPreEditStartPosition = mImpl->mEventData->mPrimaryCursorPosition;
2179       }
2180
2181       mImpl->mEventData->mPreEditLength = utf32Characters.Count();
2182       mImpl->mEventData->mPreEditFlag = true;
2183
2184       DALI_LOG_INFO( gLogFilter, Debug::Verbose, "mPreEditStartPosition %d mPreEditLength %d\n", mImpl->mEventData->mPreEditStartPosition, mImpl->mEventData->mPreEditLength );
2185     }
2186
2187     const Length numberOfCharactersInModel = mImpl->mLogicalModel->mText.Count();
2188
2189     // Restrict new text to fit within Maximum characters setting.
2190     Length maxSizeOfNewText = std::min( ( mImpl->mMaximumNumberOfCharacters - numberOfCharactersInModel ), characterCount );
2191     maxLengthReached = ( characterCount > maxSizeOfNewText );
2192
2193     // The cursor position.
2194     CharacterIndex& cursorIndex = mImpl->mEventData->mPrimaryCursorPosition;
2195
2196     // Update the text's style.
2197
2198     // Updates the text style runs by adding characters.
2199     mImpl->mLogicalModel->UpdateTextStyleRuns( cursorIndex, maxSizeOfNewText );
2200
2201     // Get the character index from the cursor index.
2202     const CharacterIndex styleIndex = ( cursorIndex > 0u ) ? cursorIndex - 1u : 0u;
2203
2204     // Retrieve the text's style for the given index.
2205     InputStyle style;
2206     mImpl->RetrieveDefaultInputStyle( style );
2207     mImpl->mLogicalModel->RetrieveStyle( styleIndex, style );
2208
2209     // Whether to add a new text color run.
2210     const bool addColorRun = ( style.textColor != mImpl->mEventData->mInputStyle.textColor );
2211
2212     // Whether to add a new font run.
2213     const bool addFontNameRun = style.familyName != mImpl->mEventData->mInputStyle.familyName;
2214     const bool addFontWeightRun = style.weight != mImpl->mEventData->mInputStyle.weight;
2215     const bool addFontWidthRun = style.width != mImpl->mEventData->mInputStyle.width;
2216     const bool addFontSlantRun = style.slant != mImpl->mEventData->mInputStyle.slant;
2217     const bool addFontSizeRun = style.size != mImpl->mEventData->mInputStyle.size;
2218
2219     // Add style runs.
2220     if( addColorRun )
2221     {
2222       const VectorBase::SizeType numberOfRuns = mImpl->mLogicalModel->mColorRuns.Count();
2223       mImpl->mLogicalModel->mColorRuns.Resize( numberOfRuns + 1u );
2224
2225       ColorRun& colorRun = *( mImpl->mLogicalModel->mColorRuns.Begin() + numberOfRuns );
2226       colorRun.color = mImpl->mEventData->mInputStyle.textColor;
2227       colorRun.characterRun.characterIndex = cursorIndex;
2228       colorRun.characterRun.numberOfCharacters = maxSizeOfNewText;
2229     }
2230
2231     if( addFontNameRun   ||
2232         addFontWeightRun ||
2233         addFontWidthRun  ||
2234         addFontSlantRun  ||
2235         addFontSizeRun )
2236     {
2237       const VectorBase::SizeType numberOfRuns = mImpl->mLogicalModel->mFontDescriptionRuns.Count();
2238       mImpl->mLogicalModel->mFontDescriptionRuns.Resize( numberOfRuns + 1u );
2239
2240       FontDescriptionRun& fontDescriptionRun = *( mImpl->mLogicalModel->mFontDescriptionRuns.Begin() + numberOfRuns );
2241
2242       if( addFontNameRun )
2243       {
2244         fontDescriptionRun.familyLength = mImpl->mEventData->mInputStyle.familyName.size();
2245         fontDescriptionRun.familyName = new char[fontDescriptionRun.familyLength];
2246         memcpy( fontDescriptionRun.familyName, mImpl->mEventData->mInputStyle.familyName.c_str(), fontDescriptionRun.familyLength );
2247         fontDescriptionRun.familyDefined = true;
2248
2249         // The memory allocated for the font family name is freed when the font description is removed from the logical model.
2250       }
2251
2252       if( addFontWeightRun )
2253       {
2254         fontDescriptionRun.weight = mImpl->mEventData->mInputStyle.weight;
2255         fontDescriptionRun.weightDefined = true;
2256       }
2257
2258       if( addFontWidthRun )
2259       {
2260         fontDescriptionRun.width = mImpl->mEventData->mInputStyle.width;
2261         fontDescriptionRun.widthDefined = true;
2262       }
2263
2264       if( addFontSlantRun )
2265       {
2266         fontDescriptionRun.slant = mImpl->mEventData->mInputStyle.slant;
2267         fontDescriptionRun.slantDefined = true;
2268       }
2269
2270       if( addFontSizeRun )
2271       {
2272         fontDescriptionRun.size = static_cast<PointSize26Dot6>( mImpl->mEventData->mInputStyle.size * 64.f );
2273         fontDescriptionRun.sizeDefined = true;
2274       }
2275
2276       fontDescriptionRun.characterRun.characterIndex = cursorIndex;
2277       fontDescriptionRun.characterRun.numberOfCharacters = maxSizeOfNewText;
2278     }
2279
2280     // Insert at current cursor position.
2281     Vector<Character>& modifyText = mImpl->mLogicalModel->mText;
2282
2283     if( cursorIndex < numberOfCharactersInModel )
2284     {
2285       modifyText.Insert( modifyText.Begin() + cursorIndex, utf32Characters.Begin(), utf32Characters.Begin() + maxSizeOfNewText );
2286     }
2287     else
2288     {
2289       modifyText.Insert( modifyText.End(), utf32Characters.Begin(), utf32Characters.Begin() + maxSizeOfNewText );
2290     }
2291
2292     // Mark the first paragraph to be updated.
2293     mImpl->mTextUpdateInfo.mCharacterIndex = std::min( cursorIndex, mImpl->mTextUpdateInfo.mCharacterIndex );
2294     mImpl->mTextUpdateInfo.mNumberOfCharactersToAdd += maxSizeOfNewText;
2295
2296     // Update the cursor index.
2297     cursorIndex += maxSizeOfNewText;
2298
2299     DALI_LOG_INFO( gLogFilter, Debug::Verbose, "Inserted %d characters, new size %d new cursor %d\n", maxSizeOfNewText, mImpl->mLogicalModel->mText.Count(), mImpl->mEventData->mPrimaryCursorPosition );
2300   }
2301
2302   const Length numberOfCharacters = mImpl->IsShowingRealText() ? mImpl->mLogicalModel->mText.Count() : 0u;
2303
2304   if( ( 0u == mImpl->mLogicalModel->mText.Count() ) &&
2305       mImpl->IsPlaceholderAvailable() )
2306   {
2307     // Show place-holder if empty after removing the pre-edit text
2308     ShowPlaceholderText();
2309     mImpl->mEventData->mUpdateCursorPosition = true;
2310     mImpl->ClearPreEditFlag();
2311   }
2312   else if( removedPrevious ||
2313            ( 0 != utf32Characters.Count() ) )
2314   {
2315     // Queue an inserted event
2316     mImpl->QueueModifyEvent( ModifyEvent::TEXT_INSERTED );
2317
2318     mImpl->mEventData->mUpdateCursorPosition = true;
2319     if( numberOfCharacters < currentNumberOfCharacters )
2320     {
2321       mImpl->mEventData->mScrollAfterDelete = true;
2322     }
2323     else
2324     {
2325       mImpl->mEventData->mScrollAfterUpdatePosition = true;
2326     }
2327   }
2328
2329   if( maxLengthReached )
2330   {
2331     DALI_LOG_INFO( gLogFilter, Debug::Verbose, "MaxLengthReached (%d)\n", mImpl->mLogicalModel->mText.Count() );
2332
2333     mImpl->ResetImfManager();
2334
2335     // Do this last since it provides callbacks into application code
2336     mImpl->mControlInterface.MaxLengthReached();
2337   }
2338 }
2339
2340 bool Controller::RemoveSelectedText()
2341 {
2342   bool textRemoved( false );
2343
2344   if( EventData::SELECTING == mImpl->mEventData->mState )
2345   {
2346     std::string removedString;
2347     mImpl->RetrieveSelection( removedString, true );
2348
2349     if( !removedString.empty() )
2350     {
2351       textRemoved = true;
2352       mImpl->ChangeState( EventData::EDITING );
2353     }
2354   }
2355
2356   return textRemoved;
2357 }
2358
2359 void Controller::TapEvent( unsigned int tapCount, float x, float y )
2360 {
2361   DALI_ASSERT_DEBUG( mImpl->mEventData && "Unexpected TapEvent" );
2362
2363   if( NULL != mImpl->mEventData )
2364   {
2365     DALI_LOG_INFO( gLogFilter, Debug::Concise, "TapEvent state:%d \n", mImpl->mEventData->mState );
2366
2367     if( 1u == tapCount )
2368     {
2369       // This is to avoid unnecessary relayouts when tapping an empty text-field
2370       bool relayoutNeeded( false );
2371
2372       if( ( EventData::EDITING_WITH_POPUP == mImpl->mEventData->mState ) ||
2373           ( EventData::EDITING_WITH_PASTE_POPUP == mImpl->mEventData->mState ) )
2374       {
2375         mImpl->ChangeState( EventData::EDITING_WITH_GRAB_HANDLE );  // If Popup shown hide it here so can be shown again if required.
2376       }
2377
2378       if( mImpl->IsShowingRealText() && ( EventData::INACTIVE != mImpl->mEventData->mState ) )
2379       {
2380         // Already in an active state so show a popup
2381         if( !mImpl->IsClipboardEmpty() )
2382         {
2383           // Shows Paste popup but could show full popup with Selection options. ( EDITING_WITH_POPUP )
2384           mImpl->ChangeState( EventData::EDITING_WITH_PASTE_POPUP );
2385         }
2386         else
2387         {
2388           // Show cursor and grabhandle on first tap, this matches the behaviour of tapping when already editing
2389           mImpl->ChangeState( EventData::EDITING_WITH_GRAB_HANDLE );
2390         }
2391         relayoutNeeded = true;
2392       }
2393       else
2394       {
2395         if( mImpl->IsShowingPlaceholderText() && !mImpl->IsFocusedPlaceholderAvailable() )
2396         {
2397           // Hide placeholder text
2398           ResetText();
2399         }
2400
2401         if( EventData::INACTIVE == mImpl->mEventData->mState )
2402         {
2403           mImpl->ChangeState( EventData::EDITING );
2404         }
2405         else if( !mImpl->IsClipboardEmpty() )
2406         {
2407           mImpl->ChangeState( EventData::EDITING_WITH_POPUP );
2408         }
2409         relayoutNeeded = true;
2410       }
2411
2412       // Handles & cursors must be repositioned after Relayout() i.e. after the Model has been updated
2413       if( relayoutNeeded )
2414       {
2415         Event event( Event::TAP_EVENT );
2416         event.p1.mUint = tapCount;
2417         event.p2.mFloat = x;
2418         event.p3.mFloat = y;
2419         mImpl->mEventData->mEventQueue.push_back( event );
2420
2421         mImpl->RequestRelayout();
2422       }
2423     }
2424     else if( 2u == tapCount )
2425     {
2426       if( mImpl->mEventData->mSelectionEnabled &&
2427           mImpl->IsShowingRealText() )
2428       {
2429         SelectEvent( x, y, false );
2430       }
2431     }
2432   }
2433
2434   // Reset keyboard as tap event has occurred.
2435   mImpl->ResetImfManager();
2436 }
2437
2438 void Controller::PanEvent( Gesture::State state, const Vector2& displacement )
2439 {
2440   DALI_ASSERT_DEBUG( mImpl->mEventData && "Unexpected PanEvent" );
2441
2442   if( NULL != mImpl->mEventData )
2443   {
2444     Event event( Event::PAN_EVENT );
2445     event.p1.mInt = state;
2446     event.p2.mFloat = displacement.x;
2447     event.p3.mFloat = displacement.y;
2448     mImpl->mEventData->mEventQueue.push_back( event );
2449
2450     mImpl->RequestRelayout();
2451   }
2452 }
2453
2454 void Controller::LongPressEvent( Gesture::State state, float x, float y  )
2455 {
2456   DALI_ASSERT_DEBUG( mImpl->mEventData && "Unexpected LongPressEvent" );
2457
2458   if( ( state == Gesture::Started ) &&
2459       ( NULL != mImpl->mEventData ) )
2460   {
2461     if( !mImpl->IsShowingRealText() )
2462     {
2463       Event event( Event::LONG_PRESS_EVENT );
2464       event.p1.mInt = state;
2465       mImpl->mEventData->mEventQueue.push_back( event );
2466       mImpl->RequestRelayout();
2467     }
2468     else
2469     {
2470       // The 1st long-press on inactive text-field is treated as tap
2471       if( EventData::INACTIVE == mImpl->mEventData->mState )
2472       {
2473         mImpl->ChangeState( EventData::EDITING );
2474
2475         Event event( Event::TAP_EVENT );
2476         event.p1.mUint = 1;
2477         event.p2.mFloat = x;
2478         event.p3.mFloat = y;
2479         mImpl->mEventData->mEventQueue.push_back( event );
2480
2481         mImpl->RequestRelayout();
2482       }
2483       else
2484       {
2485         // Reset the imf manger to commit the pre-edit before selecting the text.
2486         mImpl->ResetImfManager();
2487
2488         SelectEvent( x, y, false );
2489       }
2490     }
2491   }
2492 }
2493
2494 void Controller::SelectEvent( float x, float y, bool selectAll )
2495 {
2496   DALI_LOG_INFO( gLogFilter, Debug::Verbose, "Controller::SelectEvent\n" );
2497
2498   if( NULL != mImpl->mEventData )
2499   {
2500     if( selectAll )
2501     {
2502       Event event( Event::SELECT_ALL );
2503       mImpl->mEventData->mEventQueue.push_back( event );
2504     }
2505     else
2506     {
2507       Event event( Event::SELECT );
2508       event.p2.mFloat = x;
2509       event.p3.mFloat = y;
2510       mImpl->mEventData->mEventQueue.push_back( event );
2511     }
2512
2513     mImpl->RequestRelayout();
2514   }
2515 }
2516
2517 void Controller::GetTargetSize( Vector2& targetSize )
2518 {
2519   targetSize = mImpl->mVisualModel->mControlSize;
2520 }
2521
2522 void Controller::AddDecoration( Actor& actor, bool needsClipping )
2523 {
2524   mImpl->mControlInterface.AddDecoration( actor, needsClipping );
2525 }
2526
2527 void Controller::DecorationEvent( HandleType handleType, HandleState state, float x, float y )
2528 {
2529   DALI_ASSERT_DEBUG( mImpl->mEventData && "Unexpected DecorationEvent" );
2530
2531   if( NULL != mImpl->mEventData )
2532   {
2533     switch( handleType )
2534     {
2535       case GRAB_HANDLE:
2536       {
2537         Event event( Event::GRAB_HANDLE_EVENT );
2538         event.p1.mUint  = state;
2539         event.p2.mFloat = x;
2540         event.p3.mFloat = y;
2541
2542         mImpl->mEventData->mEventQueue.push_back( event );
2543         break;
2544       }
2545       case LEFT_SELECTION_HANDLE:
2546       {
2547         Event event( Event::LEFT_SELECTION_HANDLE_EVENT );
2548         event.p1.mUint  = state;
2549         event.p2.mFloat = x;
2550         event.p3.mFloat = y;
2551
2552         mImpl->mEventData->mEventQueue.push_back( event );
2553         break;
2554       }
2555       case RIGHT_SELECTION_HANDLE:
2556       {
2557         Event event( Event::RIGHT_SELECTION_HANDLE_EVENT );
2558         event.p1.mUint  = state;
2559         event.p2.mFloat = x;
2560         event.p3.mFloat = y;
2561
2562         mImpl->mEventData->mEventQueue.push_back( event );
2563         break;
2564       }
2565       case LEFT_SELECTION_HANDLE_MARKER:
2566       case RIGHT_SELECTION_HANDLE_MARKER:
2567       {
2568         // Markers do not move the handles.
2569         break;
2570       }
2571       case HANDLE_TYPE_COUNT:
2572       {
2573         DALI_ASSERT_DEBUG( !"Controller::HandleEvent. Unexpected handle type" );
2574       }
2575     }
2576
2577     mImpl->RequestRelayout();
2578   }
2579 }
2580
2581 void Controller::PasteText( const std::string& stringToPaste )
2582 {
2583   InsertText( stringToPaste, Text::Controller::COMMIT );
2584   mImpl->ChangeState( EventData::EDITING );
2585   mImpl->RequestRelayout();
2586
2587   // Do this last since it provides callbacks into application code
2588   mImpl->mControlInterface.TextChanged();
2589 }
2590
2591 void Controller::PasteClipboardItemEvent()
2592 {
2593   // Retrieve the clipboard contents first
2594   ClipboardEventNotifier notifier( ClipboardEventNotifier::Get() );
2595   std::string stringToPaste( notifier.GetContent() );
2596
2597   // Commit the current pre-edit text; the contents of the clipboard should be appended
2598   mImpl->ResetImfManager();
2599
2600   // Temporary disable hiding clipboard
2601   mImpl->SetClipboardHideEnable( false );
2602
2603   // Paste
2604   PasteText( stringToPaste );
2605
2606   mImpl->SetClipboardHideEnable( true );
2607 }
2608
2609 void Controller::TextPopupButtonTouched( Dali::Toolkit::TextSelectionPopup::Buttons button )
2610 {
2611   if( NULL == mImpl->mEventData )
2612   {
2613     return;
2614   }
2615
2616   switch( button )
2617   {
2618     case Toolkit::TextSelectionPopup::CUT:
2619     {
2620       mImpl->SendSelectionToClipboard( true ); // Synchronous call to modify text
2621       mImpl->mOperationsPending = ALL_OPERATIONS;
2622
2623       if( ( 0u != mImpl->mLogicalModel->mText.Count() ) ||
2624           !mImpl->IsPlaceholderAvailable() )
2625       {
2626         mImpl->QueueModifyEvent( ModifyEvent::TEXT_DELETED );
2627       }
2628       else
2629       {
2630         ShowPlaceholderText();
2631       }
2632
2633       mImpl->mEventData->mUpdateCursorPosition = true;
2634       mImpl->mEventData->mScrollAfterDelete = true;
2635
2636       mImpl->RequestRelayout();
2637       mImpl->mControlInterface.TextChanged();
2638       break;
2639     }
2640     case Toolkit::TextSelectionPopup::COPY:
2641     {
2642       mImpl->SendSelectionToClipboard( false ); // Text not modified
2643
2644       mImpl->mEventData->mUpdateCursorPosition = true;
2645
2646       mImpl->RequestRelayout(); // Cursor, Handles, Selection Highlight, Popup
2647       break;
2648     }
2649     case Toolkit::TextSelectionPopup::PASTE:
2650     {
2651       std::string stringToPaste("");
2652       mImpl->GetTextFromClipboard( 0, stringToPaste ); // Paste latest item from system clipboard
2653       PasteText( stringToPaste );
2654       break;
2655     }
2656     case Toolkit::TextSelectionPopup::SELECT:
2657     {
2658       const Vector2& currentCursorPosition = mImpl->mEventData->mDecorator->GetPosition( PRIMARY_CURSOR );
2659
2660       if( mImpl->mEventData->mSelectionEnabled )
2661       {
2662         // Creates a SELECT event.
2663         SelectEvent( currentCursorPosition.x, currentCursorPosition.y, false );
2664       }
2665       break;
2666     }
2667     case Toolkit::TextSelectionPopup::SELECT_ALL:
2668     {
2669       // Creates a SELECT_ALL event
2670       SelectEvent( 0.f, 0.f, true );
2671       break;
2672     }
2673     case Toolkit::TextSelectionPopup::CLIPBOARD:
2674     {
2675       mImpl->ShowClipboard();
2676       break;
2677     }
2678     case Toolkit::TextSelectionPopup::NONE:
2679     {
2680       // Nothing to do.
2681       break;
2682     }
2683   }
2684 }
2685
2686 ImfManager::ImfCallbackData Controller::OnImfEvent( ImfManager& imfManager, const ImfManager::ImfEventData& imfEvent )
2687 {
2688   // Whether the text needs to be relaid-out.
2689   bool requestRelayout = false;
2690
2691   // Whether to retrieve the text and cursor position to be sent to the IMF manager.
2692   bool retrieveText = false;
2693   bool retrieveCursor = false;
2694
2695   switch( imfEvent.eventName )
2696   {
2697     case ImfManager::COMMIT:
2698     {
2699       InsertText( imfEvent.predictiveString, Text::Controller::COMMIT );
2700       requestRelayout = true;
2701       retrieveCursor = true;
2702       break;
2703     }
2704     case ImfManager::PREEDIT:
2705     {
2706       InsertText( imfEvent.predictiveString, Text::Controller::PRE_EDIT );
2707       requestRelayout = true;
2708       retrieveCursor = true;
2709       break;
2710     }
2711     case ImfManager::DELETESURROUNDING:
2712     {
2713       const bool textDeleted = RemoveText( imfEvent.cursorOffset,
2714                                            imfEvent.numberOfChars,
2715                                            DONT_UPDATE_INPUT_STYLE );
2716
2717       if( textDeleted )
2718       {
2719         if( ( 0u != mImpl->mLogicalModel->mText.Count() ) ||
2720             !mImpl->IsPlaceholderAvailable() )
2721         {
2722           mImpl->QueueModifyEvent( ModifyEvent::TEXT_DELETED );
2723         }
2724         else
2725         {
2726           ShowPlaceholderText();
2727         }
2728         mImpl->mEventData->mUpdateCursorPosition = true;
2729         mImpl->mEventData->mScrollAfterDelete = true;
2730
2731         requestRelayout = true;
2732       }
2733       break;
2734     }
2735     case ImfManager::GETSURROUNDING:
2736     {
2737       retrieveText = true;
2738       retrieveCursor = true;
2739       break;
2740     }
2741     case ImfManager::VOID:
2742     {
2743       // do nothing
2744       break;
2745     }
2746   } // end switch
2747
2748   if( requestRelayout )
2749   {
2750     mImpl->mOperationsPending = ALL_OPERATIONS;
2751     mImpl->RequestRelayout();
2752
2753     // Do this last since it provides callbacks into application code
2754     mImpl->mControlInterface.TextChanged();
2755   }
2756
2757   std::string text;
2758   CharacterIndex cursorPosition = 0u;
2759   Length numberOfWhiteSpaces = 0u;
2760
2761   if( retrieveCursor )
2762   {
2763     numberOfWhiteSpaces = mImpl->GetNumberOfWhiteSpaces( 0u );
2764
2765     cursorPosition = mImpl->GetLogicalCursorPosition();
2766
2767     if( cursorPosition < numberOfWhiteSpaces )
2768     {
2769       cursorPosition = 0u;
2770     }
2771     else
2772     {
2773       cursorPosition -= numberOfWhiteSpaces;
2774     }
2775   }
2776
2777   if( retrieveText )
2778   {
2779     mImpl->GetText( numberOfWhiteSpaces, text );
2780   }
2781
2782   ImfManager::ImfCallbackData callbackData( ( retrieveText || retrieveCursor ), cursorPosition, text, false );
2783
2784   return callbackData;
2785 }
2786
2787 Controller::~Controller()
2788 {
2789   delete mImpl;
2790 }
2791
2792 bool Controller::BackspaceKeyEvent()
2793 {
2794   DALI_LOG_INFO( gLogFilter, Debug::Verbose, "Controller::KeyEvent %p DALI_KEY_BACKSPACE\n", this );
2795
2796   bool removed = false;
2797
2798   if( NULL == mImpl->mEventData )
2799   {
2800     return removed;
2801   }
2802
2803   // IMF manager is no longer handling key-events
2804   mImpl->ClearPreEditFlag();
2805
2806   if( EventData::SELECTING == mImpl->mEventData->mState )
2807   {
2808     removed = RemoveSelectedText();
2809   }
2810   else if( mImpl->mEventData->mPrimaryCursorPosition > 0 )
2811   {
2812     // Remove the character before the current cursor position
2813     removed = RemoveText( -1,
2814                           1,
2815                           UPDATE_INPUT_STYLE );
2816   }
2817
2818   if( removed )
2819   {
2820     if( ( 0u != mImpl->mLogicalModel->mText.Count() ) ||
2821         !mImpl->IsPlaceholderAvailable() )
2822     {
2823       mImpl->QueueModifyEvent( ModifyEvent::TEXT_DELETED );
2824     }
2825     else
2826     {
2827       ShowPlaceholderText();
2828     }
2829     mImpl->mEventData->mUpdateCursorPosition = true;
2830     mImpl->mEventData->mScrollAfterDelete = true;
2831   }
2832
2833   return removed;
2834 }
2835
2836 void Controller::ShowPlaceholderText()
2837 {
2838   if( mImpl->IsPlaceholderAvailable() )
2839   {
2840     DALI_ASSERT_DEBUG( mImpl->mEventData && "No placeholder text available" );
2841
2842     if( NULL == mImpl->mEventData )
2843     {
2844       return;
2845     }
2846
2847     mImpl->mEventData->mIsShowingPlaceholderText = true;
2848
2849     // Disable handles when showing place-holder text
2850     mImpl->mEventData->mDecorator->SetHandleActive( GRAB_HANDLE, false );
2851     mImpl->mEventData->mDecorator->SetHandleActive( LEFT_SELECTION_HANDLE, false );
2852     mImpl->mEventData->mDecorator->SetHandleActive( RIGHT_SELECTION_HANDLE, false );
2853
2854     const char* text( NULL );
2855     size_t size( 0 );
2856
2857     // TODO - Switch placeholder text styles when changing state
2858     if( ( EventData::INACTIVE != mImpl->mEventData->mState ) &&
2859         ( 0u != mImpl->mEventData->mPlaceholderTextActive.c_str() ) )
2860     {
2861       text = mImpl->mEventData->mPlaceholderTextActive.c_str();
2862       size = mImpl->mEventData->mPlaceholderTextActive.size();
2863     }
2864     else
2865     {
2866       text = mImpl->mEventData->mPlaceholderTextInactive.c_str();
2867       size = mImpl->mEventData->mPlaceholderTextInactive.size();
2868     }
2869
2870     mImpl->mTextUpdateInfo.mCharacterIndex = 0u;
2871     mImpl->mTextUpdateInfo.mNumberOfCharactersToRemove = mImpl->mTextUpdateInfo.mPreviousNumberOfCharacters;
2872
2873     // Reset model for showing placeholder.
2874     mImpl->mLogicalModel->mText.Clear();
2875     mImpl->mVisualModel->SetTextColor( mImpl->mEventData->mPlaceholderTextColor );
2876
2877     // Convert text into UTF-32
2878     Vector<Character>& utf32Characters = mImpl->mLogicalModel->mText;
2879     utf32Characters.Resize( size );
2880
2881     // This is a bit horrible but std::string returns a (signed) char*
2882     const uint8_t* utf8 = reinterpret_cast<const uint8_t*>( text );
2883
2884     // Transform a text array encoded in utf8 into an array encoded in utf32.
2885     // It returns the actual number of characters.
2886     const Length characterCount = Utf8ToUtf32( utf8, size, utf32Characters.Begin() );
2887     utf32Characters.Resize( characterCount );
2888
2889     // The characters to be added.
2890     mImpl->mTextUpdateInfo.mNumberOfCharactersToAdd = characterCount;
2891
2892     // Reset the cursor position
2893     mImpl->mEventData->mPrimaryCursorPosition = 0;
2894
2895     // The natural size needs to be re-calculated.
2896     mImpl->mRecalculateNaturalSize = true;
2897
2898     // Apply modifications to the model
2899     mImpl->mOperationsPending = ALL_OPERATIONS;
2900
2901     // Update the rest of the model during size negotiation
2902     mImpl->QueueModifyEvent( ModifyEvent::TEXT_REPLACED );
2903   }
2904 }
2905
2906 void Controller::ClearFontData()
2907 {
2908   if( mImpl->mFontDefaults )
2909   {
2910     mImpl->mFontDefaults->mFontId = 0u; // Remove old font ID
2911   }
2912
2913   // Set flags to update the model.
2914   mImpl->mTextUpdateInfo.mCharacterIndex = 0u;
2915   mImpl->mTextUpdateInfo.mNumberOfCharactersToRemove = mImpl->mTextUpdateInfo.mPreviousNumberOfCharacters;
2916   mImpl->mTextUpdateInfo.mNumberOfCharactersToAdd = mImpl->mLogicalModel->mText.Count();
2917
2918   mImpl->mTextUpdateInfo.mClearAll = true;
2919   mImpl->mTextUpdateInfo.mFullRelayoutNeeded = true;
2920   mImpl->mRecalculateNaturalSize = true;
2921
2922   mImpl->mOperationsPending = static_cast<OperationsMask>( mImpl->mOperationsPending |
2923                                                            VALIDATE_FONTS            |
2924                                                            SHAPE_TEXT                |
2925                                                            GET_GLYPH_METRICS         |
2926                                                            LAYOUT                    |
2927                                                            UPDATE_LAYOUT_SIZE        |
2928                                                            REORDER                   |
2929                                                            ALIGN );
2930 }
2931
2932 void Controller::ClearStyleData()
2933 {
2934   mImpl->mLogicalModel->mColorRuns.Clear();
2935   mImpl->mLogicalModel->ClearFontDescriptionRuns();
2936 }
2937
2938 Controller::Controller( ControlInterface& controlInterface )
2939 : mImpl( NULL )
2940 {
2941   mImpl = new Controller::Impl( controlInterface );
2942 }
2943
2944 } // namespace Text
2945
2946 } // namespace Toolkit
2947
2948 } // namespace Dali