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