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