e273f013b749d15ceb50df2b68c9ff4f4a1e390e
[platform/core/uifw/dali-toolkit.git] / dali-toolkit / internal / text / text-controller.cpp
1 /*
2  * Copyright (c) 2015 Samsung Electronics Co., Ltd.
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  * http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  *
16  */
17
18 // CLASS HEADER
19 #include <dali-toolkit/internal/text/text-controller.h>
20
21 // EXTERNAL INCLUDES
22 #include <limits>
23 #include <dali/public-api/adaptor-framework/key.h>
24 #include <dali/integration-api/debug.h>
25 #include <dali/devel-api/adaptor-framework/clipboard-event-notifier.h>
26
27 // INTERNAL INCLUDES
28 #include <dali-toolkit/internal/text/bidirectional-support.h>
29 #include <dali-toolkit/internal/text/character-set-conversion.h>
30 #include <dali-toolkit/internal/text/layouts/layout-parameters.h>
31 #include <dali-toolkit/internal/text/markup-processor.h>
32 #include <dali-toolkit/internal/text/text-controller-impl.h>
33
34 namespace
35 {
36
37 #if defined(DEBUG_ENABLED)
38   Debug::Filter* gLogFilter = Debug::Filter::New(Debug::NoLogging, true, "LOG_TEXT_CONTROLS");
39 #endif
40
41 const float MAX_FLOAT = std::numeric_limits<float>::max();
42 const unsigned int POINTS_PER_INCH = 72;
43
44 const std::string EMPTY_STRING("");
45 const unsigned int ZERO = 0u;
46
47 float ConvertToEven( float value )
48 {
49   int intValue(static_cast<int>( value ));
50   return static_cast<float>(intValue % 2 == 0) ? intValue : (intValue + 1);
51 }
52
53 } // namespace
54
55 namespace Dali
56 {
57
58 namespace Toolkit
59 {
60
61 namespace Text
62 {
63
64 ControllerPtr Controller::New( ControlInterface& controlInterface )
65 {
66   return ControllerPtr( new Controller( controlInterface ) );
67 }
68
69 void Controller::EnableTextInput( DecoratorPtr decorator )
70 {
71   if( !mImpl->mEventData )
72   {
73     mImpl->mEventData = new EventData( decorator );
74   }
75 }
76
77 void Controller::SetMarkupProcessorEnabled( bool enable )
78 {
79   mImpl->mMarkupProcessorEnabled = enable;
80 }
81
82 bool Controller::IsMarkupProcessorEnabled() const
83 {
84   return mImpl->mMarkupProcessorEnabled;
85 }
86
87 void Controller::SetText( const std::string& text )
88 {
89   DALI_LOG_INFO( gLogFilter, Debug::Verbose, "Controller::SetText\n" );
90
91   // Reset keyboard as text changed
92   mImpl->ResetImfManager();
93
94   // Remove the previously set text and style.
95   ResetText();
96
97   // Remove the style.
98   ClearStyleData();
99
100   CharacterIndex lastCursorIndex = 0u;
101
102   if( mImpl->mEventData )
103   {
104     // If popup shown then hide it by switching to Editing state
105     if( ( EventData::SELECTING == mImpl->mEventData->mState )          ||
106         ( EventData::EDITING_WITH_POPUP == mImpl->mEventData->mState ) ||
107         ( EventData::EDITING_WITH_GRAB_HANDLE == mImpl->mEventData->mState ) ||
108         ( EventData::EDITING_WITH_PASTE_POPUP == mImpl->mEventData->mState ) )
109     {
110       mImpl->ChangeState( EventData::EDITING );
111     }
112   }
113
114   if( !text.empty() )
115   {
116     MarkupProcessData markupProcessData( mImpl->mLogicalModel->mColorRuns );
117
118     Length textSize = 0u;
119     const uint8_t* utf8 = NULL;
120     if( mImpl->mMarkupProcessorEnabled )
121     {
122       ProcessMarkupString( text, markupProcessData );
123       textSize = markupProcessData.markupProcessedText.size();
124
125       // This is a bit horrible but std::string returns a (signed) char*
126       utf8 = reinterpret_cast<const uint8_t*>( markupProcessData.markupProcessedText.c_str() );
127     }
128     else
129     {
130       textSize = text.size();
131
132       // This is a bit horrible but std::string returns a (signed) char*
133       utf8 = reinterpret_cast<const uint8_t*>( text.c_str() );
134     }
135
136     //  Convert text into UTF-32
137     Vector<Character>& utf32Characters = mImpl->mLogicalModel->mText;
138     utf32Characters.Resize( textSize );
139
140     // Transform a text array encoded in utf8 into an array encoded in utf32.
141     // It returns the actual number of characters.
142     Length characterCount = Utf8ToUtf32( utf8, textSize, utf32Characters.Begin() );
143     utf32Characters.Resize( characterCount );
144
145     DALI_ASSERT_DEBUG( textSize >= characterCount && "Invalid UTF32 conversion length" );
146     DALI_LOG_INFO( gLogFilter, Debug::Verbose, "Controller::SetText %p UTF8 size %d, UTF32 size %d\n", this, textSize, mImpl->mLogicalModel->mText.Count() );
147
148     // To reset the cursor position
149     lastCursorIndex = characterCount;
150
151     // Update the rest of the model during size negotiation
152     mImpl->QueueModifyEvent( ModifyEvent::TEXT_REPLACED );
153
154     // The natural size needs to be re-calculated.
155     mImpl->mRecalculateNaturalSize = true;
156
157     // Apply modifications to the model
158     mImpl->mOperationsPending = ALL_OPERATIONS;
159   }
160   else
161   {
162     ShowPlaceholderText();
163   }
164
165   // Resets the cursor position.
166   ResetCursorPosition( lastCursorIndex );
167
168   // Scrolls the text to make the cursor visible.
169   ResetScrollPosition();
170
171   mImpl->RequestRelayout();
172
173   if( mImpl->mEventData )
174   {
175     // Cancel previously queued events
176     mImpl->mEventData->mEventQueue.clear();
177   }
178
179   // Notify IMF as text changed
180   NotifyImfManager();
181
182   // Do this last since it provides callbacks into application code
183   mImpl->mControlInterface.TextChanged();
184 }
185
186 void Controller::GetText( std::string& text ) const
187 {
188   if( ! mImpl->IsShowingPlaceholderText() )
189   {
190     Vector<Character>& utf32Characters = mImpl->mLogicalModel->mText;
191
192     if( 0u != utf32Characters.Count() )
193     {
194       Utf32ToUtf8( &utf32Characters[0], utf32Characters.Count(), text );
195     }
196   }
197   else
198   {
199     DALI_LOG_INFO( gLogFilter, Debug::Verbose, "Controller::GetText %p empty (but showing placeholder)\n", this );
200   }
201 }
202
203 unsigned int Controller::GetLogicalCursorPosition() const
204 {
205   if( mImpl->mEventData )
206   {
207     return mImpl->mEventData->mPrimaryCursorPosition;
208   }
209
210   return 0u;
211 }
212
213 void Controller::SetPlaceholderText( PlaceholderType type, const std::string& text )
214 {
215   if( mImpl->mEventData )
216   {
217     if( PLACEHOLDER_TYPE_INACTIVE == type )
218     {
219       mImpl->mEventData->mPlaceholderTextInactive = text;
220     }
221     else
222     {
223       mImpl->mEventData->mPlaceholderTextActive = text;
224     }
225
226     // Update placeholder if there is no text
227     if( mImpl->IsShowingPlaceholderText() ||
228         0u == mImpl->mLogicalModel->mText.Count() )
229     {
230       ShowPlaceholderText();
231     }
232   }
233 }
234
235 void Controller::GetPlaceholderText( PlaceholderType type, std::string& text ) const
236 {
237   if( mImpl->mEventData )
238   {
239     if( PLACEHOLDER_TYPE_INACTIVE == type )
240     {
241       text = mImpl->mEventData->mPlaceholderTextInactive;
242     }
243     else
244     {
245       text = mImpl->mEventData->mPlaceholderTextActive;
246     }
247   }
248 }
249
250 void Controller::SetMaximumNumberOfCharacters( int maxCharacters )
251 {
252   if ( maxCharacters >= 0 )
253   {
254     mImpl->mMaximumNumberOfCharacters = maxCharacters;
255   }
256 }
257
258 int Controller::GetMaximumNumberOfCharacters()
259 {
260   return mImpl->mMaximumNumberOfCharacters;
261 }
262
263 void Controller::SetDefaultFontFamily( const std::string& defaultFontFamily )
264 {
265   if( !mImpl->mFontDefaults )
266   {
267     mImpl->mFontDefaults = new FontDefaults();
268   }
269
270   mImpl->mFontDefaults->mFontDescription.family = defaultFontFamily;
271   DALI_LOG_INFO( gLogFilter, Debug::General, "Controller::SetDefaultFontFamily %s\n", defaultFontFamily.c_str());
272   mImpl->mUserDefinedFontFamily = true;
273
274   // Clear the font-specific data
275   ClearFontData();
276
277   mImpl->mOperationsPending = ALL_OPERATIONS;
278   mImpl->mRecalculateNaturalSize = true;
279
280   mImpl->RequestRelayout();
281 }
282
283 const std::string& Controller::GetDefaultFontFamily() const
284 {
285   if( mImpl->mFontDefaults )
286   {
287     return mImpl->mFontDefaults->mFontDescription.family;
288   }
289
290   return EMPTY_STRING;
291 }
292
293 void Controller::SetDefaultFontStyle( const std::string& style )
294 {
295   if( !mImpl->mFontDefaults )
296   {
297     mImpl->mFontDefaults = new FontDefaults();
298   }
299
300   mImpl->mFontDefaults->mFontStyle = style;
301 }
302
303 const std::string& Controller::GetDefaultFontStyle() const
304 {
305   if( mImpl->mFontDefaults )
306   {
307     return mImpl->mFontDefaults->mFontStyle;
308   }
309
310   return EMPTY_STRING;
311 }
312
313 void Controller::SetDefaultFontWidth( FontWidth width )
314 {
315   if( !mImpl->mFontDefaults )
316   {
317     mImpl->mFontDefaults = new FontDefaults();
318   }
319
320   mImpl->mFontDefaults->mFontDescription.width = width;
321
322   // Clear the font-specific data
323   ClearFontData();
324
325   mImpl->mOperationsPending = ALL_OPERATIONS;
326   mImpl->mRecalculateNaturalSize = true;
327
328   mImpl->RequestRelayout();
329 }
330
331 FontWidth Controller::GetDefaultFontWidth() const
332 {
333   if( mImpl->mFontDefaults )
334   {
335     return mImpl->mFontDefaults->mFontDescription.width;
336   }
337
338   return TextAbstraction::FontWidth::NORMAL;
339 }
340
341 void Controller::SetDefaultFontWeight( FontWeight weight )
342 {
343   if( !mImpl->mFontDefaults )
344   {
345     mImpl->mFontDefaults = new FontDefaults();
346   }
347
348   mImpl->mFontDefaults->mFontDescription.weight = weight;
349
350   // Clear the font-specific data
351   ClearFontData();
352
353   mImpl->mOperationsPending = ALL_OPERATIONS;
354   mImpl->mRecalculateNaturalSize = true;
355
356   mImpl->RequestRelayout();
357 }
358
359 FontWeight Controller::GetDefaultFontWeight() const
360 {
361   if( mImpl->mFontDefaults )
362   {
363     return mImpl->mFontDefaults->mFontDescription.weight;
364   }
365
366   return TextAbstraction::FontWeight::NORMAL;
367 }
368
369 void Controller::SetDefaultFontSlant( FontSlant slant )
370 {
371   if( !mImpl->mFontDefaults )
372   {
373     mImpl->mFontDefaults = new FontDefaults();
374   }
375
376   mImpl->mFontDefaults->mFontDescription.slant = slant;
377
378   // Clear the font-specific data
379   ClearFontData();
380
381   mImpl->mOperationsPending = ALL_OPERATIONS;
382   mImpl->mRecalculateNaturalSize = true;
383
384   mImpl->RequestRelayout();
385 }
386
387 FontSlant Controller::GetDefaultFontSlant() const
388 {
389   if( mImpl->mFontDefaults )
390   {
391     return mImpl->mFontDefaults->mFontDescription.slant;
392   }
393
394   return TextAbstraction::FontSlant::NORMAL;
395 }
396
397 void Controller::SetDefaultPointSize( float pointSize )
398 {
399   if( !mImpl->mFontDefaults )
400   {
401     mImpl->mFontDefaults = new FontDefaults();
402   }
403
404   mImpl->mFontDefaults->mDefaultPointSize = pointSize;
405
406   unsigned int horizontalDpi( 0u );
407   unsigned int verticalDpi( 0u );
408   mImpl->mFontClient.GetDpi( horizontalDpi, verticalDpi );
409
410   // Adjust the metrics if the fixed-size font should be down-scaled
411   int maxEmojiSize( pointSize/POINTS_PER_INCH * verticalDpi );
412   DALI_LOG_INFO( gLogFilter, Debug::General, "Controller::SetDefaultPointSize %p setting MaxEmojiSize %d\n", this, maxEmojiSize );
413   mImpl->mMetrics->SetMaxEmojiSize( maxEmojiSize );
414
415   // Clear the font-specific data
416   ClearFontData();
417
418   mImpl->mOperationsPending = ALL_OPERATIONS;
419   mImpl->mRecalculateNaturalSize = true;
420
421   mImpl->RequestRelayout();
422 }
423
424 float Controller::GetDefaultPointSize() const
425 {
426   if( mImpl->mFontDefaults )
427   {
428     return mImpl->mFontDefaults->mDefaultPointSize;
429   }
430
431   return 0.0f;
432 }
433
434 void Controller::UpdateAfterFontChange( std::string& newDefaultFont )
435 {
436   DALI_LOG_INFO( gLogFilter, Debug::Concise, "Controller::UpdateAfterFontChange");
437
438   if ( !mImpl->mUserDefinedFontFamily ) // If user defined font then should not update when system font changes
439   {
440     DALI_LOG_INFO( gLogFilter, Debug::Concise, "Controller::UpdateAfterFontChange newDefaultFont(%s)\n", newDefaultFont.c_str() );
441     ClearFontData();
442     mImpl->mFontDefaults->mFontDescription.family = newDefaultFont;
443     mImpl->UpdateModel( ALL_OPERATIONS );
444     mImpl->QueueModifyEvent( ModifyEvent::TEXT_REPLACED );
445     mImpl->mRecalculateNaturalSize = true;
446     mImpl->RequestRelayout();
447   }
448 }
449
450 void Controller::SetTextColor( const Vector4& textColor )
451 {
452   mImpl->mTextColor = textColor;
453
454   if( !mImpl->IsShowingPlaceholderText() )
455   {
456     mImpl->mVisualModel->SetTextColor( textColor );
457
458     mImpl->RequestRelayout();
459   }
460 }
461
462 const Vector4& Controller::GetTextColor() const
463 {
464   return mImpl->mTextColor;
465 }
466
467 bool Controller::RemoveText( int cursorOffset, int numberOfChars )
468 {
469   bool removed( false );
470
471   DALI_LOG_INFO( gLogFilter, Debug::General, "Controller::RemoveText %p mText.Count() %d cursor %d cursorOffset %d numberOfChars %d\n",
472                  this, mImpl->mLogicalModel->mText.Count(), mImpl->mEventData->mPrimaryCursorPosition, cursorOffset, numberOfChars );
473
474   if( !mImpl->IsShowingPlaceholderText() )
475   {
476     // Delete at current cursor position
477     Vector<Character>& currentText = mImpl->mLogicalModel->mText;
478     CharacterIndex& oldCursorIndex = mImpl->mEventData->mPrimaryCursorPosition;
479
480     CharacterIndex cursorIndex = oldCursorIndex;
481
482     // Validate the cursor position & number of characters
483     if( static_cast< CharacterIndex >( std::abs( cursorOffset ) ) <= cursorIndex )
484     {
485       cursorIndex = oldCursorIndex + cursorOffset;
486     }
487
488     if( ( cursorIndex + numberOfChars ) > currentText.Count() )
489     {
490       numberOfChars = currentText.Count() - cursorIndex;
491     }
492
493     if( ( cursorIndex + numberOfChars ) <= currentText.Count() )
494     {
495       // Update the input style and remove the text's style before removing the text.
496       if( mImpl->mEventData )
497       {
498         // Set first the default input style.
499         mImpl->RetrieveDefaultInputStyle( mImpl->mEventData->mInputStyle );
500
501         // Update the input style.
502         mImpl->mLogicalModel->RetrieveStyle( cursorIndex, mImpl->mEventData->mInputStyle );
503
504         // Remove the text's style before removing the text.
505         mImpl->mLogicalModel->UpdateTextStyleRuns( cursorIndex, -numberOfChars );
506       }
507
508       // Remove the characters.
509       Vector<Character>::Iterator first = currentText.Begin() + cursorIndex;
510       Vector<Character>::Iterator last  = first + numberOfChars;
511
512       currentText.Erase( first, last );
513
514       // Cursor position retreat
515       oldCursorIndex = cursorIndex;
516
517       DALI_LOG_INFO( gLogFilter, Debug::General, "Controller::RemoveText %p removed %d\n", this, numberOfChars );
518       removed = true;
519     }
520   }
521
522   return removed;
523 }
524
525 void Controller::SetPlaceholderTextColor( const Vector4& textColor )
526 {
527   if( mImpl->mEventData )
528   {
529     mImpl->mEventData->mPlaceholderTextColor = textColor;
530   }
531
532   if( mImpl->IsShowingPlaceholderText() )
533   {
534     mImpl->mVisualModel->SetTextColor( textColor );
535     mImpl->RequestRelayout();
536   }
537 }
538
539 const Vector4& Controller::GetPlaceholderTextColor() const
540 {
541   if( mImpl->mEventData )
542   {
543     return mImpl->mEventData->mPlaceholderTextColor;
544   }
545
546   return Color::BLACK;
547 }
548
549 void Controller::SetShadowOffset( const Vector2& shadowOffset )
550 {
551   mImpl->mVisualModel->SetShadowOffset( shadowOffset );
552
553   mImpl->RequestRelayout();
554 }
555
556 const Vector2& Controller::GetShadowOffset() const
557 {
558   return mImpl->mVisualModel->GetShadowOffset();
559 }
560
561 void Controller::SetShadowColor( const Vector4& shadowColor )
562 {
563   mImpl->mVisualModel->SetShadowColor( shadowColor );
564
565   mImpl->RequestRelayout();
566 }
567
568 const Vector4& Controller::GetShadowColor() const
569 {
570   return mImpl->mVisualModel->GetShadowColor();
571 }
572
573 void Controller::SetUnderlineColor( const Vector4& color )
574 {
575   mImpl->mVisualModel->SetUnderlineColor( color );
576
577   mImpl->RequestRelayout();
578 }
579
580 const Vector4& Controller::GetUnderlineColor() const
581 {
582   return mImpl->mVisualModel->GetUnderlineColor();
583 }
584
585 void Controller::SetUnderlineEnabled( bool enabled )
586 {
587   mImpl->mVisualModel->SetUnderlineEnabled( enabled );
588
589   mImpl->RequestRelayout();
590 }
591
592 bool Controller::IsUnderlineEnabled() const
593 {
594   return mImpl->mVisualModel->IsUnderlineEnabled();
595 }
596
597 void Controller::SetUnderlineHeight( float height )
598 {
599   mImpl->mVisualModel->SetUnderlineHeight( height );
600
601   mImpl->RequestRelayout();
602 }
603
604 float Controller::GetUnderlineHeight() const
605 {
606   return mImpl->mVisualModel->GetUnderlineHeight();
607 }
608
609 void Controller::SetInputColor( const Vector4& color )
610 {
611   if( mImpl->mEventData )
612   {
613     mImpl->mEventData->mInputStyle.textColor = color;
614
615     if( EventData::SELECTING == mImpl->mEventData->mState )
616     {
617       const bool handlesCrossed = mImpl->mEventData->mLeftSelectionPosition > mImpl->mEventData->mRightSelectionPosition;
618
619       // Get start and end position of selection
620       const CharacterIndex startOfSelectedText = handlesCrossed ? mImpl->mEventData->mRightSelectionPosition : mImpl->mEventData->mLeftSelectionPosition;
621       const Length lengthOfSelectedText = ( handlesCrossed ? mImpl->mEventData->mLeftSelectionPosition : mImpl->mEventData->mRightSelectionPosition ) - startOfSelectedText;
622
623       // Add the color run.
624       const VectorBase::SizeType numberOfRuns = mImpl->mLogicalModel->mColorRuns.Count();
625       mImpl->mLogicalModel->mColorRuns.Resize( numberOfRuns + 1u );
626
627       ColorRun& colorRun = *( mImpl->mLogicalModel->mColorRuns.Begin() + numberOfRuns );
628       colorRun.color = color;
629       colorRun.characterRun.characterIndex = startOfSelectedText;
630       colorRun.characterRun.numberOfCharacters = lengthOfSelectedText;
631
632       // Request to relayout.
633       mImpl->mOperationsPending = static_cast<OperationsMask>( mImpl->mOperationsPending | COLOR );
634       mImpl->RequestRelayout();
635     }
636   }
637 }
638
639 const Vector4& Controller::GetInputColor() const
640 {
641   if( mImpl->mEventData )
642   {
643     return mImpl->mEventData->mInputStyle.textColor;
644   }
645
646   // Return the default text's color if there is no EventData.
647   return mImpl->mTextColor;
648
649 }
650
651 void Controller::SetEnableCursorBlink( bool enable )
652 {
653   DALI_ASSERT_DEBUG( NULL != mImpl->mEventData && "TextInput disabled" );
654
655   if( mImpl->mEventData )
656   {
657     mImpl->mEventData->mCursorBlinkEnabled = enable;
658
659     if( !enable &&
660         mImpl->mEventData->mDecorator )
661     {
662       mImpl->mEventData->mDecorator->StopCursorBlink();
663     }
664   }
665 }
666
667 bool Controller::GetEnableCursorBlink() const
668 {
669   if( mImpl->mEventData )
670   {
671     return mImpl->mEventData->mCursorBlinkEnabled;
672   }
673
674   return false;
675 }
676
677 const Vector2& Controller::GetScrollPosition() const
678 {
679   if( mImpl->mEventData )
680   {
681     return mImpl->mEventData->mScrollPosition;
682   }
683
684   return Vector2::ZERO;
685 }
686
687 const Vector2& Controller::GetAlignmentOffset() const
688 {
689   return mImpl->mAlignmentOffset;
690 }
691
692 Vector3 Controller::GetNaturalSize()
693 {
694   DALI_LOG_INFO( gLogFilter, Debug::Verbose, "-->Controller::GetNaturalSize\n" );
695   Vector3 naturalSize;
696
697   // Make sure the model is up-to-date before layouting
698   ProcessModifyEvents();
699
700   if( mImpl->mRecalculateNaturalSize )
701   {
702     // Operations that can be done only once until the text changes.
703     const OperationsMask onlyOnceOperations = static_cast<OperationsMask>( CONVERT_TO_UTF32  |
704                                                                            GET_SCRIPTS       |
705                                                                            VALIDATE_FONTS    |
706                                                                            GET_LINE_BREAKS   |
707                                                                            GET_WORD_BREAKS   |
708                                                                            BIDI_INFO         |
709                                                                            SHAPE_TEXT        |
710                                                                            GET_GLYPH_METRICS );
711     // Make sure the model is up-to-date before layouting
712     mImpl->UpdateModel( onlyOnceOperations );
713
714     // Operations that need to be done if the size changes.
715     const OperationsMask sizeOperations =  static_cast<OperationsMask>( LAYOUT |
716                                                                         ALIGN  |
717                                                                         REORDER );
718
719     DoRelayout( Size( MAX_FLOAT, MAX_FLOAT ),
720                 static_cast<OperationsMask>( onlyOnceOperations |
721                                              sizeOperations ),
722                 naturalSize.GetVectorXY() );
723
724     // Do not do again the only once operations.
725     mImpl->mOperationsPending = static_cast<OperationsMask>( mImpl->mOperationsPending & ~onlyOnceOperations );
726
727     // Do the size related operations again.
728     mImpl->mOperationsPending = static_cast<OperationsMask>( mImpl->mOperationsPending | sizeOperations );
729
730     // Stores the natural size to avoid recalculate it again
731     // unless the text/style changes.
732     mImpl->mVisualModel->SetNaturalSize( naturalSize.GetVectorXY() );
733
734     mImpl->mRecalculateNaturalSize = false;
735
736     DALI_LOG_INFO( gLogFilter, Debug::Verbose, "<--Controller::GetNaturalSize calculated %f,%f,%f\n", naturalSize.x, naturalSize.y, naturalSize.z );
737   }
738   else
739   {
740     naturalSize = mImpl->mVisualModel->GetNaturalSize();
741
742     DALI_LOG_INFO( gLogFilter, Debug::Verbose, "<--Controller::GetNaturalSize cached %f,%f,%f\n", naturalSize.x, naturalSize.y, naturalSize.z );
743   }
744
745   naturalSize.x = ConvertToEven( naturalSize.x );
746   naturalSize.y = ConvertToEven( naturalSize.y );
747
748   return naturalSize;
749 }
750
751 float Controller::GetHeightForWidth( float width )
752 {
753   DALI_LOG_INFO( gLogFilter, Debug::Verbose, "-->Controller::GetHeightForWidth %p width %f\n", this, width );
754   // Make sure the model is up-to-date before layouting
755   ProcessModifyEvents();
756
757   Size layoutSize;
758   if( fabsf( width - mImpl->mVisualModel->mControlSize.width ) > Math::MACHINE_EPSILON_1000 )
759   {
760     // Operations that can be done only once until the text changes.
761     const OperationsMask onlyOnceOperations = static_cast<OperationsMask>( CONVERT_TO_UTF32  |
762                                                                            GET_SCRIPTS       |
763                                                                            VALIDATE_FONTS    |
764                                                                            GET_LINE_BREAKS   |
765                                                                            GET_WORD_BREAKS   |
766                                                                            BIDI_INFO         |
767                                                                            SHAPE_TEXT        |
768                                                                            GET_GLYPH_METRICS );
769     // Make sure the model is up-to-date before layouting
770     mImpl->UpdateModel( onlyOnceOperations );
771
772     // Operations that need to be done if the size changes.
773     const OperationsMask sizeOperations =  static_cast<OperationsMask>( LAYOUT |
774                                                                         ALIGN  |
775                                                                         REORDER );
776
777     DoRelayout( Size( width, MAX_FLOAT ),
778                 static_cast<OperationsMask>( onlyOnceOperations |
779                                              sizeOperations ),
780                 layoutSize );
781
782     // Do not do again the only once operations.
783     mImpl->mOperationsPending = static_cast<OperationsMask>( mImpl->mOperationsPending & ~onlyOnceOperations );
784
785     // Do the size related operations again.
786     mImpl->mOperationsPending = static_cast<OperationsMask>( mImpl->mOperationsPending | sizeOperations );
787     DALI_LOG_INFO( gLogFilter, Debug::Verbose, "<--Controller::GetHeightForWidth calculated %f\n", layoutSize.height );
788   }
789   else
790   {
791     layoutSize = mImpl->mVisualModel->GetActualSize();
792     DALI_LOG_INFO( gLogFilter, Debug::Verbose, "<--Controller::GetHeightForWidth cached %f\n", layoutSize.height );
793   }
794
795   return layoutSize.height;
796 }
797
798 bool Controller::Relayout( const Size& size )
799 {
800   DALI_LOG_INFO( gLogFilter, Debug::Verbose, "-->Controller::Relayout %p size %f,%f\n", this, size.width, size.height );
801
802   if( ( size.width < Math::MACHINE_EPSILON_1000 ) || ( size.height < Math::MACHINE_EPSILON_1000 ) )
803   {
804     bool glyphsRemoved( false );
805     if( 0u != mImpl->mVisualModel->mGlyphPositions.Count() )
806     {
807       mImpl->mVisualModel->mGlyphPositions.Clear();
808       glyphsRemoved = true;
809     }
810     // Not worth to relayout if width or height is equal to zero.
811     DALI_LOG_INFO( gLogFilter, Debug::Verbose, "<--Controller::Relayout (skipped)\n" );
812     return glyphsRemoved;
813   }
814
815   const bool newSize = ( size != mImpl->mVisualModel->mControlSize );
816
817   if( newSize )
818   {
819     DALI_LOG_INFO( gLogFilter, Debug::Verbose, "new size (previous size %f,%f)\n", mImpl->mVisualModel->mControlSize.width, mImpl->mVisualModel->mControlSize.height );
820
821     // Layout operations that need to be done if the size changes.
822     mImpl->mOperationsPending = static_cast<OperationsMask>( mImpl->mOperationsPending |
823                                                              LAYOUT                    |
824                                                              ALIGN                     |
825                                                              UPDATE_ACTUAL_SIZE        |
826                                                              REORDER );
827
828     mImpl->mVisualModel->mControlSize = size;
829   }
830
831   // Whether there are modify events.
832   const bool isModifyEventsEmpty = 0u == mImpl->mModifyEvents.Count();
833
834   // Make sure the model is up-to-date before layouting.
835   ProcessModifyEvents();
836   mImpl->UpdateModel( mImpl->mOperationsPending );
837
838   // Style operations that need to be done if the text is modified.
839   if( !isModifyEventsEmpty )
840   {
841     mImpl->mOperationsPending = static_cast<OperationsMask>( mImpl->mOperationsPending |
842                                                              COLOR );
843   }
844
845   // Apply the style runs if text is modified.
846   bool updated = mImpl->UpdateModelStyle( mImpl->mOperationsPending );
847
848   // Layout the text.
849   Size layoutSize;
850   updated = DoRelayout( mImpl->mVisualModel->mControlSize,
851                         mImpl->mOperationsPending,
852                         layoutSize ) || updated;
853
854   // Do not re-do any operation until something changes.
855   mImpl->mOperationsPending = NO_OPERATION;
856
857   // Keep the current offset and alignment as it will be used to update the decorator's positions (if the size changes).
858   Vector2 offset;
859   if( newSize && mImpl->mEventData )
860   {
861     offset = mImpl->mAlignmentOffset + mImpl->mEventData->mScrollPosition;
862   }
863
864   // After doing the text layout, the alignment offset to place the actor in the desired position can be calculated.
865   CalculateTextAlignment( size );
866
867   if( mImpl->mEventData )
868   {
869     if( newSize )
870     {
871       // If there is a new size, the scroll position needs to be clamped.
872       mImpl->ClampHorizontalScroll( layoutSize );
873
874       // Update the decorator's positions is needed if there is a new size.
875       mImpl->mEventData->mDecorator->UpdatePositions( mImpl->mAlignmentOffset + mImpl->mEventData->mScrollPosition - offset );
876     }
877
878     // Move the cursor, grab handle etc.
879     updated = mImpl->ProcessInputEvents() || updated;
880   }
881
882   DALI_LOG_INFO( gLogFilter, Debug::Verbose, "<--Controller::Relayout\n" );
883   return updated;
884 }
885
886 void Controller::ProcessModifyEvents()
887 {
888   Vector<ModifyEvent>& events = mImpl->mModifyEvents;
889
890   if( 0u == events.Count() )
891   {
892     // Nothing to do.
893     return;
894   }
895
896   for( Vector<ModifyEvent>::ConstIterator it = events.Begin(),
897          endIt = events.End();
898        it != endIt;
899        ++it )
900   {
901     const ModifyEvent& event = *it;
902
903     if( ModifyEvent::TEXT_REPLACED == event.type )
904     {
905       // A (single) replace event should come first, otherwise we wasted time processing NOOP events
906       DALI_ASSERT_DEBUG( it == events.Begin() && "Unexpected TEXT_REPLACED event" );
907
908       TextReplacedEvent();
909     }
910     else if( ModifyEvent::TEXT_INSERTED == event.type )
911     {
912       TextInsertedEvent();
913     }
914     else if( ModifyEvent::TEXT_DELETED == event.type )
915     {
916       // Placeholder-text cannot be deleted
917       if( !mImpl->IsShowingPlaceholderText() )
918       {
919         TextDeletedEvent();
920       }
921     }
922   }
923
924   if( mImpl->mEventData )
925   {
926     // When the text is being modified, delay cursor blinking
927     mImpl->mEventData->mDecorator->DelayCursorBlink();
928   }
929
930   // Discard temporary text
931   events.Clear();
932 }
933
934 void Controller::ResetText()
935 {
936   // Reset buffers.
937   mImpl->mLogicalModel->mText.Clear();
938   ClearModelData();
939
940   // We have cleared everything including the placeholder-text
941   mImpl->PlaceholderCleared();
942
943   // The natural size needs to be re-calculated.
944   mImpl->mRecalculateNaturalSize = true;
945
946   // Apply modifications to the model
947   mImpl->mOperationsPending = ALL_OPERATIONS;
948 }
949
950 void Controller::ResetCursorPosition( CharacterIndex cursorIndex )
951 {
952   // Reset the cursor position
953   if( NULL != mImpl->mEventData )
954   {
955     mImpl->mEventData->mPrimaryCursorPosition = cursorIndex;
956
957     // Update the cursor if it's in editing mode.
958     if ( EventData::IsEditingState( mImpl->mEventData->mState )  )
959     {
960       mImpl->mEventData->mUpdateCursorPosition = true;
961     }
962   }
963 }
964
965 void Controller::ResetScrollPosition()
966 {
967   if( NULL != mImpl->mEventData )
968   {
969     // Reset the scroll position.
970     mImpl->mEventData->mScrollPosition = Vector2::ZERO;
971     mImpl->mEventData->mScrollAfterUpdatePosition = true;
972   }
973 }
974
975 void Controller::TextReplacedEvent()
976 {
977   // Reset buffers.
978   ClearModelData();
979
980   // The natural size needs to be re-calculated.
981   mImpl->mRecalculateNaturalSize = true;
982
983   // Apply modifications to the model
984   mImpl->mOperationsPending = ALL_OPERATIONS;
985   mImpl->UpdateModel( ALL_OPERATIONS );
986   mImpl->mOperationsPending = static_cast<OperationsMask>( LAYOUT             |
987                                                            ALIGN              |
988                                                            UPDATE_ACTUAL_SIZE |
989                                                            REORDER );
990 }
991
992 void Controller::TextInsertedEvent()
993 {
994   DALI_ASSERT_DEBUG( NULL != mImpl->mEventData && "Unexpected TextInsertedEvent" );
995
996   // TODO - Optimize this
997   ClearModelData();
998
999   // The natural size needs to be re-calculated.
1000   mImpl->mRecalculateNaturalSize = true;
1001
1002   // Apply modifications to the model; TODO - Optimize this
1003   mImpl->mOperationsPending = ALL_OPERATIONS;
1004   mImpl->UpdateModel( ALL_OPERATIONS );
1005   mImpl->mOperationsPending = static_cast<OperationsMask>( LAYOUT             |
1006                                                            ALIGN              |
1007                                                            UPDATE_ACTUAL_SIZE |
1008                                                            REORDER );
1009
1010   // Queue a cursor reposition event; this must wait until after DoRelayout()
1011   if ( EventData::IsEditingState( mImpl->mEventData->mState )  )
1012   {
1013     mImpl->mEventData->mUpdateCursorPosition = true;
1014     mImpl->mEventData->mScrollAfterUpdatePosition = true;
1015   }
1016 }
1017
1018 void Controller::TextDeletedEvent()
1019 {
1020   DALI_ASSERT_DEBUG( NULL != mImpl->mEventData && "Unexpected TextDeletedEvent" );
1021
1022   // TODO - Optimize this
1023   ClearModelData();
1024
1025   // The natural size needs to be re-calculated.
1026   mImpl->mRecalculateNaturalSize = true;
1027
1028   // Apply modifications to the model; TODO - Optimize this
1029   mImpl->mOperationsPending = ALL_OPERATIONS;
1030   mImpl->UpdateModel( ALL_OPERATIONS );
1031   mImpl->mOperationsPending = static_cast<OperationsMask>( LAYOUT             |
1032                                                            ALIGN              |
1033                                                            UPDATE_ACTUAL_SIZE |
1034                                                            REORDER );
1035
1036   // Queue a cursor reposition event; this must wait until after DoRelayout()
1037   mImpl->mEventData->mUpdateCursorPosition = true;
1038   if( 0u != mImpl->mLogicalModel->mText.Count() )
1039   {
1040     mImpl->mEventData->mScrollAfterDelete = true;
1041   }
1042 }
1043
1044 bool Controller::DoRelayout( const Size& size,
1045                              OperationsMask operationsRequired,
1046                              Size& layoutSize )
1047 {
1048   DALI_LOG_INFO( gLogFilter, Debug::Verbose, "-->Controller::DoRelayout %p size %f,%f\n", this, size.width, size.height );
1049   bool viewUpdated( false );
1050
1051   // Calculate the operations to be done.
1052   const OperationsMask operations = static_cast<OperationsMask>( mImpl->mOperationsPending & operationsRequired );
1053
1054   if( LAYOUT & operations )
1055   {
1056     // Some vectors with data needed to layout and reorder may be void
1057     // after the first time the text has been laid out.
1058     // Fill the vectors again.
1059
1060     const Length numberOfGlyphs = mImpl->mVisualModel->mGlyphs.Count();
1061
1062     if( 0u == numberOfGlyphs )
1063     {
1064       // Nothing else to do if there is no glyphs.
1065       DALI_LOG_INFO( gLogFilter, Debug::Verbose, "<--Controller::DoRelayout no glyphs, view updated true\n" );
1066       return true;
1067     }
1068
1069     const Vector<LineBreakInfo>& lineBreakInfo = mImpl->mLogicalModel->mLineBreakInfo;
1070     const Vector<WordBreakInfo>& wordBreakInfo = mImpl->mLogicalModel->mWordBreakInfo;
1071     const Vector<CharacterDirection>& characterDirection = mImpl->mLogicalModel->mCharacterDirections;
1072     const Vector<GlyphInfo>& glyphs = mImpl->mVisualModel->mGlyphs;
1073     const Vector<CharacterIndex>& glyphsToCharactersMap = mImpl->mVisualModel->mGlyphsToCharacters;
1074     const Vector<Length>& charactersPerGlyph = mImpl->mVisualModel->mCharactersPerGlyph;
1075     const Character* const textBuffer = mImpl->mLogicalModel->mText.Begin();
1076
1077     // Set the layout parameters.
1078     LayoutParameters layoutParameters( size,
1079                                        textBuffer,
1080                                        lineBreakInfo.Begin(),
1081                                        wordBreakInfo.Begin(),
1082                                        ( 0u != characterDirection.Count() ) ? characterDirection.Begin() : NULL,
1083                                        numberOfGlyphs,
1084                                        glyphs.Begin(),
1085                                        glyphsToCharactersMap.Begin(),
1086                                        charactersPerGlyph.Begin() );
1087
1088     // The laid-out lines.
1089     // It's not possible to know in how many lines the text is going to be laid-out,
1090     // but it can be resized at least with the number of 'paragraphs' to avoid
1091     // some re-allocations.
1092     Vector<LineRun>& lines = mImpl->mVisualModel->mLines;
1093
1094     // Delete any previous laid out lines before setting the new ones.
1095     lines.Clear();
1096
1097     // The capacity of the bidirectional paragraph info is the number of paragraphs.
1098     lines.Reserve( mImpl->mLogicalModel->mBidirectionalParagraphInfo.Capacity() );
1099
1100     // Resize the vector of positions to have the same size than the vector of glyphs.
1101     Vector<Vector2>& glyphPositions = mImpl->mVisualModel->mGlyphPositions;
1102     glyphPositions.Resize( numberOfGlyphs );
1103
1104     // Whether the last character is a new paragraph character.
1105     layoutParameters.isLastNewParagraph = TextAbstraction::IsNewParagraph( *( textBuffer + ( mImpl->mLogicalModel->mText.Count() - 1u ) ) );
1106
1107     // Update the visual model.
1108     viewUpdated = mImpl->mLayoutEngine.LayoutText( layoutParameters,
1109                                                    glyphPositions,
1110                                                    lines,
1111                                                    layoutSize );
1112
1113     if( viewUpdated )
1114     {
1115       // Reorder the lines
1116       if( REORDER & operations )
1117       {
1118         Vector<BidirectionalParagraphInfoRun>& bidirectionalInfo = mImpl->mLogicalModel->mBidirectionalParagraphInfo;
1119
1120         // Check first if there are paragraphs with bidirectional info.
1121         if( 0u != bidirectionalInfo.Count() )
1122         {
1123           // Get the lines
1124           const Length numberOfLines = mImpl->mVisualModel->mLines.Count();
1125
1126           // Reorder the lines.
1127           Vector<BidirectionalLineInfoRun> lineBidirectionalInfoRuns;
1128           lineBidirectionalInfoRuns.Reserve( numberOfLines ); // Reserve because is not known yet how many lines have right to left characters.
1129           ReorderLines( bidirectionalInfo,
1130                         lines,
1131                         lineBidirectionalInfoRuns );
1132
1133           // Set the bidirectional info into the model.
1134           const Length numberOfBidirectionalInfoRuns = lineBidirectionalInfoRuns.Count();
1135           mImpl->mLogicalModel->SetVisualToLogicalMap( lineBidirectionalInfoRuns.Begin(),
1136                                                        numberOfBidirectionalInfoRuns );
1137
1138           // Set the bidirectional info per line into the layout parameters.
1139           layoutParameters.lineBidirectionalInfoRunsBuffer = lineBidirectionalInfoRuns.Begin();
1140           layoutParameters.numberOfBidirectionalInfoRuns = numberOfBidirectionalInfoRuns;
1141
1142           // Get the character to glyph conversion table and set into the layout.
1143           layoutParameters.charactersToGlyphsBuffer = mImpl->mVisualModel->mCharactersToGlyph.Begin();
1144
1145           // Get the glyphs per character table and set into the layout.
1146           layoutParameters.glyphsPerCharacterBuffer = mImpl->mVisualModel->mGlyphsPerCharacter.Begin();
1147
1148           // Re-layout the text. Reorder those lines with right to left characters.
1149           mImpl->mLayoutEngine.ReLayoutRightToLeftLines( layoutParameters,
1150                                                          glyphPositions );
1151
1152           // Free the allocated memory used to store the conversion table in the bidirectional line info run.
1153           for( Vector<BidirectionalLineInfoRun>::Iterator it = lineBidirectionalInfoRuns.Begin(),
1154                  endIt = lineBidirectionalInfoRuns.End();
1155                it != endIt;
1156                ++it )
1157           {
1158             BidirectionalLineInfoRun& bidiLineInfo = *it;
1159
1160             free( bidiLineInfo.visualToLogicalMap );
1161           }
1162         }
1163       } // REORDER
1164
1165       // Sets the actual size.
1166       if( UPDATE_ACTUAL_SIZE & operations )
1167       {
1168         mImpl->mVisualModel->SetActualSize( layoutSize );
1169       }
1170     } // view updated
1171   }
1172   else
1173   {
1174     layoutSize = mImpl->mVisualModel->GetActualSize();
1175   }
1176
1177   if( ALIGN & operations )
1178   {
1179     // The laid-out lines.
1180     Vector<LineRun>& lines = mImpl->mVisualModel->mLines;
1181
1182     mImpl->mLayoutEngine.Align( layoutSize,
1183                                 lines );
1184
1185     viewUpdated = true;
1186   }
1187
1188   DALI_LOG_INFO( gLogFilter, Debug::Verbose, "<--Controller::DoRelayout, view updated %s\n", ( viewUpdated ? "true" : "false" ) );
1189   return viewUpdated;
1190 }
1191
1192 void Controller::SetMultiLineEnabled( bool enable )
1193 {
1194   const LayoutEngine::Layout layout = enable ? LayoutEngine::MULTI_LINE_BOX : LayoutEngine::SINGLE_LINE_BOX;
1195
1196   if( layout != mImpl->mLayoutEngine.GetLayout() )
1197   {
1198     // Set the layout type.
1199     mImpl->mLayoutEngine.SetLayout( layout );
1200
1201     // Set the flags to redo the layout operations
1202     const OperationsMask layoutOperations =  static_cast<OperationsMask>( LAYOUT             |
1203                                                                           UPDATE_ACTUAL_SIZE |
1204                                                                           ALIGN              |
1205                                                                           REORDER );
1206
1207     mImpl->mOperationsPending = static_cast<OperationsMask>( mImpl->mOperationsPending | layoutOperations );
1208
1209     mImpl->RequestRelayout();
1210   }
1211 }
1212
1213 bool Controller::IsMultiLineEnabled() const
1214 {
1215   return LayoutEngine::MULTI_LINE_BOX == mImpl->mLayoutEngine.GetLayout();
1216 }
1217
1218 void Controller::SetHorizontalAlignment( LayoutEngine::HorizontalAlignment alignment )
1219 {
1220   if( alignment != mImpl->mLayoutEngine.GetHorizontalAlignment() )
1221   {
1222     // Set the alignment.
1223     mImpl->mLayoutEngine.SetHorizontalAlignment( alignment );
1224
1225     // Set the flag to redo the alignment operation.
1226     mImpl->mOperationsPending = static_cast<OperationsMask>( mImpl->mOperationsPending | ALIGN );
1227
1228     mImpl->RequestRelayout();
1229   }
1230 }
1231
1232 LayoutEngine::HorizontalAlignment Controller::GetHorizontalAlignment() const
1233 {
1234   return mImpl->mLayoutEngine.GetHorizontalAlignment();
1235 }
1236
1237 void Controller::SetVerticalAlignment( LayoutEngine::VerticalAlignment alignment )
1238 {
1239   if( alignment != mImpl->mLayoutEngine.GetVerticalAlignment() )
1240   {
1241     // Set the alignment.
1242     mImpl->mLayoutEngine.SetVerticalAlignment( alignment );
1243
1244     mImpl->mOperationsPending = static_cast<OperationsMask>( mImpl->mOperationsPending | ALIGN );
1245
1246     mImpl->RequestRelayout();
1247   }
1248 }
1249
1250 LayoutEngine::VerticalAlignment Controller::GetVerticalAlignment() const
1251 {
1252   return mImpl->mLayoutEngine.GetVerticalAlignment();
1253 }
1254
1255 void Controller::CalculateTextAlignment( const Size& size )
1256 {
1257   // Get the direction of the first character.
1258   const CharacterDirection firstParagraphDirection = mImpl->mLogicalModel->GetCharacterDirection( 0u );
1259
1260   Size actualSize = mImpl->mVisualModel->GetActualSize();
1261   if( fabsf( actualSize.height ) < Math::MACHINE_EPSILON_1000 )
1262   {
1263     // Get the line height of the default font.
1264     actualSize.height = mImpl->GetDefaultFontLineHeight();
1265   }
1266
1267   // If the first paragraph is right to left swap ALIGN_BEGIN and ALIGN_END;
1268   LayoutEngine::HorizontalAlignment horizontalAlignment = mImpl->mLayoutEngine.GetHorizontalAlignment();
1269   if( firstParagraphDirection &&
1270       ( LayoutEngine::HORIZONTAL_ALIGN_CENTER != horizontalAlignment ) )
1271   {
1272     if( LayoutEngine::HORIZONTAL_ALIGN_BEGIN == horizontalAlignment )
1273     {
1274       horizontalAlignment = LayoutEngine::HORIZONTAL_ALIGN_END;
1275     }
1276     else
1277     {
1278       horizontalAlignment = LayoutEngine::HORIZONTAL_ALIGN_BEGIN;
1279     }
1280   }
1281
1282   switch( horizontalAlignment )
1283   {
1284     case LayoutEngine::HORIZONTAL_ALIGN_BEGIN:
1285     {
1286       mImpl->mAlignmentOffset.x = 0.f;
1287       break;
1288     }
1289     case LayoutEngine::HORIZONTAL_ALIGN_CENTER:
1290     {
1291       mImpl->mAlignmentOffset.x = floorf( 0.5f * ( size.width - actualSize.width ) ); // try to avoid pixel alignment.
1292       break;
1293     }
1294     case LayoutEngine::HORIZONTAL_ALIGN_END:
1295     {
1296       mImpl->mAlignmentOffset.x = size.width - actualSize.width;
1297       break;
1298     }
1299   }
1300
1301   const LayoutEngine::VerticalAlignment verticalAlignment = mImpl->mLayoutEngine.GetVerticalAlignment();
1302   switch( verticalAlignment )
1303   {
1304     case LayoutEngine::VERTICAL_ALIGN_TOP:
1305     {
1306       mImpl->mAlignmentOffset.y = 0.f;
1307       break;
1308     }
1309     case LayoutEngine::VERTICAL_ALIGN_CENTER:
1310     {
1311       mImpl->mAlignmentOffset.y = floorf( 0.5f * ( size.height - actualSize.height ) ); // try to avoid pixel alignment.
1312       break;
1313     }
1314     case LayoutEngine::VERTICAL_ALIGN_BOTTOM:
1315     {
1316       mImpl->mAlignmentOffset.y = size.height - actualSize.height;
1317       break;
1318     }
1319   }
1320 }
1321
1322 LayoutEngine& Controller::GetLayoutEngine()
1323 {
1324   return mImpl->mLayoutEngine;
1325 }
1326
1327 View& Controller::GetView()
1328 {
1329   return mImpl->mView;
1330 }
1331
1332 void Controller::KeyboardFocusGainEvent()
1333 {
1334   DALI_ASSERT_DEBUG( mImpl->mEventData && "Unexpected KeyboardFocusGainEvent" );
1335
1336   if( mImpl->mEventData )
1337   {
1338     if( ( EventData::INACTIVE == mImpl->mEventData->mState ) ||
1339         ( EventData::INTERRUPTED == mImpl->mEventData->mState ) )
1340     {
1341       mImpl->ChangeState( EventData::EDITING );
1342       mImpl->mEventData->mUpdateCursorPosition = true; //If editing started without tap event, cursor update must be triggered.
1343     }
1344
1345     if( mImpl->IsShowingPlaceholderText() )
1346     {
1347       // Show alternative placeholder-text when editing
1348       ShowPlaceholderText();
1349     }
1350
1351     mImpl->RequestRelayout();
1352   }
1353 }
1354
1355 void Controller::KeyboardFocusLostEvent()
1356 {
1357   DALI_ASSERT_DEBUG( mImpl->mEventData && "Unexpected KeyboardFocusLostEvent" );
1358
1359   if( mImpl->mEventData )
1360   {
1361     if ( EventData::INTERRUPTED != mImpl->mEventData->mState )
1362     {
1363       mImpl->ChangeState( EventData::INACTIVE );
1364
1365       if( !mImpl->IsShowingRealText() )
1366       {
1367         // Revert to regular placeholder-text when not editing
1368         ShowPlaceholderText();
1369       }
1370     }
1371   }
1372   mImpl->RequestRelayout();
1373 }
1374
1375 bool Controller::KeyEvent( const Dali::KeyEvent& keyEvent )
1376 {
1377   DALI_ASSERT_DEBUG( mImpl->mEventData && "Unexpected KeyEvent" );
1378
1379   bool textChanged( false );
1380
1381   if( mImpl->mEventData &&
1382       keyEvent.state == KeyEvent::Down )
1383   {
1384     int keyCode = keyEvent.keyCode;
1385     const std::string& keyString = keyEvent.keyPressed;
1386
1387     // Pre-process to separate modifying events from non-modifying input events.
1388     if( Dali::DALI_KEY_ESCAPE == keyCode )
1389     {
1390       // Escape key is a special case which causes focus loss
1391       KeyboardFocusLostEvent();
1392     }
1393     else if( Dali::DALI_KEY_CURSOR_LEFT  == keyCode ||
1394              Dali::DALI_KEY_CURSOR_RIGHT == keyCode ||
1395              Dali::DALI_KEY_CURSOR_UP    == keyCode ||
1396              Dali::DALI_KEY_CURSOR_DOWN  == keyCode )
1397     {
1398       Event event( Event::CURSOR_KEY_EVENT );
1399       event.p1.mInt = keyCode;
1400       mImpl->mEventData->mEventQueue.push_back( event );
1401     }
1402     else if( Dali::DALI_KEY_BACKSPACE == keyCode )
1403     {
1404       textChanged = BackspaceKeyEvent();
1405     }
1406     else if ( IsKey( keyEvent,  Dali::DALI_KEY_POWER ) )
1407     {
1408       mImpl->ChangeState( EventData::INTERRUPTED ); // State is not INACTIVE as expect to return to edit mode.
1409       // Avoids calling the InsertText() method which can delete selected text
1410     }
1411     else if ( IsKey( keyEvent, Dali::DALI_KEY_MENU ) ||
1412               IsKey( keyEvent, Dali::DALI_KEY_HOME ) )
1413     {
1414       mImpl->ChangeState( EventData::INACTIVE );
1415       // Menu/Home key behaviour does not allow edit mode to resume like Power key
1416       // Avoids calling the InsertText() method which can delete selected text
1417     }
1418     else if( Dali::DALI_KEY_SHIFT_LEFT == keyCode )
1419     {
1420       // DALI_KEY_SHIFT_LEFT is the key code for the Left Shift. It's sent (by the imf?) when the predictive text is enabled
1421       // and a character is typed after the type of a upper case latin character.
1422
1423       // Do nothing.
1424     }
1425     else
1426     {
1427       DALI_LOG_INFO( gLogFilter, Debug::Verbose, "Controller::KeyEvent %p keyString %s\n", this, keyString.c_str() );
1428
1429       // IMF manager is no longer handling key-events
1430       mImpl->ClearPreEditFlag();
1431
1432       InsertText( keyString, COMMIT );
1433       textChanged = true;
1434     }
1435
1436     if ( ( mImpl->mEventData->mState != EventData::INTERRUPTED ) &&
1437          ( mImpl->mEventData->mState != EventData::INACTIVE ) )
1438     {
1439       mImpl->ChangeState( EventData::EDITING );
1440     }
1441
1442     mImpl->RequestRelayout();
1443   }
1444
1445   if( textChanged )
1446   {
1447     // Do this last since it provides callbacks into application code
1448     mImpl->mControlInterface.TextChanged();
1449   }
1450
1451   return false;
1452 }
1453
1454 void Controller::InsertText( const std::string& text, Controller::InsertType type )
1455 {
1456   bool removedPrevious( false );
1457   bool maxLengthReached( false );
1458
1459   DALI_ASSERT_DEBUG( NULL != mImpl->mEventData && "Unexpected InsertText" )
1460   DALI_LOG_INFO( gLogFilter, Debug::Verbose, "Controller::InsertText %p %s (%s) mPrimaryCursorPosition %d mPreEditFlag %d mPreEditStartPosition %d mPreEditLength %d\n",
1461                  this, text.c_str(), (COMMIT == type ? "COMMIT" : "PRE_EDIT"),
1462                  mImpl->mEventData->mPrimaryCursorPosition, mImpl->mEventData->mPreEditFlag, mImpl->mEventData->mPreEditStartPosition, mImpl->mEventData->mPreEditLength );
1463
1464   // TODO: At the moment the underline runs are only for pre-edit.
1465   mImpl->mVisualModel->mUnderlineRuns.Clear();
1466
1467   Vector<Character> utf32Characters;
1468   Length characterCount( 0u );
1469
1470   // Remove the previous IMF pre-edit (predicitive text)
1471   if( mImpl->mEventData &&
1472       mImpl->mEventData->mPreEditFlag &&
1473       0 != mImpl->mEventData->mPreEditLength )
1474   {
1475     CharacterIndex offset = mImpl->mEventData->mPrimaryCursorPosition - mImpl->mEventData->mPreEditStartPosition;
1476
1477     removedPrevious = RemoveText( -static_cast<int>(offset), mImpl->mEventData->mPreEditLength );
1478
1479     mImpl->mEventData->mPrimaryCursorPosition = mImpl->mEventData->mPreEditStartPosition;
1480     mImpl->mEventData->mPreEditLength = 0;
1481   }
1482   else
1483   {
1484     // Remove the previous Selection
1485     removedPrevious = RemoveSelectedText();
1486   }
1487
1488   if( !text.empty() )
1489   {
1490     //  Convert text into UTF-32
1491     utf32Characters.Resize( text.size() );
1492
1493     // This is a bit horrible but std::string returns a (signed) char*
1494     const uint8_t* utf8 = reinterpret_cast<const uint8_t*>( text.c_str() );
1495
1496     // Transform a text array encoded in utf8 into an array encoded in utf32.
1497     // It returns the actual number of characters.
1498     characterCount = Utf8ToUtf32( utf8, text.size(), utf32Characters.Begin() );
1499     utf32Characters.Resize( characterCount );
1500
1501     DALI_ASSERT_DEBUG( text.size() >= utf32Characters.Count() && "Invalid UTF32 conversion length" );
1502     DALI_LOG_INFO( gLogFilter, Debug::Verbose, "UTF8 size %d, UTF32 size %d\n", text.size(), utf32Characters.Count() );
1503   }
1504
1505   if( 0u != utf32Characters.Count() ) // Check if Utf8ToUtf32 conversion succeeded
1506   {
1507     // The placeholder text is no longer needed
1508     if( mImpl->IsShowingPlaceholderText() )
1509     {
1510       ResetText();
1511     }
1512
1513     mImpl->ChangeState( EventData::EDITING );
1514
1515     // Handle the IMF (predicitive text) state changes
1516     if( mImpl->mEventData )
1517     {
1518       if( COMMIT == type )
1519       {
1520         // IMF manager is no longer handling key-events
1521         mImpl->ClearPreEditFlag();
1522       }
1523       else // PRE_EDIT
1524       {
1525         if( !mImpl->mEventData->mPreEditFlag )
1526         {
1527           DALI_LOG_INFO( gLogFilter, Debug::Verbose, "Entered PreEdit state" );
1528
1529           // Record the start of the pre-edit text
1530           mImpl->mEventData->mPreEditStartPosition = mImpl->mEventData->mPrimaryCursorPosition;
1531         }
1532
1533         mImpl->mEventData->mPreEditLength = utf32Characters.Count();
1534         mImpl->mEventData->mPreEditFlag = true;
1535
1536         DALI_LOG_INFO( gLogFilter, Debug::Verbose, "mPreEditStartPosition %d mPreEditLength %d\n", mImpl->mEventData->mPreEditStartPosition, mImpl->mEventData->mPreEditLength );
1537       }
1538     }
1539
1540     const Length numberOfCharactersInModel = mImpl->mLogicalModel->mText.Count();
1541
1542     // Restrict new text to fit within Maximum characters setting
1543     Length maxSizeOfNewText = std::min ( ( mImpl->mMaximumNumberOfCharacters - numberOfCharactersInModel ), characterCount );
1544     maxLengthReached = ( characterCount > maxSizeOfNewText );
1545
1546     // The cursor position.
1547     CharacterIndex& cursorIndex = mImpl->mEventData->mPrimaryCursorPosition;
1548
1549     // Update the text's style.
1550     if( mImpl->mEventData )
1551     {
1552       // Updates the text style runs.
1553       mImpl->mLogicalModel->UpdateTextStyleRuns( cursorIndex, maxSizeOfNewText );
1554
1555       // Get the character index from the cursor index.
1556       const CharacterIndex styleIndex = ( cursorIndex > 0u ) ? cursorIndex - 1u : 0u;
1557
1558       // Retrieve the text's style for the given index.
1559       InputStyle style;
1560       mImpl->mLogicalModel->RetrieveStyle( styleIndex, style );
1561
1562       // Whether to add a new text color run.
1563       const bool addColorRun = style.textColor != mImpl->mEventData->mInputStyle.textColor;
1564
1565       // Add style runs.
1566       if( addColorRun )
1567       {
1568         const VectorBase::SizeType numberOfRuns = mImpl->mLogicalModel->mColorRuns.Count();
1569         mImpl->mLogicalModel->mColorRuns.Resize( numberOfRuns + 1u );
1570
1571         ColorRun& colorRun = *( mImpl->mLogicalModel->mColorRuns.Begin() + numberOfRuns );
1572         colorRun.color = mImpl->mEventData->mInputStyle.textColor;
1573         colorRun.characterRun.characterIndex = cursorIndex;
1574         colorRun.characterRun.numberOfCharacters = maxSizeOfNewText;
1575       }
1576     }
1577
1578     // Insert at current cursor position.
1579     Vector<Character>& modifyText = mImpl->mLogicalModel->mText;
1580
1581     if( cursorIndex < numberOfCharactersInModel )
1582     {
1583       modifyText.Insert( modifyText.Begin() + cursorIndex, utf32Characters.Begin(), utf32Characters.Begin() + maxSizeOfNewText );
1584     }
1585     else
1586     {
1587       modifyText.Insert( modifyText.End(), utf32Characters.Begin(), utf32Characters.Begin() + maxSizeOfNewText );
1588     }
1589
1590     cursorIndex += maxSizeOfNewText;
1591
1592     DALI_LOG_INFO( gLogFilter, Debug::Verbose, "Inserted %d characters, new size %d new cursor %d\n", maxSizeOfNewText, mImpl->mLogicalModel->mText.Count(), mImpl->mEventData->mPrimaryCursorPosition );
1593   }
1594
1595   if( 0u == mImpl->mLogicalModel->mText.Count() &&
1596       mImpl->IsPlaceholderAvailable() )
1597   {
1598     // Show place-holder if empty after removing the pre-edit text
1599     ShowPlaceholderText();
1600     mImpl->mEventData->mUpdateCursorPosition = true;
1601     mImpl->ClearPreEditFlag();
1602   }
1603   else if( removedPrevious ||
1604            0 != utf32Characters.Count() )
1605   {
1606     // Queue an inserted event
1607     mImpl->QueueModifyEvent( ModifyEvent::TEXT_INSERTED );
1608   }
1609
1610   if( maxLengthReached )
1611   {
1612     DALI_LOG_INFO( gLogFilter, Debug::Verbose, "MaxLengthReached (%d)\n", mImpl->mLogicalModel->mText.Count() );
1613
1614     mImpl->ResetImfManager();
1615
1616     // Do this last since it provides callbacks into application code
1617     mImpl->mControlInterface.MaxLengthReached();
1618   }
1619 }
1620
1621 bool Controller::RemoveSelectedText()
1622 {
1623   bool textRemoved( false );
1624
1625   if( EventData::SELECTING == mImpl->mEventData->mState )
1626   {
1627     std::string removedString;
1628     mImpl->RetrieveSelection( removedString, true );
1629
1630     if( !removedString.empty() )
1631     {
1632       textRemoved = true;
1633       mImpl->ChangeState( EventData::EDITING );
1634     }
1635   }
1636
1637   return textRemoved;
1638 }
1639
1640 void Controller::TapEvent( unsigned int tapCount, float x, float y )
1641 {
1642   DALI_ASSERT_DEBUG( mImpl->mEventData && "Unexpected TapEvent" );
1643
1644   if( NULL != mImpl->mEventData )
1645   {
1646     DALI_LOG_INFO( gLogFilter, Debug::Concise, "TapEvent state:%d \n", mImpl->mEventData->mState );
1647
1648     if( 1u == tapCount )
1649     {
1650       // This is to avoid unnecessary relayouts when tapping an empty text-field
1651       bool relayoutNeeded( false );
1652
1653       if ( EventData::EDITING_WITH_PASTE_POPUP == mImpl->mEventData->mState || EventData::EDITING_WITH_PASTE_POPUP == mImpl->mEventData->mState )
1654       {
1655         mImpl->ChangeState( EventData::EDITING_WITH_GRAB_HANDLE);  // If Popup shown hide it here so can be shown again if required.
1656       }
1657
1658       if( mImpl->IsShowingRealText() && ( EventData::INACTIVE !=  mImpl->mEventData->mState ) )
1659       {
1660         // Already in an active state so show a popup
1661         if ( !mImpl->IsClipboardEmpty() )
1662         {
1663           // Shows Paste popup but could show full popup with Selection options. ( EDITING_WITH_POPUP )
1664           mImpl->ChangeState( EventData::EDITING_WITH_PASTE_POPUP );
1665         }
1666         else
1667         {
1668           mImpl->ChangeState( EventData::EDITING_WITH_GRAB_HANDLE );
1669         }
1670         relayoutNeeded = true;
1671       }
1672       else
1673       {
1674         if( mImpl->IsShowingPlaceholderText() &&  !mImpl->IsFocusedPlaceholderAvailable() )
1675         {
1676           // Hide placeholder text
1677           ResetText();
1678         }
1679
1680         if ( EventData::INACTIVE == mImpl->mEventData->mState )
1681         {
1682           mImpl->ChangeState( EventData::EDITING );
1683         }
1684         else if ( !mImpl->IsClipboardEmpty() )
1685         {
1686           mImpl->ChangeState( EventData::EDITING_WITH_POPUP );
1687         }
1688         relayoutNeeded = true;
1689       }
1690
1691       // Handles & cursors must be repositioned after Relayout() i.e. after the Model has been updated
1692       if( relayoutNeeded )
1693       {
1694         Event event( Event::TAP_EVENT );
1695         event.p1.mUint = tapCount;
1696         event.p2.mFloat = x;
1697         event.p3.mFloat = y;
1698         mImpl->mEventData->mEventQueue.push_back( event );
1699
1700         mImpl->RequestRelayout();
1701       }
1702     }
1703     else if( 2u == tapCount )
1704     {
1705       if( mImpl->mEventData->mSelectionEnabled &&
1706           mImpl->IsShowingRealText() )
1707       {
1708         SelectEvent( x, y, false );
1709       }
1710     }
1711   }
1712
1713   // Reset keyboard as tap event has occurred.
1714   mImpl->ResetImfManager();
1715 }
1716
1717 void Controller::PanEvent( Gesture::State state, const Vector2& displacement )
1718         // Show cursor and grabhandle on first tap, this matches the behaviour of tapping when already editing
1719 {
1720   DALI_ASSERT_DEBUG( mImpl->mEventData && "Unexpected PanEvent" );
1721
1722   if( mImpl->mEventData )
1723   {
1724     Event event( Event::PAN_EVENT );
1725     event.p1.mInt = state;
1726     event.p2.mFloat = displacement.x;
1727     event.p3.mFloat = displacement.y;
1728     mImpl->mEventData->mEventQueue.push_back( event );
1729
1730     mImpl->RequestRelayout();
1731   }
1732 }
1733
1734 void Controller::LongPressEvent( Gesture::State state, float x, float y  )
1735 {
1736   DALI_ASSERT_DEBUG( mImpl->mEventData && "Unexpected LongPressEvent" );
1737
1738   if( state == Gesture::Started &&
1739       mImpl->mEventData )
1740   {
1741     if( ! mImpl->IsShowingRealText() )
1742     {
1743       Event event( Event::LONG_PRESS_EVENT );
1744       event.p1.mInt = state;
1745       mImpl->mEventData->mEventQueue.push_back( event );
1746       mImpl->RequestRelayout();
1747     }
1748     else
1749     {
1750       // The 1st long-press on inactive text-field is treated as tap
1751       if( EventData::INACTIVE == mImpl->mEventData->mState )
1752       {
1753         mImpl->ChangeState( EventData::EDITING );
1754
1755         Event event( Event::TAP_EVENT );
1756         event.p1.mUint = 1;
1757         event.p2.mFloat = x;
1758         event.p3.mFloat = y;
1759         mImpl->mEventData->mEventQueue.push_back( event );
1760
1761         mImpl->RequestRelayout();
1762       }
1763       else
1764       {
1765         // Reset the imf manger to commit the pre-edit before selecting the text.
1766         mImpl->ResetImfManager();
1767
1768         SelectEvent( x, y, false );
1769       }
1770     }
1771   }
1772 }
1773
1774 void Controller::SelectEvent( float x, float y, bool selectAll )
1775 {
1776   DALI_LOG_INFO( gLogFilter, Debug::Verbose, "Controller::SelectEvent\n" );
1777
1778   if( mImpl->mEventData )
1779   {
1780     mImpl->ChangeState( EventData::SELECTING );
1781
1782     if( selectAll )
1783     {
1784       Event event( Event::SELECT_ALL );
1785       mImpl->mEventData->mEventQueue.push_back( event );
1786     }
1787     else
1788     {
1789       Event event( Event::SELECT );
1790       event.p2.mFloat = x;
1791       event.p3.mFloat = y;
1792       mImpl->mEventData->mEventQueue.push_back( event );
1793     }
1794
1795     mImpl->RequestRelayout();
1796   }
1797 }
1798
1799 void Controller::GetTargetSize( Vector2& targetSize )
1800 {
1801   targetSize = mImpl->mVisualModel->mControlSize;
1802 }
1803
1804 void Controller::AddDecoration( Actor& actor, bool needsClipping )
1805 {
1806   mImpl->mControlInterface.AddDecoration( actor, needsClipping );
1807 }
1808
1809 void Controller::DecorationEvent( HandleType handleType, HandleState state, float x, float y )
1810 {
1811   DALI_ASSERT_DEBUG( mImpl->mEventData && "Unexpected DecorationEvent" );
1812
1813   if( mImpl->mEventData )
1814   {
1815     switch( handleType )
1816     {
1817       case GRAB_HANDLE:
1818       {
1819         Event event( Event::GRAB_HANDLE_EVENT );
1820         event.p1.mUint  = state;
1821         event.p2.mFloat = x;
1822         event.p3.mFloat = y;
1823
1824         mImpl->mEventData->mEventQueue.push_back( event );
1825         break;
1826       }
1827       case LEFT_SELECTION_HANDLE:
1828       {
1829         Event event( Event::LEFT_SELECTION_HANDLE_EVENT );
1830         event.p1.mUint  = state;
1831         event.p2.mFloat = x;
1832         event.p3.mFloat = y;
1833
1834         mImpl->mEventData->mEventQueue.push_back( event );
1835         break;
1836       }
1837       case RIGHT_SELECTION_HANDLE:
1838       {
1839         Event event( Event::RIGHT_SELECTION_HANDLE_EVENT );
1840         event.p1.mUint  = state;
1841         event.p2.mFloat = x;
1842         event.p3.mFloat = y;
1843
1844         mImpl->mEventData->mEventQueue.push_back( event );
1845         break;
1846       }
1847       case LEFT_SELECTION_HANDLE_MARKER:
1848       case RIGHT_SELECTION_HANDLE_MARKER:
1849       {
1850         // Markers do not move the handles.
1851         break;
1852       }
1853       case HANDLE_TYPE_COUNT:
1854       {
1855         DALI_ASSERT_DEBUG( !"Controller::HandleEvent. Unexpected handle type" );
1856       }
1857     }
1858
1859     mImpl->RequestRelayout();
1860   }
1861 }
1862
1863 void Controller::PasteText( const std::string& stringToPaste )
1864 {
1865   InsertText( stringToPaste, Text::Controller::COMMIT );
1866   mImpl->ChangeState( EventData::EDITING );
1867   mImpl->RequestRelayout();
1868
1869   // Do this last since it provides callbacks into application code
1870   mImpl->mControlInterface.TextChanged();
1871 }
1872
1873 void Controller::PasteClipboardItemEvent()
1874 {
1875   // Retrieve the clipboard contents first
1876   ClipboardEventNotifier notifier( ClipboardEventNotifier::Get() );
1877   std::string stringToPaste( notifier.GetContent() );
1878
1879   // Commit the current pre-edit text; the contents of the clipboard should be appended
1880   mImpl->ResetImfManager();
1881
1882   // Paste
1883   PasteText( stringToPaste );
1884 }
1885
1886 void Controller::TextPopupButtonTouched( Dali::Toolkit::TextSelectionPopup::Buttons button )
1887 {
1888   if( NULL == mImpl->mEventData )
1889   {
1890     return;
1891   }
1892
1893   switch( button )
1894   {
1895     case Toolkit::TextSelectionPopup::CUT:
1896     {
1897       mImpl->SendSelectionToClipboard( true ); // Synchronous call to modify text
1898       mImpl->mOperationsPending = ALL_OPERATIONS;
1899
1900       // This is to reset the virtual keyboard to Upper-case
1901       if( 0u == mImpl->mLogicalModel->mText.Count() )
1902       {
1903         NotifyImfManager();
1904       }
1905
1906       if( 0u != mImpl->mLogicalModel->mText.Count() ||
1907           !mImpl->IsPlaceholderAvailable() )
1908       {
1909         mImpl->QueueModifyEvent( ModifyEvent::TEXT_DELETED );
1910       }
1911       else
1912       {
1913         ShowPlaceholderText();
1914         mImpl->mEventData->mUpdateCursorPosition = true;
1915       }
1916       mImpl->RequestRelayout();
1917       mImpl->mControlInterface.TextChanged();
1918       break;
1919     }
1920     case Toolkit::TextSelectionPopup::COPY:
1921     {
1922       mImpl->SendSelectionToClipboard( false ); // Text not modified
1923       mImpl->RequestRelayout(); // Handles, Selection Highlight, Popup
1924       break;
1925     }
1926     case Toolkit::TextSelectionPopup::PASTE:
1927     {
1928       std::string stringToPaste("");
1929       mImpl->GetTextFromClipboard( 0, stringToPaste ); // Paste latest item from system clipboard
1930       PasteText( stringToPaste );
1931       break;
1932     }
1933     case Toolkit::TextSelectionPopup::SELECT:
1934     {
1935       const Vector2& currentCursorPosition = mImpl->mEventData->mDecorator->GetPosition( PRIMARY_CURSOR );
1936
1937       if( mImpl->mEventData->mSelectionEnabled  )
1938       {
1939         // Creates a SELECT event.
1940         SelectEvent( currentCursorPosition.x, currentCursorPosition.y, false );
1941       }
1942       break;
1943     }
1944     case Toolkit::TextSelectionPopup::SELECT_ALL:
1945     {
1946       // Creates a SELECT_ALL event
1947       SelectEvent( 0.f, 0.f, true );
1948       break;
1949     }
1950     case Toolkit::TextSelectionPopup::CLIPBOARD:
1951     {
1952       mImpl->ShowClipboard();
1953       break;
1954     }
1955     case Toolkit::TextSelectionPopup::NONE:
1956     {
1957       // Nothing to do.
1958       break;
1959     }
1960   }
1961 }
1962
1963 ImfManager::ImfCallbackData Controller::OnImfEvent( ImfManager& imfManager, const ImfManager::ImfEventData& imfEvent )
1964 {
1965   bool update = false;
1966   bool requestRelayout = false;
1967
1968   std::string text;
1969   unsigned int cursorPosition( 0 );
1970
1971   switch ( imfEvent.eventName )
1972   {
1973     case ImfManager::COMMIT:
1974     {
1975       InsertText( imfEvent.predictiveString, Text::Controller::COMMIT );
1976       update=true;
1977       requestRelayout = true;
1978       break;
1979     }
1980     case ImfManager::PREEDIT:
1981     {
1982       InsertText( imfEvent.predictiveString, Text::Controller::PRE_EDIT );
1983       update = true;
1984       requestRelayout = true;
1985       break;
1986     }
1987     case ImfManager::DELETESURROUNDING:
1988     {
1989       update = RemoveText( imfEvent.cursorOffset, imfEvent.numberOfChars );
1990
1991       if( update )
1992       {
1993         if( 0u != mImpl->mLogicalModel->mText.Count() ||
1994             !mImpl->IsPlaceholderAvailable() )
1995         {
1996           mImpl->QueueModifyEvent( ModifyEvent::TEXT_DELETED );
1997         }
1998         else
1999         {
2000           ShowPlaceholderText();
2001           mImpl->mEventData->mUpdateCursorPosition = true;
2002         }
2003       }
2004       requestRelayout = true;
2005       break;
2006     }
2007     case ImfManager::GETSURROUNDING:
2008     {
2009       GetText( text );
2010       cursorPosition = GetLogicalCursorPosition();
2011
2012       imfManager.SetSurroundingText( text );
2013       imfManager.SetCursorPosition( cursorPosition );
2014       break;
2015     }
2016     case ImfManager::VOID:
2017     {
2018       // do nothing
2019       break;
2020     }
2021   } // end switch
2022
2023   if( ImfManager::GETSURROUNDING != imfEvent.eventName )
2024   {
2025     GetText( text );
2026     cursorPosition = GetLogicalCursorPosition();
2027   }
2028
2029   if( requestRelayout )
2030   {
2031     mImpl->mOperationsPending = ALL_OPERATIONS;
2032     mImpl->RequestRelayout();
2033
2034     // Do this last since it provides callbacks into application code
2035     mImpl->mControlInterface.TextChanged();
2036   }
2037
2038   ImfManager::ImfCallbackData callbackData( update, cursorPosition, text, false );
2039
2040   return callbackData;
2041 }
2042
2043 Controller::~Controller()
2044 {
2045   delete mImpl;
2046 }
2047
2048 bool Controller::BackspaceKeyEvent()
2049 {
2050   DALI_LOG_INFO( gLogFilter, Debug::Verbose, "Controller::KeyEvent %p DALI_KEY_BACKSPACE\n", this );
2051
2052   // IMF manager is no longer handling key-events
2053   mImpl->ClearPreEditFlag();
2054
2055   bool removed( false );
2056
2057   if( EventData::SELECTING == mImpl->mEventData->mState )
2058   {
2059     removed = RemoveSelectedText();
2060   }
2061   else if( mImpl->mEventData->mPrimaryCursorPosition > 0 )
2062   {
2063     // Remove the character before the current cursor position
2064     removed = RemoveText( -1, 1 );
2065   }
2066
2067   if( removed )
2068   {
2069     DALI_LOG_INFO( gLogFilter, Debug::Verbose, "Controller::KeyEvent %p DALI_KEY_BACKSPACE RemovedText\n", this );
2070     // Notifiy the IMF manager after text changed
2071     // Automatic  Upper-case and restarting prediction on an existing word require this.
2072     NotifyImfManager();
2073
2074     if( 0u != mImpl->mLogicalModel->mText.Count() ||
2075         !mImpl->IsPlaceholderAvailable() )
2076     {
2077       mImpl->QueueModifyEvent( ModifyEvent::TEXT_DELETED );
2078     }
2079     else
2080     {
2081       ShowPlaceholderText();
2082       mImpl->mEventData->mUpdateCursorPosition = true;
2083     }
2084   }
2085
2086   return removed;
2087 }
2088
2089 void Controller::NotifyImfManager()
2090 {
2091   if( mImpl->mEventData )
2092   {
2093     if( mImpl->mEventData->mImfManager )
2094     {
2095       // Notifying IMF of a cursor change triggers a surrounding text request so updating it now.
2096       std::string text;
2097       GetText( text );
2098       mImpl->mEventData->mImfManager.SetSurroundingText( text );
2099
2100       mImpl->mEventData->mImfManager.SetCursorPosition( GetLogicalCursorPosition() );
2101       mImpl->mEventData->mImfManager.NotifyCursorPosition();
2102     }
2103   }
2104 }
2105
2106 void Controller::ShowPlaceholderText()
2107 {
2108   if( mImpl->IsPlaceholderAvailable() )
2109   {
2110     DALI_ASSERT_DEBUG( mImpl->mEventData && "No placeholder text available" );
2111
2112     mImpl->mEventData->mIsShowingPlaceholderText = true;
2113
2114     // Disable handles when showing place-holder text
2115     mImpl->mEventData->mDecorator->SetHandleActive( GRAB_HANDLE, false );
2116     mImpl->mEventData->mDecorator->SetHandleActive( LEFT_SELECTION_HANDLE, false );
2117     mImpl->mEventData->mDecorator->SetHandleActive( RIGHT_SELECTION_HANDLE, false );
2118
2119     const char* text( NULL );
2120     size_t size( 0 );
2121
2122     // TODO - Switch placeholder text styles when changing state
2123     if( EventData::INACTIVE != mImpl->mEventData->mState &&
2124         0u != mImpl->mEventData->mPlaceholderTextActive.c_str() )
2125     {
2126       text = mImpl->mEventData->mPlaceholderTextActive.c_str();
2127       size = mImpl->mEventData->mPlaceholderTextActive.size();
2128     }
2129     else
2130     {
2131       text = mImpl->mEventData->mPlaceholderTextInactive.c_str();
2132       size = mImpl->mEventData->mPlaceholderTextInactive.size();
2133     }
2134
2135     // Reset model for showing placeholder.
2136     mImpl->mLogicalModel->mText.Clear();
2137     ClearModelData();
2138     mImpl->mVisualModel->SetTextColor( mImpl->mEventData->mPlaceholderTextColor );
2139
2140     // Convert text into UTF-32
2141     Vector<Character>& utf32Characters = mImpl->mLogicalModel->mText;
2142     utf32Characters.Resize( size );
2143
2144     // This is a bit horrible but std::string returns a (signed) char*
2145     const uint8_t* utf8 = reinterpret_cast<const uint8_t*>( text );
2146
2147     // Transform a text array encoded in utf8 into an array encoded in utf32.
2148     // It returns the actual number of characters.
2149     Length characterCount = Utf8ToUtf32( utf8, size, utf32Characters.Begin() );
2150     utf32Characters.Resize( characterCount );
2151
2152     // Reset the cursor position
2153     mImpl->mEventData->mPrimaryCursorPosition = 0;
2154
2155     // The natural size needs to be re-calculated.
2156     mImpl->mRecalculateNaturalSize = true;
2157
2158     // Apply modifications to the model
2159     mImpl->mOperationsPending = ALL_OPERATIONS;
2160
2161     // Update the rest of the model during size negotiation
2162     mImpl->QueueModifyEvent( ModifyEvent::TEXT_REPLACED );
2163   }
2164 }
2165
2166 void Controller::ClearModelData()
2167 {
2168   // n.b. This does not Clear the mText from mLogicalModel
2169   mImpl->mLogicalModel->mScriptRuns.Clear();
2170   mImpl->mLogicalModel->mFontRuns.Clear();
2171   mImpl->mLogicalModel->mLineBreakInfo.Clear();
2172   mImpl->mLogicalModel->mWordBreakInfo.Clear();
2173   mImpl->mLogicalModel->mBidirectionalParagraphInfo.Clear();
2174   mImpl->mLogicalModel->mCharacterDirections.Clear();
2175   mImpl->mLogicalModel->mBidirectionalLineInfo.Clear();
2176   mImpl->mLogicalModel->mLogicalToVisualMap.Clear();
2177   mImpl->mLogicalModel->mVisualToLogicalMap.Clear();
2178   mImpl->mVisualModel->mGlyphs.Clear();
2179   mImpl->mVisualModel->mGlyphsToCharacters.Clear();
2180   mImpl->mVisualModel->mCharactersToGlyph.Clear();
2181   mImpl->mVisualModel->mCharactersPerGlyph.Clear();
2182   mImpl->mVisualModel->mGlyphsPerCharacter.Clear();
2183   mImpl->mVisualModel->mGlyphPositions.Clear();
2184   mImpl->mVisualModel->mLines.Clear();
2185   mImpl->mVisualModel->mColorRuns.Clear();
2186   mImpl->mVisualModel->ClearCaches();
2187 }
2188
2189 void Controller::ClearFontData()
2190 {
2191   mImpl->mFontDefaults->mFontId = 0u; // Remove old font ID
2192   mImpl->mLogicalModel->mFontRuns.Clear();
2193   mImpl->mVisualModel->mGlyphs.Clear();
2194   mImpl->mVisualModel->mGlyphsToCharacters.Clear();
2195   mImpl->mVisualModel->mCharactersToGlyph.Clear();
2196   mImpl->mVisualModel->mCharactersPerGlyph.Clear();
2197   mImpl->mVisualModel->mGlyphsPerCharacter.Clear();
2198   mImpl->mVisualModel->mGlyphPositions.Clear();
2199   mImpl->mVisualModel->mLines.Clear();
2200   mImpl->mVisualModel->ClearCaches();
2201 }
2202
2203 void Controller::ClearStyleData()
2204 {
2205   mImpl->mLogicalModel->mColorRuns.Clear();
2206 }
2207
2208 Controller::Controller( ControlInterface& controlInterface )
2209 : mImpl( NULL )
2210 {
2211   mImpl = new Controller::Impl( controlInterface );
2212 }
2213
2214 } // namespace Text
2215
2216 } // namespace Toolkit
2217
2218 } // namespace Dali