e3b29bd1e36e9eb7026ce2bee72189ad7ee6c791
[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   if( mImpl->mEventData &&
685       0 != events.size() )
686   {
687     // When the text is being modified, delay cursor blinking
688     mImpl->mEventData->mDecorator->DelayCursorBlink();
689   }
690
691   // Discard temporary text
692   events.clear();
693 }
694
695 void Controller::ResetText()
696 {
697   // Reset buffers.
698   mImpl->mLogicalModel->mText.Clear();
699   ClearModelData();
700
701   // We have cleared everything including the placeholder-text
702   mImpl->PlaceholderCleared();
703
704   // The natural size needs to be re-calculated.
705   mImpl->mRecalculateNaturalSize = true;
706
707   // Apply modifications to the model
708   mImpl->mOperationsPending = ALL_OPERATIONS;
709 }
710
711 void Controller::ResetCursorPosition( CharacterIndex cursorIndex )
712 {
713   // Reset the cursor position
714   if( NULL != mImpl->mEventData )
715   {
716     mImpl->mEventData->mPrimaryCursorPosition = cursorIndex;
717
718     // Update the cursor if it's in editing mode.
719     if( ( EventData::EDITING == mImpl->mEventData->mState )            ||
720         ( EventData::EDITING_WITH_POPUP == mImpl->mEventData->mState ) ||
721         ( EventData::EDITING_WITH_GRAB_HANDLE == mImpl->mEventData->mState ) )
722     {
723       mImpl->mEventData->mUpdateCursorPosition = true;
724     }
725   }
726 }
727
728 void Controller::ResetScrollPosition()
729 {
730   if( NULL != mImpl->mEventData )
731   {
732     // Reset the scroll position.
733     mImpl->mEventData->mScrollPosition = Vector2::ZERO;
734     mImpl->mEventData->mScrollAfterUpdatePosition = true;
735   }
736 }
737
738 void Controller::TextReplacedEvent()
739 {
740   // Reset buffers.
741   ClearModelData();
742
743   // The natural size needs to be re-calculated.
744   mImpl->mRecalculateNaturalSize = true;
745
746   // Apply modifications to the model
747   mImpl->mOperationsPending = ALL_OPERATIONS;
748   mImpl->UpdateModel( ALL_OPERATIONS );
749   mImpl->mOperationsPending = static_cast<OperationsMask>( LAYOUT             |
750                                                            ALIGN              |
751                                                            UPDATE_ACTUAL_SIZE |
752                                                            REORDER );
753 }
754
755 void Controller::TextInsertedEvent()
756 {
757   DALI_ASSERT_DEBUG( NULL != mImpl->mEventData && "Unexpected TextInsertedEvent" );
758
759   // TODO - Optimize this
760   ClearModelData();
761
762   // The natural size needs to be re-calculated.
763   mImpl->mRecalculateNaturalSize = true;
764
765   // Apply modifications to the model; TODO - Optimize this
766   mImpl->mOperationsPending = ALL_OPERATIONS;
767   mImpl->UpdateModel( ALL_OPERATIONS );
768   mImpl->mOperationsPending = static_cast<OperationsMask>( LAYOUT             |
769                                                            ALIGN              |
770                                                            UPDATE_ACTUAL_SIZE |
771                                                            REORDER );
772
773   // Queue a cursor reposition event; this must wait until after DoRelayout()
774   if( ( EventData::EDITING == mImpl->mEventData->mState )            ||
775       ( EventData::EDITING_WITH_POPUP == mImpl->mEventData->mState ) ||
776       ( EventData::EDITING_WITH_GRAB_HANDLE == mImpl->mEventData->mState ) )
777   {
778     mImpl->mEventData->mUpdateCursorPosition = true;
779     mImpl->mEventData->mScrollAfterUpdatePosition = true;
780   }
781 }
782
783 void Controller::TextDeletedEvent()
784 {
785   DALI_ASSERT_DEBUG( NULL != mImpl->mEventData && "Unexpected TextDeletedEvent" );
786
787   // TODO - Optimize this
788   ClearModelData();
789
790   // The natural size needs to be re-calculated.
791   mImpl->mRecalculateNaturalSize = true;
792
793   // Apply modifications to the model; TODO - Optimize this
794   mImpl->mOperationsPending = ALL_OPERATIONS;
795   mImpl->UpdateModel( ALL_OPERATIONS );
796   mImpl->mOperationsPending = static_cast<OperationsMask>( LAYOUT             |
797                                                            ALIGN              |
798                                                            UPDATE_ACTUAL_SIZE |
799                                                            REORDER );
800
801   // Queue a cursor reposition event; this must wait until after DoRelayout()
802   if( 0u == mImpl->mLogicalModel->mText.Count() )
803   {
804     mImpl->mEventData->mUpdateCursorPosition = true;
805   }
806   else
807   {
808     mImpl->mEventData->mScrollAfterDelete = true;
809   }
810 }
811
812 bool Controller::DoRelayout( const Size& size,
813                              OperationsMask operationsRequired,
814                              Size& layoutSize )
815 {
816   DALI_LOG_INFO( gLogFilter, Debug::Verbose, "-->Controller::DoRelayout %p size %f,%f\n", this, size.width, size.height );
817   bool viewUpdated( false );
818
819   // Calculate the operations to be done.
820   const OperationsMask operations = static_cast<OperationsMask>( mImpl->mOperationsPending & operationsRequired );
821
822   if( LAYOUT & operations )
823   {
824     // Some vectors with data needed to layout and reorder may be void
825     // after the first time the text has been laid out.
826     // Fill the vectors again.
827
828     const Length numberOfGlyphs = mImpl->mVisualModel->mGlyphs.Count();
829
830     if( 0u == numberOfGlyphs )
831     {
832       // Nothing else to do if there is no glyphs.
833       DALI_LOG_INFO( gLogFilter, Debug::Verbose, "<--Controller::DoRelayout no glyphs, view updated true\n" );
834       return true;
835     }
836
837     const Vector<LineBreakInfo>& lineBreakInfo = mImpl->mLogicalModel->mLineBreakInfo;
838     const Vector<WordBreakInfo>& wordBreakInfo = mImpl->mLogicalModel->mWordBreakInfo;
839     const Vector<CharacterDirection>& characterDirection = mImpl->mLogicalModel->mCharacterDirections;
840     const Vector<GlyphInfo>& glyphs = mImpl->mVisualModel->mGlyphs;
841     const Vector<CharacterIndex>& glyphsToCharactersMap = mImpl->mVisualModel->mGlyphsToCharacters;
842     const Vector<Length>& charactersPerGlyph = mImpl->mVisualModel->mCharactersPerGlyph;
843     const Character* const textBuffer = mImpl->mLogicalModel->mText.Begin();
844
845     // Set the layout parameters.
846     LayoutParameters layoutParameters( size,
847                                        textBuffer,
848                                        lineBreakInfo.Begin(),
849                                        wordBreakInfo.Begin(),
850                                        ( 0u != characterDirection.Count() ) ? characterDirection.Begin() : NULL,
851                                        numberOfGlyphs,
852                                        glyphs.Begin(),
853                                        glyphsToCharactersMap.Begin(),
854                                        charactersPerGlyph.Begin() );
855
856     // The laid-out lines.
857     // It's not possible to know in how many lines the text is going to be laid-out,
858     // but it can be resized at least with the number of 'paragraphs' to avoid
859     // some re-allocations.
860     Vector<LineRun>& lines = mImpl->mVisualModel->mLines;
861
862     // Delete any previous laid out lines before setting the new ones.
863     lines.Clear();
864
865     // The capacity of the bidirectional paragraph info is the number of paragraphs.
866     lines.Reserve( mImpl->mLogicalModel->mBidirectionalParagraphInfo.Capacity() );
867
868     // Resize the vector of positions to have the same size than the vector of glyphs.
869     Vector<Vector2>& glyphPositions = mImpl->mVisualModel->mGlyphPositions;
870     glyphPositions.Resize( numberOfGlyphs );
871
872     // Whether the last character is a new paragraph character.
873     layoutParameters.isLastNewParagraph = TextAbstraction::IsNewParagraph( *( textBuffer + ( mImpl->mLogicalModel->mText.Count() - 1u ) ) );
874
875     // Update the visual model.
876     viewUpdated = mImpl->mLayoutEngine.LayoutText( layoutParameters,
877                                                    glyphPositions,
878                                                    lines,
879                                                    layoutSize );
880
881     if( viewUpdated )
882     {
883       // Reorder the lines
884       if( REORDER & operations )
885       {
886         Vector<BidirectionalParagraphInfoRun>& bidirectionalInfo = mImpl->mLogicalModel->mBidirectionalParagraphInfo;
887
888         // Check first if there are paragraphs with bidirectional info.
889         if( 0u != bidirectionalInfo.Count() )
890         {
891           // Get the lines
892           const Length numberOfLines = mImpl->mVisualModel->mLines.Count();
893
894           // Reorder the lines.
895           Vector<BidirectionalLineInfoRun> lineBidirectionalInfoRuns;
896           lineBidirectionalInfoRuns.Reserve( numberOfLines ); // Reserve because is not known yet how many lines have right to left characters.
897           ReorderLines( bidirectionalInfo,
898                         lines,
899                         lineBidirectionalInfoRuns );
900
901           // Set the bidirectional info into the model.
902           const Length numberOfBidirectionalInfoRuns = lineBidirectionalInfoRuns.Count();
903           mImpl->mLogicalModel->SetVisualToLogicalMap( lineBidirectionalInfoRuns.Begin(),
904                                                        numberOfBidirectionalInfoRuns );
905
906           // Set the bidirectional info per line into the layout parameters.
907           layoutParameters.lineBidirectionalInfoRunsBuffer = lineBidirectionalInfoRuns.Begin();
908           layoutParameters.numberOfBidirectionalInfoRuns = numberOfBidirectionalInfoRuns;
909
910           // Get the character to glyph conversion table and set into the layout.
911           layoutParameters.charactersToGlyphsBuffer = mImpl->mVisualModel->mCharactersToGlyph.Begin();
912
913           // Get the glyphs per character table and set into the layout.
914           layoutParameters.glyphsPerCharacterBuffer = mImpl->mVisualModel->mGlyphsPerCharacter.Begin();
915
916           // Re-layout the text. Reorder those lines with right to left characters.
917           mImpl->mLayoutEngine.ReLayoutRightToLeftLines( layoutParameters,
918                                                          glyphPositions );
919
920           // Free the allocated memory used to store the conversion table in the bidirectional line info run.
921           for( Vector<BidirectionalLineInfoRun>::Iterator it = lineBidirectionalInfoRuns.Begin(),
922                  endIt = lineBidirectionalInfoRuns.End();
923                it != endIt;
924                ++it )
925           {
926             BidirectionalLineInfoRun& bidiLineInfo = *it;
927
928             free( bidiLineInfo.visualToLogicalMap );
929           }
930         }
931       } // REORDER
932
933       // Sets the actual size.
934       if( UPDATE_ACTUAL_SIZE & operations )
935       {
936         mImpl->mVisualModel->SetActualSize( layoutSize );
937       }
938     } // view updated
939   }
940   else
941   {
942     layoutSize = mImpl->mVisualModel->GetActualSize();
943   }
944
945   if( ALIGN & operations )
946   {
947     // The laid-out lines.
948     Vector<LineRun>& lines = mImpl->mVisualModel->mLines;
949
950     mImpl->mLayoutEngine.Align( layoutSize,
951                                 lines );
952
953     viewUpdated = true;
954   }
955
956   DALI_LOG_INFO( gLogFilter, Debug::Verbose, "<--Controller::DoRelayout, view updated %s\n", ( viewUpdated ? "true" : "false" ) );
957   return viewUpdated;
958 }
959
960 void Controller::SetMultiLineEnabled( bool enable )
961 {
962   const LayoutEngine::Layout layout = enable ? LayoutEngine::MULTI_LINE_BOX : LayoutEngine::SINGLE_LINE_BOX;
963
964   if( layout != mImpl->mLayoutEngine.GetLayout() )
965   {
966     // Set the layout type.
967     mImpl->mLayoutEngine.SetLayout( layout );
968
969     // Set the flags to redo the layout operations
970     const OperationsMask layoutOperations =  static_cast<OperationsMask>( LAYOUT             |
971                                                                           UPDATE_ACTUAL_SIZE |
972                                                                           ALIGN              |
973                                                                           REORDER );
974
975     mImpl->mOperationsPending = static_cast<OperationsMask>( mImpl->mOperationsPending | layoutOperations );
976
977     mImpl->RequestRelayout();
978   }
979 }
980
981 bool Controller::IsMultiLineEnabled() const
982 {
983   return LayoutEngine::MULTI_LINE_BOX == mImpl->mLayoutEngine.GetLayout();
984 }
985
986 void Controller::SetHorizontalAlignment( LayoutEngine::HorizontalAlignment alignment )
987 {
988   if( alignment != mImpl->mLayoutEngine.GetHorizontalAlignment() )
989   {
990     // Set the alignment.
991     mImpl->mLayoutEngine.SetHorizontalAlignment( alignment );
992
993     // Set the flag to redo the alignment operation.
994     mImpl->mOperationsPending = static_cast<OperationsMask>( mImpl->mOperationsPending | ALIGN );
995
996     mImpl->RequestRelayout();
997   }
998 }
999
1000 LayoutEngine::HorizontalAlignment Controller::GetHorizontalAlignment() const
1001 {
1002   return mImpl->mLayoutEngine.GetHorizontalAlignment();
1003 }
1004
1005 void Controller::SetVerticalAlignment( LayoutEngine::VerticalAlignment alignment )
1006 {
1007   if( alignment != mImpl->mLayoutEngine.GetVerticalAlignment() )
1008   {
1009     // Set the alignment.
1010     mImpl->mLayoutEngine.SetVerticalAlignment( alignment );
1011
1012     mImpl->mOperationsPending = static_cast<OperationsMask>( mImpl->mOperationsPending | ALIGN );
1013
1014     mImpl->RequestRelayout();
1015   }
1016 }
1017
1018 LayoutEngine::VerticalAlignment Controller::GetVerticalAlignment() const
1019 {
1020   return mImpl->mLayoutEngine.GetVerticalAlignment();
1021 }
1022
1023 void Controller::CalculateTextAlignment( const Size& size )
1024 {
1025   // Get the direction of the first character.
1026   const CharacterDirection firstParagraphDirection = mImpl->mLogicalModel->GetCharacterDirection( 0u );
1027
1028   Size actualSize = mImpl->mVisualModel->GetActualSize();
1029   if( fabsf( actualSize.height ) < Math::MACHINE_EPSILON_1000 )
1030   {
1031     // Get the line height of the default font.
1032     actualSize.height = mImpl->GetDefaultFontLineHeight();
1033   }
1034
1035   // If the first paragraph is right to left swap ALIGN_BEGIN and ALIGN_END;
1036   LayoutEngine::HorizontalAlignment horizontalAlignment = mImpl->mLayoutEngine.GetHorizontalAlignment();
1037   if( firstParagraphDirection &&
1038       ( LayoutEngine::HORIZONTAL_ALIGN_CENTER != horizontalAlignment ) )
1039   {
1040     if( LayoutEngine::HORIZONTAL_ALIGN_BEGIN == horizontalAlignment )
1041     {
1042       horizontalAlignment = LayoutEngine::HORIZONTAL_ALIGN_END;
1043     }
1044     else
1045     {
1046       horizontalAlignment = LayoutEngine::HORIZONTAL_ALIGN_BEGIN;
1047     }
1048   }
1049
1050   switch( horizontalAlignment )
1051   {
1052     case LayoutEngine::HORIZONTAL_ALIGN_BEGIN:
1053     {
1054       mImpl->mAlignmentOffset.x = 0.f;
1055       break;
1056     }
1057     case LayoutEngine::HORIZONTAL_ALIGN_CENTER:
1058     {
1059       const int intOffset = static_cast<int>( 0.5f * ( size.width - actualSize.width ) ); // try to avoid pixel alignment.
1060       mImpl->mAlignmentOffset.x = static_cast<float>( intOffset );
1061       break;
1062     }
1063     case LayoutEngine::HORIZONTAL_ALIGN_END:
1064     {
1065       mImpl->mAlignmentOffset.x = size.width - actualSize.width;
1066       break;
1067     }
1068   }
1069
1070   const LayoutEngine::VerticalAlignment verticalAlignment = mImpl->mLayoutEngine.GetVerticalAlignment();
1071   switch( verticalAlignment )
1072   {
1073     case LayoutEngine::VERTICAL_ALIGN_TOP:
1074     {
1075       mImpl->mAlignmentOffset.y = 0.f;
1076       break;
1077     }
1078     case LayoutEngine::VERTICAL_ALIGN_CENTER:
1079     {
1080       const int intOffset = static_cast<int>( 0.5f * ( size.height - actualSize.height ) ); // try to avoid pixel alignment.
1081       mImpl->mAlignmentOffset.y = static_cast<float>( intOffset );
1082       break;
1083     }
1084     case LayoutEngine::VERTICAL_ALIGN_BOTTOM:
1085     {
1086       mImpl->mAlignmentOffset.y = size.height - actualSize.height;
1087       break;
1088     }
1089   }
1090 }
1091
1092 LayoutEngine& Controller::GetLayoutEngine()
1093 {
1094   return mImpl->mLayoutEngine;
1095 }
1096
1097 View& Controller::GetView()
1098 {
1099   return mImpl->mView;
1100 }
1101
1102 void Controller::KeyboardFocusGainEvent()
1103 {
1104   DALI_ASSERT_DEBUG( mImpl->mEventData && "Unexpected KeyboardFocusGainEvent" );
1105
1106   if( mImpl->mEventData )
1107   {
1108     if( ( EventData::INACTIVE == mImpl->mEventData->mState ) ||
1109         ( EventData::INTERRUPTED == mImpl->mEventData->mState ) )
1110     {
1111       mImpl->ChangeState( EventData::EDITING );
1112       mImpl->mEventData->mUpdateCursorPosition = true; //If editing started without tap event, cursor update must be triggered.
1113     }
1114
1115     if( mImpl->IsShowingPlaceholderText() )
1116     {
1117       // Show alternative placeholder-text when editing
1118       ShowPlaceholderText();
1119     }
1120
1121     mImpl->RequestRelayout();
1122   }
1123 }
1124
1125 void Controller::KeyboardFocusLostEvent()
1126 {
1127   DALI_ASSERT_DEBUG( mImpl->mEventData && "Unexpected KeyboardFocusLostEvent" );
1128
1129   if( mImpl->mEventData )
1130   {
1131     if ( EventData::INTERRUPTED != mImpl->mEventData->mState )
1132     {
1133       mImpl->ChangeState( EventData::INACTIVE );
1134
1135       if( mImpl->IsShowingPlaceholderText() )
1136       {
1137         // Revert to regular placeholder-text when not editing
1138         ShowPlaceholderText();
1139       }
1140     }
1141   }
1142   mImpl->RequestRelayout();
1143 }
1144
1145 bool Controller::KeyEvent( const Dali::KeyEvent& keyEvent )
1146 {
1147   DALI_ASSERT_DEBUG( mImpl->mEventData && "Unexpected KeyEvent" );
1148
1149   bool textChanged( false );
1150
1151   if( mImpl->mEventData &&
1152       keyEvent.state == KeyEvent::Down )
1153   {
1154     int keyCode = keyEvent.keyCode;
1155     const std::string& keyString = keyEvent.keyPressed;
1156
1157     // Pre-process to separate modifying events from non-modifying input events.
1158     if( Dali::DALI_KEY_ESCAPE == keyCode )
1159     {
1160       // Escape key is a special case which causes focus loss
1161       KeyboardFocusLostEvent();
1162     }
1163     else if( Dali::DALI_KEY_CURSOR_LEFT  == keyCode ||
1164              Dali::DALI_KEY_CURSOR_RIGHT == keyCode ||
1165              Dali::DALI_KEY_CURSOR_UP    == keyCode ||
1166              Dali::DALI_KEY_CURSOR_DOWN  == keyCode )
1167     {
1168       Event event( Event::CURSOR_KEY_EVENT );
1169       event.p1.mInt = keyCode;
1170       mImpl->mEventData->mEventQueue.push_back( event );
1171     }
1172     else if( Dali::DALI_KEY_BACKSPACE == keyCode )
1173     {
1174       textChanged = BackspaceKeyEvent();
1175     }
1176     else if ( IsKey( keyEvent,  Dali::DALI_KEY_POWER ) )
1177     {
1178       mImpl->ChangeState( EventData::INTERRUPTED ); // State is not INACTIVE as expect to return to edit mode.
1179       // Avoids calling the InsertText() method which can delete selected text
1180     }
1181     else if ( IsKey( keyEvent, Dali::DALI_KEY_MENU ) ||
1182               IsKey( keyEvent, Dali::DALI_KEY_HOME ) )
1183     {
1184       mImpl->ChangeState( EventData::INACTIVE );
1185       // Menu/Home key behaviour does not allow edit mode to resume like Power key
1186       // Avoids calling the InsertText() method which can delete selected text
1187     }
1188     else if( Dali::DALI_KEY_SHIFT_LEFT == keyCode )
1189     {
1190       // DALI_KEY_SHIFT_LEFT is the key code for the Left Shift. It's sent (by the imf?) when the predictive text is enabled
1191       // and a character is typed after the type of a upper case latin character.
1192
1193       // Do nothing.
1194     }
1195     else
1196     {
1197       DALI_LOG_INFO( gLogFilter, Debug::Verbose, "Controller::KeyEvent %p keyString %s\n", this, keyString.c_str() );
1198
1199       // IMF manager is no longer handling key-events
1200       mImpl->ClearPreEditFlag();
1201
1202       InsertText( keyString, COMMIT );
1203       textChanged = true;
1204     }
1205
1206     if ( ( mImpl->mEventData->mState != EventData::INTERRUPTED ) &&
1207          ( mImpl->mEventData->mState != EventData::INACTIVE ) )
1208     {
1209       mImpl->ChangeState( EventData::EDITING );
1210     }
1211
1212     mImpl->RequestRelayout();
1213   }
1214
1215   if( textChanged )
1216   {
1217     // Do this last since it provides callbacks into application code
1218     mImpl->mControlInterface.TextChanged();
1219   }
1220
1221   return false;
1222 }
1223
1224 void Controller::InsertText( const std::string& text, Controller::InsertType type )
1225 {
1226   bool removedPrevious( false );
1227   bool maxLengthReached( false );
1228
1229   DALI_ASSERT_DEBUG( NULL != mImpl->mEventData && "Unexpected InsertText" )
1230   DALI_LOG_INFO( gLogFilter, Debug::Verbose, "Controller::InsertText %p %s (%s) mPrimaryCursorPosition %d mPreEditFlag %d mPreEditStartPosition %d mPreEditLength %d\n",
1231                  this, text.c_str(), (COMMIT == type ? "COMMIT" : "PRE_EDIT"),
1232                  mImpl->mEventData->mPrimaryCursorPosition, mImpl->mEventData->mPreEditFlag, mImpl->mEventData->mPreEditStartPosition, mImpl->mEventData->mPreEditLength );
1233
1234   // TODO: At the moment the underline runs are only for pre-edit.
1235   mImpl->mVisualModel->mUnderlineRuns.Clear();
1236
1237   Vector<Character> utf32Characters;
1238   Length characterCount( 0u );
1239
1240   // Remove the previous IMF pre-edit (predicitive text)
1241   if( mImpl->mEventData &&
1242       mImpl->mEventData->mPreEditFlag &&
1243       0 != mImpl->mEventData->mPreEditLength )
1244   {
1245     CharacterIndex offset = mImpl->mEventData->mPrimaryCursorPosition - mImpl->mEventData->mPreEditStartPosition;
1246
1247     removedPrevious = RemoveText( -static_cast<int>(offset), mImpl->mEventData->mPreEditLength );
1248
1249     mImpl->mEventData->mPrimaryCursorPosition = mImpl->mEventData->mPreEditStartPosition;
1250     mImpl->mEventData->mPreEditLength = 0;
1251   }
1252   else
1253   {
1254     // Remove the previous Selection
1255     removedPrevious = RemoveSelectedText();
1256   }
1257
1258   if( !text.empty() )
1259   {
1260     //  Convert text into UTF-32
1261     utf32Characters.Resize( text.size() );
1262
1263     // This is a bit horrible but std::string returns a (signed) char*
1264     const uint8_t* utf8 = reinterpret_cast<const uint8_t*>( text.c_str() );
1265
1266     // Transform a text array encoded in utf8 into an array encoded in utf32.
1267     // It returns the actual number of characters.
1268     characterCount = Utf8ToUtf32( utf8, text.size(), utf32Characters.Begin() );
1269     utf32Characters.Resize( characterCount );
1270
1271     DALI_ASSERT_DEBUG( text.size() >= utf32Characters.Count() && "Invalid UTF32 conversion length" );
1272     DALI_LOG_INFO( gLogFilter, Debug::Verbose, "UTF8 size %d, UTF32 size %d\n", text.size(), utf32Characters.Count() );
1273   }
1274
1275   if( 0u != utf32Characters.Count() ) // Check if Utf8ToUtf32 conversion succeeded
1276   {
1277     // The placeholder text is no longer needed
1278     if( mImpl->IsShowingPlaceholderText() )
1279     {
1280       ResetText();
1281     }
1282
1283     mImpl->ChangeState( EventData::EDITING );
1284
1285     // Handle the IMF (predicitive text) state changes
1286     if( mImpl->mEventData )
1287     {
1288       if( COMMIT == type )
1289       {
1290         // IMF manager is no longer handling key-events
1291         mImpl->ClearPreEditFlag();
1292       }
1293       else // PRE_EDIT
1294       {
1295         if( !mImpl->mEventData->mPreEditFlag )
1296         {
1297           DALI_LOG_INFO( gLogFilter, Debug::Verbose, "Entered PreEdit state" );
1298
1299           // Record the start of the pre-edit text
1300           mImpl->mEventData->mPreEditStartPosition = mImpl->mEventData->mPrimaryCursorPosition;
1301         }
1302
1303         mImpl->mEventData->mPreEditLength = utf32Characters.Count();
1304         mImpl->mEventData->mPreEditFlag = true;
1305
1306         DALI_LOG_INFO( gLogFilter, Debug::Verbose, "mPreEditStartPosition %d mPreEditLength %d\n", mImpl->mEventData->mPreEditStartPosition, mImpl->mEventData->mPreEditLength );
1307       }
1308     }
1309
1310     const Length numberOfCharactersInModel = mImpl->mLogicalModel->mText.Count();
1311
1312     // Restrict new text to fit within Maximum characters setting
1313     Length maxSizeOfNewText = std::min ( ( mImpl->mMaximumNumberOfCharacters - numberOfCharactersInModel ), characterCount );
1314     maxLengthReached = ( characterCount > maxSizeOfNewText );
1315
1316     // Insert at current cursor position
1317     CharacterIndex& cursorIndex = mImpl->mEventData->mPrimaryCursorPosition;
1318
1319     Vector<Character>& modifyText = mImpl->mLogicalModel->mText;
1320
1321     if( cursorIndex < numberOfCharactersInModel )
1322     {
1323       modifyText.Insert( modifyText.Begin() + cursorIndex, utf32Characters.Begin(), utf32Characters.Begin() + maxSizeOfNewText );
1324     }
1325     else
1326     {
1327       modifyText.Insert( modifyText.End(), utf32Characters.Begin(), utf32Characters.Begin() + maxSizeOfNewText );
1328     }
1329
1330     cursorIndex += maxSizeOfNewText;
1331
1332     DALI_LOG_INFO( gLogFilter, Debug::Verbose, "Inserted %d characters, new size %d new cursor %d\n", maxSizeOfNewText, mImpl->mLogicalModel->mText.Count(), mImpl->mEventData->mPrimaryCursorPosition );
1333   }
1334
1335   if( 0u == mImpl->mLogicalModel->mText.Count() &&
1336       mImpl->IsPlaceholderAvailable() )
1337   {
1338     // Show place-holder if empty after removing the pre-edit text
1339     ShowPlaceholderText();
1340     mImpl->mEventData->mUpdateCursorPosition = true;
1341     mImpl->ClearPreEditFlag();
1342   }
1343   else if( removedPrevious ||
1344            0 != utf32Characters.Count() )
1345   {
1346     // Queue an inserted event
1347     mImpl->QueueModifyEvent( ModifyEvent::TEXT_INSERTED );
1348   }
1349
1350   if( maxLengthReached )
1351   {
1352     DALI_LOG_INFO( gLogFilter, Debug::Verbose, "MaxLengthReached (%d)\n", mImpl->mLogicalModel->mText.Count() );
1353
1354     mImpl->ResetImfManager();
1355
1356     // Do this last since it provides callbacks into application code
1357     mImpl->mControlInterface.MaxLengthReached();
1358   }
1359 }
1360
1361 bool Controller::RemoveSelectedText()
1362 {
1363   bool textRemoved( false );
1364
1365   if ( EventData::SELECTING         == mImpl->mEventData->mState ||
1366        EventData::SELECTION_CHANGED == mImpl->mEventData->mState )
1367   {
1368     std::string removedString;
1369     mImpl->RetrieveSelection( removedString, true );
1370
1371     if( !removedString.empty() )
1372     {
1373       textRemoved = true;
1374       mImpl->ChangeState( EventData::EDITING );
1375     }
1376   }
1377
1378   return textRemoved;
1379 }
1380
1381 void Controller::TapEvent( unsigned int tapCount, float x, float y )
1382 {
1383   DALI_ASSERT_DEBUG( mImpl->mEventData && "Unexpected TapEvent" );
1384
1385   if( NULL != mImpl->mEventData )
1386   {
1387     if( 1u == tapCount )
1388     {
1389       // This is to avoid unnecessary relayouts when tapping an empty text-field
1390       bool relayoutNeeded( false );
1391
1392       if( mImpl->IsShowingRealText() &&
1393           EventData::EDITING == mImpl->mEventData->mState )
1394       {
1395         // Show grab handle on second tap
1396         mImpl->ChangeState( EventData::EDITING_WITH_GRAB_HANDLE );
1397         relayoutNeeded = true;
1398       }
1399       else if( EventData::EDITING                  != mImpl->mEventData->mState &&
1400                EventData::EDITING_WITH_GRAB_HANDLE != mImpl->mEventData->mState )
1401       {
1402         // Show cursor on first tap
1403         mImpl->ChangeState( EventData::EDITING );
1404         relayoutNeeded = true;
1405       }
1406       else if( mImpl->IsShowingRealText() )
1407       {
1408         // Move the cursor
1409         relayoutNeeded = true;
1410       }
1411
1412       // Handles & cursors must be repositioned after Relayout() i.e. after the Model has been updated
1413       if( relayoutNeeded )
1414       {
1415         Event event( Event::TAP_EVENT );
1416         event.p1.mUint = tapCount;
1417         event.p2.mFloat = x;
1418         event.p3.mFloat = y;
1419         mImpl->mEventData->mEventQueue.push_back( event );
1420
1421         mImpl->RequestRelayout();
1422       }
1423     }
1424     else if( 2u == tapCount )
1425     {
1426       if( mImpl->mEventData->mSelectionEnabled &&
1427           mImpl->IsShowingRealText() )
1428       {
1429         SelectEvent( x, y, false );
1430       }
1431     }
1432   }
1433
1434   // Reset keyboard as tap event has occurred.
1435   mImpl->ResetImfManager();
1436 }
1437
1438 void Controller::PanEvent( Gesture::State state, const Vector2& displacement )
1439 {
1440   DALI_ASSERT_DEBUG( mImpl->mEventData && "Unexpected PanEvent" );
1441
1442   if( mImpl->mEventData )
1443   {
1444     Event event( Event::PAN_EVENT );
1445     event.p1.mInt = state;
1446     event.p2.mFloat = displacement.x;
1447     event.p3.mFloat = displacement.y;
1448     mImpl->mEventData->mEventQueue.push_back( event );
1449
1450     mImpl->RequestRelayout();
1451   }
1452 }
1453
1454 void Controller::LongPressEvent( Gesture::State state, float x, float y  )
1455 {
1456   DALI_ASSERT_DEBUG( mImpl->mEventData && "Unexpected PanEvent" );
1457
1458   if  ( mImpl->IsShowingPlaceholderText() || mImpl->mLogicalModel->mText.Count() == 0u )
1459   {
1460     if ( mImpl->mEventData )
1461     {
1462       Event event( Event::LONG_PRESS_EVENT );
1463       event.p1.mInt = state;
1464       mImpl->mEventData->mEventQueue.push_back( event );
1465       mImpl->RequestRelayout();
1466     }
1467   }
1468   else if( mImpl->mEventData )
1469   {
1470     SelectEvent( x, y, false );
1471   }
1472 }
1473
1474 void Controller::SelectEvent( float x, float y, bool selectAll )
1475 {
1476   if( mImpl->mEventData )
1477   {
1478     if ( mImpl->mEventData->mState == EventData::SELECTING )
1479     {
1480       mImpl->ChangeState( EventData::SELECTION_CHANGED );
1481     }
1482     else
1483     {
1484       mImpl->ChangeState( EventData::SELECTING );
1485     }
1486
1487     if( selectAll )
1488     {
1489       Event event( Event::SELECT_ALL );
1490       mImpl->mEventData->mEventQueue.push_back( event );
1491     }
1492     else
1493     {
1494       Event event( Event::SELECT );
1495       event.p2.mFloat = x;
1496       event.p3.mFloat = y;
1497       mImpl->mEventData->mEventQueue.push_back( event );
1498     }
1499
1500     mImpl->RequestRelayout();
1501   }
1502 }
1503
1504 void Controller::GetTargetSize( Vector2& targetSize )
1505 {
1506   targetSize = mImpl->mVisualModel->mControlSize;
1507 }
1508
1509 void Controller::AddDecoration( Actor& actor, bool needsClipping )
1510 {
1511   mImpl->mControlInterface.AddDecoration( actor, needsClipping );
1512 }
1513
1514 void Controller::DecorationEvent( HandleType handleType, HandleState state, float x, float y )
1515 {
1516   DALI_ASSERT_DEBUG( mImpl->mEventData && "Unexpected DecorationEvent" );
1517
1518   if( mImpl->mEventData )
1519   {
1520     switch( handleType )
1521     {
1522       case GRAB_HANDLE:
1523       {
1524         Event event( Event::GRAB_HANDLE_EVENT );
1525         event.p1.mUint  = state;
1526         event.p2.mFloat = x;
1527         event.p3.mFloat = y;
1528
1529         mImpl->mEventData->mEventQueue.push_back( event );
1530         break;
1531       }
1532       case LEFT_SELECTION_HANDLE:
1533       {
1534         Event event( Event::LEFT_SELECTION_HANDLE_EVENT );
1535         event.p1.mUint  = state;
1536         event.p2.mFloat = x;
1537         event.p3.mFloat = y;
1538
1539         mImpl->mEventData->mEventQueue.push_back( event );
1540         break;
1541       }
1542       case RIGHT_SELECTION_HANDLE:
1543       {
1544         Event event( Event::RIGHT_SELECTION_HANDLE_EVENT );
1545         event.p1.mUint  = state;
1546         event.p2.mFloat = x;
1547         event.p3.mFloat = y;
1548
1549         mImpl->mEventData->mEventQueue.push_back( event );
1550         break;
1551       }
1552       case LEFT_SELECTION_HANDLE_MARKER:
1553       case RIGHT_SELECTION_HANDLE_MARKER:
1554       {
1555         // Markers do not move the handles.
1556         break;
1557       }
1558       case HANDLE_TYPE_COUNT:
1559       {
1560         DALI_ASSERT_DEBUG( !"Controller::HandleEvent. Unexpected handle type" );
1561       }
1562     }
1563
1564     mImpl->RequestRelayout();
1565   }
1566 }
1567
1568 void Controller::PasteText( const std::string& stringToPaste )
1569 {
1570   InsertText( stringToPaste, Text::Controller::COMMIT );
1571   mImpl->ChangeState( EventData::EDITING );
1572   mImpl->RequestRelayout();
1573 }
1574
1575 void Controller::PasteClipboardItemEvent()
1576 {
1577   ClipboardEventNotifier notifier( ClipboardEventNotifier::Get() );
1578   std::string stringToPaste( notifier.GetContent() );
1579   PasteText( stringToPaste );
1580 }
1581
1582 void Controller::TextPopupButtonTouched( Dali::Toolkit::TextSelectionPopup::Buttons button )
1583 {
1584   if( NULL == mImpl->mEventData )
1585   {
1586     return;
1587   }
1588
1589   switch( button )
1590   {
1591     case Toolkit::TextSelectionPopup::CUT:
1592     {
1593       mImpl->SendSelectionToClipboard( true ); // Synchronous call to modify text
1594       mImpl->mOperationsPending = ALL_OPERATIONS;
1595       if( 0u != mImpl->mLogicalModel->mText.Count() ||
1596           !mImpl->IsPlaceholderAvailable() )
1597       {
1598         mImpl->QueueModifyEvent( ModifyEvent::TEXT_DELETED );
1599       }
1600       else
1601       {
1602         ShowPlaceholderText();
1603         mImpl->mEventData->mUpdateCursorPosition = true;
1604       }
1605       mImpl->RequestRelayout();
1606       mImpl->mControlInterface.TextChanged();
1607       break;
1608     }
1609     case Toolkit::TextSelectionPopup::COPY:
1610     {
1611       mImpl->SendSelectionToClipboard( false ); // Text not modified
1612       mImpl->RequestRelayout(); // Handles, Selection Highlight, Popup
1613       break;
1614     }
1615     case Toolkit::TextSelectionPopup::PASTE:
1616     {
1617       std::string stringToPaste("");
1618       mImpl->GetTextFromClipboard( 0, stringToPaste ); // Paste latest item from system clipboard
1619       PasteText( stringToPaste );
1620       break;
1621     }
1622     case Toolkit::TextSelectionPopup::SELECT:
1623     {
1624       const Vector2& currentCursorPosition = mImpl->mEventData->mDecorator->GetPosition( PRIMARY_CURSOR );
1625
1626       if( mImpl->mEventData->mSelectionEnabled  )
1627       {
1628         // Creates a SELECT event.
1629         SelectEvent( currentCursorPosition.x, currentCursorPosition.y, false );
1630       }
1631       break;
1632     }
1633     case Toolkit::TextSelectionPopup::SELECT_ALL:
1634     {
1635       // Creates a SELECT_ALL event
1636       SelectEvent( 0.f, 0.f, true );
1637       break;
1638     }
1639     case Toolkit::TextSelectionPopup::CLIPBOARD:
1640     {
1641       mImpl->ShowClipboard();
1642       break;
1643     }
1644     case Toolkit::TextSelectionPopup::NONE:
1645     {
1646       // Nothing to do.
1647       break;
1648     }
1649   }
1650 }
1651
1652 ImfManager::ImfCallbackData Controller::OnImfEvent( ImfManager& imfManager, const ImfManager::ImfEventData& imfEvent )
1653 {
1654   bool update( false );
1655   bool requestRelayout = false;
1656
1657   std::string text;
1658   unsigned int cursorPosition( 0 );
1659
1660   switch ( imfEvent.eventName )
1661   {
1662     case ImfManager::COMMIT:
1663     {
1664       InsertText( imfEvent.predictiveString, Text::Controller::COMMIT );
1665       requestRelayout = true;
1666       break;
1667     }
1668     case ImfManager::PREEDIT:
1669     {
1670       InsertText( imfEvent.predictiveString, Text::Controller::PRE_EDIT );
1671       update = true;
1672       requestRelayout = true;
1673       break;
1674     }
1675     case ImfManager::DELETESURROUNDING:
1676     {
1677       update = RemoveText( imfEvent.cursorOffset, imfEvent.numberOfChars );
1678
1679       if( update )
1680       {
1681         if( 0u != mImpl->mLogicalModel->mText.Count() ||
1682             !mImpl->IsPlaceholderAvailable() )
1683         {
1684           mImpl->QueueModifyEvent( ModifyEvent::TEXT_DELETED );
1685         }
1686         else
1687         {
1688           ShowPlaceholderText();
1689           mImpl->mEventData->mUpdateCursorPosition = true;
1690         }
1691       }
1692       requestRelayout = true;
1693       break;
1694     }
1695     case ImfManager::GETSURROUNDING:
1696     {
1697       GetText( text );
1698       cursorPosition = GetLogicalCursorPosition();
1699
1700       imfManager.SetSurroundingText( text );
1701       imfManager.SetCursorPosition( cursorPosition );
1702       break;
1703     }
1704     case ImfManager::VOID:
1705     {
1706       // do nothing
1707       break;
1708     }
1709   } // end switch
1710
1711   if( ImfManager::GETSURROUNDING != imfEvent.eventName )
1712   {
1713     GetText( text );
1714     cursorPosition = GetLogicalCursorPosition();
1715   }
1716
1717   if( requestRelayout )
1718   {
1719     mImpl->mOperationsPending = ALL_OPERATIONS;
1720     mImpl->RequestRelayout();
1721
1722     // Do this last since it provides callbacks into application code
1723     mImpl->mControlInterface.TextChanged();
1724   }
1725
1726   ImfManager::ImfCallbackData callbackData( update, cursorPosition, text, false );
1727
1728   return callbackData;
1729 }
1730
1731 Controller::~Controller()
1732 {
1733   delete mImpl;
1734 }
1735
1736 bool Controller::BackspaceKeyEvent()
1737 {
1738   DALI_LOG_INFO( gLogFilter, Debug::Verbose, "Controller::KeyEvent %p DALI_KEY_BACKSPACE\n", this );
1739
1740   // IMF manager is no longer handling key-events
1741   mImpl->ClearPreEditFlag();
1742
1743   bool removed( false );
1744
1745   if ( EventData::SELECTING         == mImpl->mEventData->mState ||
1746        EventData::SELECTION_CHANGED == mImpl->mEventData->mState )
1747   {
1748     removed = RemoveSelectedText();
1749   }
1750   else if( mImpl->mEventData->mPrimaryCursorPosition > 0 )
1751   {
1752     // Remove the character before the current cursor position
1753     removed = RemoveText( -1, 1 );
1754   }
1755
1756   if( removed )
1757   {
1758     if( 0u != mImpl->mLogicalModel->mText.Count() ||
1759         !mImpl->IsPlaceholderAvailable() )
1760     {
1761       mImpl->QueueModifyEvent( ModifyEvent::TEXT_DELETED );
1762     }
1763     else
1764     {
1765       ShowPlaceholderText();
1766       mImpl->mEventData->mUpdateCursorPosition = true;
1767     }
1768   }
1769
1770   return removed;
1771 }
1772
1773 void Controller::ShowPlaceholderText()
1774 {
1775   if( mImpl->IsPlaceholderAvailable() )
1776   {
1777     DALI_ASSERT_DEBUG( mImpl->mEventData && "No placeholder text available" );
1778
1779     mImpl->mEventData->mIsShowingPlaceholderText = true;
1780
1781     // Disable handles when showing place-holder text
1782     mImpl->mEventData->mDecorator->SetHandleActive( GRAB_HANDLE, false );
1783     mImpl->mEventData->mDecorator->SetHandleActive( LEFT_SELECTION_HANDLE, false );
1784     mImpl->mEventData->mDecorator->SetHandleActive( RIGHT_SELECTION_HANDLE, false );
1785
1786     const char* text( NULL );
1787     size_t size( 0 );
1788
1789     // TODO - Switch placeholder text styles when changing state
1790     if( EventData::INACTIVE != mImpl->mEventData->mState &&
1791         0u != mImpl->mEventData->mPlaceholderTextActive.c_str() )
1792     {
1793       text = mImpl->mEventData->mPlaceholderTextActive.c_str();
1794       size = mImpl->mEventData->mPlaceholderTextActive.size();
1795     }
1796     else
1797     {
1798       text = mImpl->mEventData->mPlaceholderTextInactive.c_str();
1799       size = mImpl->mEventData->mPlaceholderTextInactive.size();
1800     }
1801
1802     // Reset model for showing placeholder.
1803     mImpl->mLogicalModel->mText.Clear();
1804     ClearModelData();
1805     mImpl->mVisualModel->SetTextColor( mImpl->mEventData->mPlaceholderTextColor );
1806
1807     // Convert text into UTF-32
1808     Vector<Character>& utf32Characters = mImpl->mLogicalModel->mText;
1809     utf32Characters.Resize( size );
1810
1811     // This is a bit horrible but std::string returns a (signed) char*
1812     const uint8_t* utf8 = reinterpret_cast<const uint8_t*>( text );
1813
1814     // Transform a text array encoded in utf8 into an array encoded in utf32.
1815     // It returns the actual number of characters.
1816     Length characterCount = Utf8ToUtf32( utf8, size, utf32Characters.Begin() );
1817     utf32Characters.Resize( characterCount );
1818
1819     // Reset the cursor position
1820     mImpl->mEventData->mPrimaryCursorPosition = 0;
1821
1822     // The natural size needs to be re-calculated.
1823     mImpl->mRecalculateNaturalSize = true;
1824
1825     // Apply modifications to the model
1826     mImpl->mOperationsPending = ALL_OPERATIONS;
1827
1828     // Update the rest of the model during size negotiation
1829     mImpl->QueueModifyEvent( ModifyEvent::TEXT_REPLACED );
1830   }
1831 }
1832
1833 void Controller::ClearModelData()
1834 {
1835   // n.b. This does not Clear the mText from mLogicalModel
1836   mImpl->mLogicalModel->mScriptRuns.Clear();
1837   mImpl->mLogicalModel->mFontRuns.Clear();
1838   mImpl->mLogicalModel->mLineBreakInfo.Clear();
1839   mImpl->mLogicalModel->mWordBreakInfo.Clear();
1840   mImpl->mLogicalModel->mBidirectionalParagraphInfo.Clear();
1841   mImpl->mLogicalModel->mCharacterDirections.Clear();
1842   mImpl->mLogicalModel->mBidirectionalLineInfo.Clear();
1843   mImpl->mLogicalModel->mLogicalToVisualMap.Clear();
1844   mImpl->mLogicalModel->mVisualToLogicalMap.Clear();
1845   mImpl->mVisualModel->mGlyphs.Clear();
1846   mImpl->mVisualModel->mGlyphsToCharacters.Clear();
1847   mImpl->mVisualModel->mCharactersToGlyph.Clear();
1848   mImpl->mVisualModel->mCharactersPerGlyph.Clear();
1849   mImpl->mVisualModel->mGlyphsPerCharacter.Clear();
1850   mImpl->mVisualModel->mGlyphPositions.Clear();
1851   mImpl->mVisualModel->mLines.Clear();
1852   mImpl->mVisualModel->ClearCaches();
1853 }
1854
1855 void Controller::ClearFontData()
1856 {
1857   mImpl->mFontDefaults->mFontId = 0u; // Remove old font ID
1858   mImpl->mLogicalModel->mFontRuns.Clear();
1859   mImpl->mVisualModel->mGlyphs.Clear();
1860   mImpl->mVisualModel->mGlyphsToCharacters.Clear();
1861   mImpl->mVisualModel->mCharactersToGlyph.Clear();
1862   mImpl->mVisualModel->mCharactersPerGlyph.Clear();
1863   mImpl->mVisualModel->mGlyphsPerCharacter.Clear();
1864   mImpl->mVisualModel->mGlyphPositions.Clear();
1865   mImpl->mVisualModel->mLines.Clear();
1866   mImpl->mVisualModel->ClearCaches();
1867 }
1868
1869 Controller::Controller( ControlInterface& controlInterface )
1870 : mImpl( NULL )
1871 {
1872   mImpl = new Controller::Impl( controlInterface );
1873 }
1874
1875 } // namespace Text
1876
1877 } // namespace Toolkit
1878
1879 } // namespace Dali