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