2ceee77f66f97f252a33a71acd2ba567668217fe
[platform/core/uifw/dali-toolkit.git] / dali-toolkit / internal / text / controller / text-controller-text-updater.cpp
1 /*
2  * Copyright (c) 2022 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/controller/text-controller-text-updater.h>
20
21 // EXTERNAL INCLUDES
22 #include <dali/integration-api/debug.h>
23 #include <dali/public-api/math/math-utils.h>
24 #include <memory.h>
25
26 // INTERNAL INCLUDES
27 #include <dali-toolkit/internal/text/character-set-conversion.h>
28 #include <dali-toolkit/internal/text/characters-helper-functions.h>
29 #include <dali-toolkit/internal/text/controller/text-controller-impl.h>
30 #include <dali-toolkit/internal/text/controller/text-controller-placeholder-handler.h>
31 #include <dali-toolkit/internal/text/emoji-helper.h>
32 #include <dali-toolkit/internal/text/markup-processor/markup-processor.h>
33 #include <dali-toolkit/internal/text/text-editable-control-interface.h>
34
35 namespace
36 {
37 #if defined(DEBUG_ENABLED)
38 Debug::Filter* gLogFilter = Debug::Filter::New(Debug::NoLogging, true, "LOG_TEXT_CONTROLS");
39 #endif
40
41 } // namespace
42
43 namespace Dali
44 {
45 namespace Toolkit
46 {
47 namespace Text
48 {
49 void Controller::TextUpdater::SetText(Controller& controller, const std::string& text)
50 {
51   DALI_LOG_INFO(gLogFilter, Debug::Verbose, "Controller::SetText\n");
52
53   Controller::Impl& impl = *controller.mImpl;
54
55   // Reset keyboard as text changed
56   impl.ResetInputMethodContext();
57
58   // Remove the previously set text and style.
59   ResetText(controller);
60
61   // Remove the style.
62   impl.ClearStyleData();
63
64   CharacterIndex lastCursorIndex = 0u;
65
66   EventData*& eventData = impl.mEventData;
67
68   if(nullptr != eventData)
69   {
70     // If popup shown then hide it by switching to Editing state
71     if((EventData::SELECTING == eventData->mState) ||
72        (EventData::EDITING_WITH_POPUP == eventData->mState) ||
73        (EventData::EDITING_WITH_GRAB_HANDLE == eventData->mState) ||
74        (EventData::EDITING_WITH_PASTE_POPUP == eventData->mState))
75     {
76       if((impl.mSelectableControlInterface != nullptr) && (EventData::SELECTING == eventData->mState))
77       {
78         impl.mSelectableControlInterface->SelectionChanged(eventData->mLeftSelectionPosition, eventData->mRightSelectionPosition, eventData->mPrimaryCursorPosition, eventData->mPrimaryCursorPosition);
79       }
80
81       impl.ChangeState(EventData::EDITING);
82     }
83   }
84
85   if(!text.empty())
86   {
87     ModelPtr&        model        = impl.mModel;
88     LogicalModelPtr& logicalModel = model->mLogicalModel;
89     model->mVisualModel->SetTextColor(impl.mTextColor);
90
91     MarkupProcessData markupProcessData(logicalModel->mColorRuns,
92                                         logicalModel->mFontDescriptionRuns,
93                                         logicalModel->mEmbeddedItems,
94                                         logicalModel->mAnchors,
95                                         logicalModel->mUnderlinedCharacterRuns,
96                                         logicalModel->mBackgroundColorRuns,
97                                         logicalModel->mStrikethroughCharacterRuns,
98                                         logicalModel->mBoundedParagraphRuns,
99                                         logicalModel->mCharacterSpacingCharacterRuns);
100
101     Length         textSize = 0u;
102     const uint8_t* utf8     = NULL;
103     if(impl.mMarkupProcessorEnabled)
104     {
105       MarkupPropertyData markupPropertyData(impl.mAnchorColor, impl.mAnchorClickedColor);
106
107       ProcessMarkupString(text, markupPropertyData, markupProcessData);
108       textSize = markupProcessData.markupProcessedText.size();
109
110       // This is a bit horrible but std::string returns a (signed) char*
111       utf8 = reinterpret_cast<const uint8_t*>(markupProcessData.markupProcessedText.c_str());
112     }
113     else
114     {
115       textSize = text.size();
116
117       // This is a bit horrible but std::string returns a (signed) char*
118       utf8 = reinterpret_cast<const uint8_t*>(text.c_str());
119     }
120
121     //  Convert text into UTF-32
122     Vector<Character>& utf32Characters = logicalModel->mText;
123     utf32Characters.Resize(textSize);
124
125     // Transform a text array encoded in utf8 into an array encoded in utf32.
126     // It returns the actual number of characters.
127     Length characterCount = Utf8ToUtf32(utf8, textSize, utf32Characters.Begin());
128     utf32Characters.Resize(characterCount);
129
130     DALI_ASSERT_DEBUG(textSize >= characterCount && "Invalid UTF32 conversion length");
131     DALI_LOG_INFO(gLogFilter, Debug::Verbose, "Controller::SetText %p UTF8 size %d, UTF32 size %d\n", &controller, textSize, logicalModel->mText.Count());
132
133     // The characters to be added.
134     impl.mTextUpdateInfo.mNumberOfCharactersToAdd = logicalModel->mText.Count();
135
136     // To reset the cursor position
137     lastCursorIndex = characterCount;
138
139     // Update the rest of the model during size negotiation
140     impl.QueueModifyEvent(ModifyEvent::TEXT_REPLACED);
141
142     // The natural size needs to be re-calculated.
143     impl.mRecalculateNaturalSize = true;
144
145     // The text direction needs to be updated.
146     impl.mUpdateTextDirection = true;
147
148     // Apply modifications to the model
149     impl.mOperationsPending = ALL_OPERATIONS;
150   }
151   else
152   {
153     PlaceholderHandler::ShowPlaceholderText(impl);
154   }
155
156   unsigned int oldCursorPos = (nullptr != eventData ? eventData->mPrimaryCursorPosition : 0);
157
158   // Resets the cursor position.
159   controller.ResetCursorPosition(lastCursorIndex);
160
161   // Scrolls the text to make the cursor visible.
162   impl.ResetScrollPosition();
163
164   impl.RequestRelayout();
165
166   if(nullptr != eventData)
167   {
168     // Cancel previously queued events
169     eventData->mEventQueue.clear();
170   }
171
172   // Do this last since it provides callbacks into application code.
173   if(NULL != impl.mEditableControlInterface)
174   {
175     impl.mEditableControlInterface->CursorPositionChanged(oldCursorPos, lastCursorIndex);
176     impl.mEditableControlInterface->TextChanged(true);
177   }
178 }
179
180 void Controller::TextUpdater::InsertText(Controller& controller, const std::string& text, Controller::InsertType type)
181 {
182   Controller::Impl& impl      = *controller.mImpl;
183   EventData*&       eventData = impl.mEventData;
184
185   DALI_ASSERT_DEBUG(nullptr != eventData && "Unexpected InsertText")
186
187   if(NULL == eventData)
188   {
189     return;
190   }
191
192   bool         removedPrevious  = false;
193   bool         removedSelected  = false;
194   bool         maxLengthReached = false;
195   unsigned int oldCursorPos     = eventData->mPrimaryCursorPosition;
196
197   DALI_LOG_INFO(gLogFilter, Debug::Verbose, "Controller::InsertText %p %s (%s) mPrimaryCursorPosition %d mPreEditFlag %d mPreEditStartPosition %d mPreEditLength %d\n", &controller, text.c_str(), (COMMIT == type ? "COMMIT" : "PRE_EDIT"), eventData->mPrimaryCursorPosition, eventData->mPreEditFlag, eventData->mPreEditStartPosition, eventData->mPreEditLength);
198
199   ModelPtr&        model        = impl.mModel;
200   LogicalModelPtr& logicalModel = model->mLogicalModel;
201
202   // TODO: At the moment the underline runs are only for pre-edit.
203   model->mVisualModel->mUnderlineRuns.Clear();
204
205   // Remove the previous InputMethodContext pre-edit.
206   if(eventData->mPreEditFlag && (0u != eventData->mPreEditLength))
207   {
208     removedPrevious = RemoveText(controller,
209                                  -static_cast<int>(eventData->mPrimaryCursorPosition - eventData->mPreEditStartPosition),
210                                  eventData->mPreEditLength,
211                                  DONT_UPDATE_INPUT_STYLE);
212
213     eventData->mPrimaryCursorPosition = eventData->mPreEditStartPosition;
214     eventData->mPreEditLength         = 0u;
215   }
216   else
217   {
218     // Remove the previous Selection.
219     removedSelected = RemoveSelectedText(controller);
220   }
221
222   Vector<Character> utf32Characters;
223   Length            characterCount = 0u;
224
225   if(!text.empty())
226   {
227     std::string redefinedText = text;
228
229     if(controller.mImpl->mInputFilter != NULL)
230     {
231       bool accepted = false;
232       bool rejected = false;
233
234       accepted = impl.mInputFilter->Filter(Toolkit::InputFilter::Property::ACCEPTED, redefinedText);
235       rejected = impl.mInputFilter->Filter(Toolkit::InputFilter::Property::REJECTED, redefinedText);
236
237       if(accepted)
238       {
239         // Signal emits when the string to be inserted is filtered by the accepted filter.
240         controller.mImpl->mEditableControlInterface->InputFiltered(Toolkit::InputFilter::Property::ACCEPTED);
241       }
242       if(rejected)
243       {
244         // Signal emits when the string to be inserted is filtered by the rejected filter.
245         controller.mImpl->mEditableControlInterface->InputFiltered(Toolkit::InputFilter::Property::REJECTED);
246       }
247     }
248
249     //  Convert text into UTF-32
250     utf32Characters.Resize(redefinedText.size());
251
252     // This is a bit horrible but std::string returns a (signed) char*
253     const uint8_t* utf8 = reinterpret_cast<const uint8_t*>(redefinedText.c_str());
254
255     // Transform a text array encoded in utf8 into an array encoded in utf32.
256     // It returns the actual number of characters.
257     characterCount = Utf8ToUtf32(utf8, redefinedText.size(), utf32Characters.Begin());
258     utf32Characters.Resize(characterCount);
259
260     DALI_ASSERT_DEBUG(redefinedText.size() >= utf32Characters.Count() && "Invalid UTF32 conversion length");
261     DALI_LOG_INFO(gLogFilter, Debug::Verbose, "UTF8 size %d, UTF32 size %d\n", redefinedText.size(), utf32Characters.Count());
262   }
263
264   if(0u != utf32Characters.Count()) // Check if Utf8ToUtf32 conversion succeeded
265   {
266     // The placeholder text is no longer needed
267     if(impl.IsShowingPlaceholderText())
268     {
269       ResetText(controller);
270     }
271
272     impl.ChangeState(EventData::EDITING);
273
274     // Handle the InputMethodContext (predicitive text) state changes
275     if(COMMIT == type)
276     {
277       // InputMethodContext is no longer handling key-events
278       impl.ClearPreEditFlag();
279     }
280     else // PRE_EDIT
281     {
282       if(!eventData->mPreEditFlag)
283       {
284         DALI_LOG_INFO(gLogFilter, Debug::Verbose, "Entered PreEdit state\n");
285
286         // Record the start of the pre-edit text
287         eventData->mPreEditStartPosition = eventData->mPrimaryCursorPosition;
288       }
289
290       eventData->mPreEditLength = utf32Characters.Count();
291       eventData->mPreEditFlag   = true;
292
293       DALI_LOG_INFO(gLogFilter, Debug::Verbose, "mPreEditStartPosition %d mPreEditLength %d\n", eventData->mPreEditStartPosition, eventData->mPreEditLength);
294     }
295
296     const Length numberOfCharactersInModel = logicalModel->mText.Count();
297
298     // Restrict new text to fit within Maximum characters setting.
299     Length temp_length      = (impl.mMaximumNumberOfCharacters > numberOfCharactersInModel ? impl.mMaximumNumberOfCharacters - numberOfCharactersInModel : 0);
300     Length maxSizeOfNewText = std::min(temp_length, characterCount);
301     maxLengthReached        = (characterCount > maxSizeOfNewText);
302
303     // The cursor position.
304     CharacterIndex& cursorIndex = eventData->mPrimaryCursorPosition;
305
306     // Update the text's style.
307
308     // Updates the text style runs by adding characters.
309     logicalModel->UpdateTextStyleRuns(cursorIndex, maxSizeOfNewText);
310
311     // Get the character index from the cursor index.
312     const CharacterIndex styleIndex = (cursorIndex > 0u) ? cursorIndex - 1u : 0u;
313
314     // Retrieve the text's style for the given index.
315     InputStyle style;
316     impl.RetrieveDefaultInputStyle(style);
317     logicalModel->RetrieveStyle(styleIndex, style);
318
319     InputStyle& inputStyle = eventData->mInputStyle;
320
321     // Whether to add a new text color run.
322     const bool addColorRun = (style.textColor != inputStyle.textColor) && !inputStyle.isDefaultColor;
323
324     // Whether to add a new font run.
325     const bool addFontNameRun   = (style.familyName != inputStyle.familyName) && inputStyle.isFamilyDefined;
326     const bool addFontWeightRun = (style.weight != inputStyle.weight) && inputStyle.isWeightDefined;
327     const bool addFontWidthRun  = (style.width != inputStyle.width) && inputStyle.isWidthDefined;
328     const bool addFontSlantRun  = (style.slant != inputStyle.slant) && inputStyle.isSlantDefined;
329     const bool addFontSizeRun   = (!Dali::Equals(style.size, inputStyle.size)) && inputStyle.isSizeDefined;
330
331     // Add style runs.
332     if(addColorRun)
333     {
334       const VectorBase::SizeType numberOfRuns = logicalModel->mColorRuns.Count();
335       logicalModel->mColorRuns.Resize(numberOfRuns + 1u);
336
337       ColorRun& colorRun                       = *(logicalModel->mColorRuns.Begin() + numberOfRuns);
338       colorRun.color                           = inputStyle.textColor;
339       colorRun.characterRun.characterIndex     = cursorIndex;
340       colorRun.characterRun.numberOfCharacters = maxSizeOfNewText;
341     }
342
343     if(addFontNameRun ||
344        addFontWeightRun ||
345        addFontWidthRun ||
346        addFontSlantRun ||
347        addFontSizeRun)
348     {
349       const VectorBase::SizeType numberOfRuns = logicalModel->mFontDescriptionRuns.Count();
350       logicalModel->mFontDescriptionRuns.Resize(numberOfRuns + 1u);
351
352       FontDescriptionRun& fontDescriptionRun = *(logicalModel->mFontDescriptionRuns.Begin() + numberOfRuns);
353
354       if(addFontNameRun)
355       {
356         fontDescriptionRun.familyLength = inputStyle.familyName.size();
357         fontDescriptionRun.familyName   = new char[fontDescriptionRun.familyLength];
358         memcpy(fontDescriptionRun.familyName, inputStyle.familyName.c_str(), fontDescriptionRun.familyLength);
359         fontDescriptionRun.familyDefined = true;
360
361         // The memory allocated for the font family name is freed when the font description is removed from the logical model.
362       }
363
364       if(addFontWeightRun)
365       {
366         fontDescriptionRun.weight        = inputStyle.weight;
367         fontDescriptionRun.weightDefined = true;
368       }
369
370       if(addFontWidthRun)
371       {
372         fontDescriptionRun.width        = inputStyle.width;
373         fontDescriptionRun.widthDefined = true;
374       }
375
376       if(addFontSlantRun)
377       {
378         fontDescriptionRun.slant        = inputStyle.slant;
379         fontDescriptionRun.slantDefined = true;
380       }
381
382       if(addFontSizeRun)
383       {
384         fontDescriptionRun.size        = static_cast<PointSize26Dot6>(inputStyle.size * impl.GetFontSizeScale() * 64.f);
385         fontDescriptionRun.sizeDefined = true;
386       }
387
388       fontDescriptionRun.characterRun.characterIndex     = cursorIndex;
389       fontDescriptionRun.characterRun.numberOfCharacters = maxSizeOfNewText;
390     }
391
392     // Insert at current cursor position.
393     Vector<Character>& modifyText = logicalModel->mText;
394
395     auto pos = modifyText.End();
396     if(cursorIndex < numberOfCharactersInModel)
397     {
398       pos = modifyText.Begin() + cursorIndex;
399     }
400     unsigned int realPos = static_cast<unsigned int>(pos - modifyText.Begin());
401     modifyText.Insert(pos, utf32Characters.Begin(), utf32Characters.Begin() + maxSizeOfNewText);
402
403     if(NULL != impl.mEditableControlInterface)
404     {
405       impl.mEditableControlInterface->TextInserted(realPos, maxSizeOfNewText, text);
406     }
407
408     TextUpdateInfo& textUpdateInfo = impl.mTextUpdateInfo;
409
410     // Mark the first paragraph to be updated.
411     if(Layout::Engine::SINGLE_LINE_BOX == impl.mLayoutEngine.GetLayout())
412     {
413       textUpdateInfo.mCharacterIndex             = 0;
414       textUpdateInfo.mNumberOfCharactersToRemove = textUpdateInfo.mPreviousNumberOfCharacters;
415       textUpdateInfo.mNumberOfCharactersToAdd    = numberOfCharactersInModel + maxSizeOfNewText;
416       textUpdateInfo.mClearAll                   = true;
417     }
418     else
419     {
420       textUpdateInfo.mCharacterIndex = std::min(cursorIndex, textUpdateInfo.mCharacterIndex);
421       textUpdateInfo.mNumberOfCharactersToAdd += maxSizeOfNewText;
422     }
423
424     if(impl.mMarkupProcessorEnabled)
425     {
426       InsertTextAnchor(controller, maxSizeOfNewText, cursorIndex);
427     }
428
429     // Update the cursor index.
430     cursorIndex += maxSizeOfNewText;
431
432     DALI_LOG_INFO(gLogFilter, Debug::Verbose, "Inserted %d characters, new size %d new cursor %d\n", maxSizeOfNewText, logicalModel->mText.Count(), eventData->mPrimaryCursorPosition);
433   }
434
435   if((0u == logicalModel->mText.Count()) &&
436      impl.IsPlaceholderAvailable())
437   {
438     // Show place-holder if empty after removing the pre-edit text
439     PlaceholderHandler::ShowPlaceholderText(impl);
440     eventData->mUpdateCursorPosition = true;
441     impl.ClearPreEditFlag();
442   }
443   else if(removedPrevious ||
444           removedSelected ||
445           (0 != utf32Characters.Count()))
446   {
447     // Queue an inserted event
448     impl.QueueModifyEvent(ModifyEvent::TEXT_INSERTED);
449
450     eventData->mUpdateCursorPosition = true;
451     if(removedSelected)
452     {
453       eventData->mScrollAfterDelete = true;
454     }
455     else
456     {
457       eventData->mScrollAfterUpdatePosition = true;
458     }
459   }
460
461   if(nullptr != impl.mEditableControlInterface)
462   {
463     impl.mEditableControlInterface->CursorPositionChanged(oldCursorPos, eventData->mPrimaryCursorPosition);
464   }
465
466   if(maxLengthReached)
467   {
468     DALI_LOG_INFO(gLogFilter, Debug::Verbose, "MaxLengthReached (%d)\n", logicalModel->mText.Count());
469
470     impl.ResetInputMethodContext();
471
472     if(NULL != impl.mEditableControlInterface)
473     {
474       // Do this last since it provides callbacks into application code
475       impl.mEditableControlInterface->MaxLengthReached();
476     }
477   }
478 }
479
480 void Controller::TextUpdater::PasteText(Controller& controller, const std::string& stringToPaste)
481 {
482   InsertText(controller, stringToPaste, Text::Controller::COMMIT);
483   Controller::Impl& impl = *controller.mImpl;
484   impl.ChangeState(EventData::EDITING);
485   impl.RequestRelayout();
486
487   if(NULL != impl.mEditableControlInterface)
488   {
489     // Do this last since it provides callbacks into application code
490     impl.mEditableControlInterface->TextChanged(true);
491   }
492 }
493
494 bool Controller::TextUpdater::RemoveText(
495   Controller&          controller,
496   int                  cursorOffset,
497   int                  numberOfCharacters,
498   UpdateInputStyleType type)
499 {
500   bool removed   = false;
501   bool removeAll = false;
502
503   Controller::Impl& impl      = *controller.mImpl;
504   EventData*&       eventData = impl.mEventData;
505
506   if(nullptr == eventData)
507   {
508     return removed;
509   }
510
511   ModelPtr&        model        = impl.mModel;
512   LogicalModelPtr& logicalModel = model->mLogicalModel;
513   VisualModelPtr&  visualModel  = model->mVisualModel;
514
515   DALI_LOG_INFO(gLogFilter, Debug::General, "Controller::RemoveText %p mText.Count() %d cursor %d cursorOffset %d numberOfCharacters %d\n", &controller, logicalModel->mText.Count(), eventData->mPrimaryCursorPosition, cursorOffset, numberOfCharacters);
516
517   if(!impl.IsShowingPlaceholderText())
518   {
519     // Delete at current cursor position
520     Vector<Character>& currentText         = logicalModel->mText;
521     CharacterIndex&    previousCursorIndex = eventData->mPrimaryCursorPosition;
522
523     CharacterIndex cursorIndex = 0;
524
525     // Validate the cursor position & number of characters
526     if((static_cast<int>(eventData->mPrimaryCursorPosition) + cursorOffset) >= 0)
527     {
528       cursorIndex = eventData->mPrimaryCursorPosition + cursorOffset;
529     }
530
531     //Handle Emoji clustering for cursor handling
532     // Deletion case: this is handling the deletion cases when the cursor is before or after Emoji
533     //  - Before: when use delete key and cursor is before Emoji (cursorOffset = -1)
534     //  - After: when use backspace key and cursor is after Emoji (cursorOffset = 0)
535
536     const Script script = logicalModel->GetScript(cursorIndex);
537     if((numberOfCharacters == 1u) &&
538        (IsOneOfEmojiScripts(script)))
539     {
540       //TODO: Use this clustering for Emoji cases only. This needs more testing to generalize to all scripts.
541       CharacterRun emojiClusteredCharacters = RetrieveClusteredCharactersOfCharacterIndex(visualModel, logicalModel, cursorIndex);
542       Length       actualNumberOfCharacters = emojiClusteredCharacters.numberOfCharacters;
543
544       //Set cursorIndex at the first characterIndex of clustred Emoji
545       cursorIndex = emojiClusteredCharacters.characterIndex;
546
547       numberOfCharacters = actualNumberOfCharacters;
548     }
549
550     if((cursorIndex + numberOfCharacters) > currentText.Count())
551     {
552       numberOfCharacters = currentText.Count() - cursorIndex;
553     }
554
555     if((cursorIndex == 0) && (currentText.Count() - numberOfCharacters == 0))
556     {
557       removeAll = true;
558     }
559
560     TextUpdateInfo& textUpdateInfo = impl.mTextUpdateInfo;
561
562     if(eventData->mPreEditFlag || removeAll || // If the preedit flag is enabled, it means two (or more) of them came together i.e. when two keys have been pressed at the same time.
563        ((cursorIndex + numberOfCharacters) <= textUpdateInfo.mPreviousNumberOfCharacters))
564     {
565       // Mark the paragraphs to be updated.
566       if(Layout::Engine::SINGLE_LINE_BOX == impl.mLayoutEngine.GetLayout())
567       {
568         textUpdateInfo.mCharacterIndex             = 0;
569         textUpdateInfo.mNumberOfCharactersToRemove = textUpdateInfo.mPreviousNumberOfCharacters;
570         textUpdateInfo.mNumberOfCharactersToAdd    = textUpdateInfo.mPreviousNumberOfCharacters - numberOfCharacters;
571         textUpdateInfo.mClearAll                   = true;
572       }
573       else
574       {
575         textUpdateInfo.mCharacterIndex = std::min(cursorIndex, textUpdateInfo.mCharacterIndex);
576         textUpdateInfo.mNumberOfCharactersToRemove += numberOfCharacters;
577       }
578
579       // Update the input style and remove the text's style before removing the text.
580
581       if(UPDATE_INPUT_STYLE == type)
582       {
583         InputStyle& eventDataInputStyle = eventData->mInputStyle;
584
585         // Keep a copy of the current input style.
586         InputStyle currentInputStyle;
587         currentInputStyle.Copy(eventDataInputStyle);
588
589         // Set first the default input style.
590         impl.RetrieveDefaultInputStyle(eventDataInputStyle);
591
592         // Update the input style.
593         logicalModel->RetrieveStyle(cursorIndex, eventDataInputStyle);
594
595         // Compare if the input style has changed.
596         const bool hasInputStyleChanged = !currentInputStyle.Equal(eventDataInputStyle);
597
598         if(hasInputStyleChanged)
599         {
600           const InputStyle::Mask styleChangedMask = currentInputStyle.GetInputStyleChangeMask(eventDataInputStyle);
601           // Queue the input style changed signal.
602           eventData->mInputStyleChangedQueue.PushBack(styleChangedMask);
603         }
604       }
605
606       // If the number of current text and the number of characters to be deleted are same,
607       // it means all texts should be removed and all Preedit variables should be initialized.
608       if(removeAll)
609       {
610         impl.ClearPreEditFlag();
611         textUpdateInfo.mNumberOfCharactersToAdd = 0;
612       }
613
614       // Updates the text style runs by removing characters. Runs with no characters are removed.
615       logicalModel->UpdateTextStyleRuns(cursorIndex, -numberOfCharacters);
616
617       // Remove the characters.
618       Vector<Character>::Iterator first = currentText.Begin() + cursorIndex;
619       Vector<Character>::Iterator last  = first + numberOfCharacters;
620
621       if(NULL != impl.mEditableControlInterface)
622       {
623         std::string utf8;
624         Utf32ToUtf8(first, numberOfCharacters, utf8);
625         impl.mEditableControlInterface->TextDeleted(cursorIndex, numberOfCharacters, utf8);
626       }
627
628       currentText.Erase(first, last);
629
630       if(impl.mMarkupProcessorEnabled)
631       {
632         RemoveTextAnchor(controller, cursorOffset, numberOfCharacters, previousCursorIndex);
633       }
634
635       if(nullptr != impl.mEditableControlInterface)
636       {
637         impl.mEditableControlInterface->CursorPositionChanged(previousCursorIndex, cursorIndex);
638       }
639
640       // Cursor position retreat
641       previousCursorIndex = cursorIndex;
642
643       eventData->mScrollAfterDelete = true;
644
645       if(EventData::INACTIVE == eventData->mState)
646       {
647         impl.ChangeState(EventData::EDITING);
648       }
649
650       DALI_LOG_INFO(gLogFilter, Debug::General, "Controller::RemoveText %p removed %d\n", &controller, numberOfCharacters);
651       removeAll = false;
652       removed   = true;
653     }
654   }
655
656   return removed;
657 }
658
659 bool Controller::TextUpdater::RemoveSelectedText(Controller& controller)
660 {
661   bool textRemoved(false);
662
663   Controller::Impl& impl = *controller.mImpl;
664
665   if(EventData::SELECTING == impl.mEventData->mState)
666   {
667     std::string removedString;
668     uint32_t    oldSelStart = impl.mEventData->mLeftSelectionPosition;
669     uint32_t    oldSelEnd   = impl.mEventData->mRightSelectionPosition;
670
671     impl.RetrieveSelection(removedString, true);
672
673     if(!removedString.empty())
674     {
675       textRemoved = true;
676       impl.ChangeState(EventData::EDITING);
677
678       if(impl.mMarkupProcessorEnabled)
679       {
680         int             cursorOffset        = -1;
681         int             numberOfCharacters  = removedString.length();
682         CharacterIndex& cursorIndex         = impl.mEventData->mPrimaryCursorPosition;
683         CharacterIndex  previousCursorIndex = cursorIndex + numberOfCharacters;
684
685         RemoveTextAnchor(controller, cursorOffset, numberOfCharacters, previousCursorIndex);
686       }
687
688       if(impl.mSelectableControlInterface != nullptr)
689       {
690         impl.mSelectableControlInterface->SelectionChanged(oldSelStart, oldSelEnd, impl.mEventData->mPrimaryCursorPosition, impl.mEventData->mPrimaryCursorPosition);
691       }
692     }
693   }
694
695   return textRemoved;
696 }
697
698 void Controller::TextUpdater::ResetText(Controller& controller)
699 {
700   Controller::Impl& impl         = *controller.mImpl;
701   LogicalModelPtr&  logicalModel = impl.mModel->mLogicalModel;
702
703   // Reset spanned-text
704   logicalModel->mSpannedTextPlaced = false;
705
706   // Reset buffers.
707   logicalModel->mText.Clear();
708
709   // Reset the embedded images buffer.
710   logicalModel->ClearEmbeddedImages();
711
712   // Reset the anchors buffer.
713   logicalModel->ClearAnchors();
714
715   // We have cleared everything including the placeholder-text
716   impl.PlaceholderCleared();
717
718   impl.mTextUpdateInfo.mCharacterIndex             = 0u;
719   impl.mTextUpdateInfo.mNumberOfCharactersToRemove = impl.mTextUpdateInfo.mPreviousNumberOfCharacters;
720   impl.mTextUpdateInfo.mNumberOfCharactersToAdd    = 0u;
721
722   // Clear any previous text.
723   impl.mTextUpdateInfo.mClearAll = true;
724
725   // The natural size needs to be re-calculated.
726   impl.mRecalculateNaturalSize = true;
727
728   // The text direction needs to be updated.
729   impl.mUpdateTextDirection = true;
730
731   // Apply modifications to the model
732   impl.mOperationsPending = ALL_OPERATIONS;
733 }
734
735 void Controller::TextUpdater::InsertTextAnchor(Controller& controller, int numberOfCharacters, CharacterIndex previousCursorIndex)
736 {
737   Controller::Impl& impl         = *controller.mImpl;
738   ModelPtr&         model        = impl.mModel;
739   LogicalModelPtr&  logicalModel = model->mLogicalModel;
740
741   for(auto& anchor : logicalModel->mAnchors)
742   {
743     if(anchor.endIndex < previousCursorIndex) //      [anchor]  CUR
744     {
745       continue;
746     }
747     if(anchor.startIndex < previousCursorIndex) //      [anCURr]
748     {
749       anchor.endIndex += numberOfCharacters;
750     }
751     else // CUR  [anchor]
752     {
753       anchor.startIndex += numberOfCharacters;
754       anchor.endIndex += numberOfCharacters;
755     }
756     DALI_LOG_INFO(gLogFilter, Debug::General, "Controller::InsertTextAnchor[%p] Anchor[%s] start[%d] end[%d]\n", &controller, anchor.href, anchor.startIndex, anchor.endIndex);
757   }
758 }
759
760 void Controller::TextUpdater::RemoveTextAnchor(Controller& controller, int cursorOffset, int numberOfCharacters, CharacterIndex previousCursorIndex)
761 {
762   Controller::Impl&        impl         = *controller.mImpl;
763   ModelPtr&                model        = impl.mModel;
764   LogicalModelPtr&         logicalModel = model->mLogicalModel;
765   Vector<Anchor>::Iterator it           = logicalModel->mAnchors.Begin();
766
767   while(it != logicalModel->mAnchors.End())
768   {
769     Anchor& anchor = *it;
770
771     if(anchor.endIndex <= previousCursorIndex && cursorOffset == 0) // [anchor]    CUR >>
772     {
773       // Nothing happens.
774     }
775     else if(anchor.endIndex <= previousCursorIndex && cursorOffset == -1) // [anchor] << CUR
776     {
777       int endIndex = anchor.endIndex;
778       int offset   = previousCursorIndex - endIndex;
779       int index    = endIndex - (numberOfCharacters - offset);
780
781       if(index < endIndex)
782       {
783         endIndex = index;
784       }
785
786       if((int)anchor.startIndex >= endIndex)
787       {
788         if(anchor.href)
789         {
790           delete[] anchor.href;
791         }
792         it = logicalModel->mAnchors.Erase(it);
793         continue;
794       }
795       else
796       {
797         anchor.endIndex = endIndex;
798       }
799     }
800     else if(anchor.startIndex >= previousCursorIndex && cursorOffset == -1) // << CUR    [anchor]
801     {
802       anchor.startIndex -= numberOfCharacters;
803       anchor.endIndex -= numberOfCharacters;
804     }
805     else if(anchor.startIndex >= previousCursorIndex && cursorOffset == 0) //    CUR >> [anchor]
806     {
807       int startIndex = anchor.startIndex;
808       int endIndex   = anchor.endIndex;
809       int index      = previousCursorIndex + numberOfCharacters - 1;
810
811       if(startIndex > index)
812       {
813         anchor.startIndex -= numberOfCharacters;
814         anchor.endIndex -= numberOfCharacters;
815       }
816       else if(endIndex > index + 1)
817       {
818         anchor.endIndex -= numberOfCharacters;
819       }
820       else
821       {
822         if(anchor.href)
823         {
824           delete[] anchor.href;
825         }
826         it = logicalModel->mAnchors.Erase(it);
827         continue;
828       }
829     }
830     else if(cursorOffset == -1) // [<< CUR]
831     {
832       int startIndex = anchor.startIndex;
833       int index      = previousCursorIndex - numberOfCharacters;
834
835       if(startIndex >= index)
836       {
837         anchor.startIndex = index;
838       }
839       anchor.endIndex -= numberOfCharacters;
840     }
841     else if(cursorOffset == 0) // [CUR >>]
842     {
843       anchor.endIndex -= numberOfCharacters;
844     }
845     else
846     {
847       // When this condition is reached, someting is wrong.
848       DALI_LOG_ERROR("Controller::RemoveTextAnchor[%p] Invaild state cursorOffset[%d]\n", &controller, cursorOffset);
849     }
850
851     DALI_LOG_INFO(gLogFilter, Debug::General, "Controller::RemoveTextAnchor[%p] Anchor[%s] start[%d] end[%d]\n", &controller, anchor.href, anchor.startIndex, anchor.endIndex);
852
853     it++;
854   }
855 }
856
857 } // namespace Text
858
859 } // namespace Toolkit
860
861 } // namespace Dali