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