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