fix incorrect calculaion of natural size in text
[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
477   Controller::Impl& impl      = *controller.mImpl;
478   EventData*&       eventData = impl.mEventData;
479
480   if(nullptr == eventData)
481   {
482     return removed;
483   }
484
485   ModelPtr&        model        = impl.mModel;
486   LogicalModelPtr& logicalModel = model->mLogicalModel;
487   VisualModelPtr&  visualModel  = model->mVisualModel;
488
489   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);
490
491   if(!impl.IsShowingPlaceholderText())
492   {
493     // Delete at current cursor position
494     Vector<Character>& currentText         = logicalModel->mText;
495     CharacterIndex&    previousCursorIndex = eventData->mPrimaryCursorPosition;
496
497     CharacterIndex cursorIndex = 0;
498
499     // Validate the cursor position & number of characters
500     if((static_cast<int>(eventData->mPrimaryCursorPosition) + cursorOffset) >= 0)
501     {
502       cursorIndex = eventData->mPrimaryCursorPosition + cursorOffset;
503     }
504
505     //Handle Emoji clustering for cursor handling
506     // Deletion case: this is handling the deletion cases when the cursor is before or after Emoji
507     //  - Before: when use delete key and cursor is before Emoji (cursorOffset = -1)
508     //  - After: when use backspace key and cursor is after Emoji (cursorOffset = 0)
509
510     const Script script = logicalModel->GetScript(cursorIndex);
511     if((numberOfCharacters == 1u) &&
512        (IsOneOfEmojiScripts(script)))
513     {
514       //TODO: Use this clustering for Emoji cases only. This needs more testing to generalize to all scripts.
515       CharacterRun emojiClusteredCharacters = RetrieveClusteredCharactersOfCharacterIndex(visualModel, logicalModel, cursorIndex);
516       Length       actualNumberOfCharacters = emojiClusteredCharacters.numberOfCharacters;
517
518       //Set cursorIndex at the first characterIndex of clustred Emoji
519       cursorIndex = emojiClusteredCharacters.characterIndex;
520
521       numberOfCharacters = actualNumberOfCharacters;
522     }
523
524     if((cursorIndex + numberOfCharacters) > currentText.Count())
525     {
526       numberOfCharacters = currentText.Count() - cursorIndex;
527     }
528
529     TextUpdateInfo& textUpdateInfo = impl.mTextUpdateInfo;
530
531     if(eventData->mPreEditFlag || // 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.
532        ((cursorIndex + numberOfCharacters) <= textUpdateInfo.mPreviousNumberOfCharacters))
533     {
534       // Mark the paragraphs to be updated.
535       if(Layout::Engine::SINGLE_LINE_BOX == impl.mLayoutEngine.GetLayout())
536       {
537         textUpdateInfo.mCharacterIndex             = 0;
538         textUpdateInfo.mNumberOfCharactersToRemove = textUpdateInfo.mPreviousNumberOfCharacters;
539         textUpdateInfo.mNumberOfCharactersToAdd    = textUpdateInfo.mPreviousNumberOfCharacters - numberOfCharacters;
540         textUpdateInfo.mClearAll                   = true;
541       }
542       else
543       {
544         textUpdateInfo.mCharacterIndex = std::min(cursorIndex, textUpdateInfo.mCharacterIndex);
545         textUpdateInfo.mNumberOfCharactersToRemove += numberOfCharacters;
546       }
547
548       // Update the input style and remove the text's style before removing the text.
549
550       if(UPDATE_INPUT_STYLE == type)
551       {
552         InputStyle& eventDataInputStyle = eventData->mInputStyle;
553
554         // Keep a copy of the current input style.
555         InputStyle currentInputStyle;
556         currentInputStyle.Copy(eventDataInputStyle);
557
558         // Set first the default input style.
559         impl.RetrieveDefaultInputStyle(eventDataInputStyle);
560
561         // Update the input style.
562         logicalModel->RetrieveStyle(cursorIndex, eventDataInputStyle);
563
564         // Compare if the input style has changed.
565         const bool hasInputStyleChanged = !currentInputStyle.Equal(eventDataInputStyle);
566
567         if(hasInputStyleChanged)
568         {
569           const InputStyle::Mask styleChangedMask = currentInputStyle.GetInputStyleChangeMask(eventDataInputStyle);
570           // Queue the input style changed signal.
571           eventData->mInputStyleChangedQueue.PushBack(styleChangedMask);
572         }
573       }
574
575       // If the number of current text and the number of characters to be deleted are same,
576       // it means all texts should be removed and all Preedit variables should be initialized.
577       if((currentText.Count() - numberOfCharacters == 0) && (cursorIndex == 0))
578       {
579         impl.ClearPreEditFlag();
580         textUpdateInfo.mNumberOfCharactersToAdd = 0;
581       }
582
583       // Updates the text style runs by removing characters. Runs with no characters are removed.
584       logicalModel->UpdateTextStyleRuns(cursorIndex, -numberOfCharacters);
585
586       // Remove the characters.
587       Vector<Character>::Iterator first = currentText.Begin() + cursorIndex;
588       Vector<Character>::Iterator last  = first + numberOfCharacters;
589
590       if(NULL != impl.mEditableControlInterface)
591       {
592         std::string utf8;
593         Utf32ToUtf8(first, numberOfCharacters, utf8);
594         impl.mEditableControlInterface->TextDeleted(cursorIndex, numberOfCharacters, utf8);
595       }
596
597       currentText.Erase(first, last);
598
599       if(impl.mMarkupProcessorEnabled)
600       {
601         RemoveTextAnchor(controller, cursorOffset, numberOfCharacters, previousCursorIndex);
602       }
603
604       if(nullptr != impl.mEditableControlInterface)
605       {
606         impl.mEditableControlInterface->CursorPositionChanged(previousCursorIndex, cursorIndex);
607       }
608
609       // Cursor position retreat
610       previousCursorIndex = cursorIndex;
611
612       eventData->mScrollAfterDelete = true;
613
614       if(EventData::INACTIVE == eventData->mState)
615       {
616         impl.ChangeState(EventData::EDITING);
617       }
618
619       DALI_LOG_INFO(gLogFilter, Debug::General, "Controller::RemoveText %p removed %d\n", &controller, numberOfCharacters);
620       removed = true;
621     }
622   }
623
624   return removed;
625 }
626
627 bool Controller::TextUpdater::RemoveSelectedText(Controller& controller)
628 {
629   bool textRemoved(false);
630
631   Controller::Impl& impl = *controller.mImpl;
632
633   if(EventData::SELECTING == impl.mEventData->mState)
634   {
635     std::string removedString;
636     uint32_t    oldSelStart = impl.mEventData->mLeftSelectionPosition;
637     uint32_t    oldSelEnd   = impl.mEventData->mRightSelectionPosition;
638
639     impl.RetrieveSelection(removedString, true);
640
641     if(!removedString.empty())
642     {
643       textRemoved = true;
644       impl.ChangeState(EventData::EDITING);
645
646       if(impl.mMarkupProcessorEnabled)
647       {
648         int             cursorOffset        = -1;
649         int             numberOfCharacters  = removedString.length();
650         CharacterIndex& cursorIndex         = impl.mEventData->mPrimaryCursorPosition;
651         CharacterIndex  previousCursorIndex = cursorIndex + numberOfCharacters;
652
653         RemoveTextAnchor(controller, cursorOffset, numberOfCharacters, previousCursorIndex);
654       }
655
656       if(impl.mSelectableControlInterface != nullptr)
657       {
658         impl.mSelectableControlInterface->SelectionChanged(oldSelStart, oldSelEnd, impl.mEventData->mPrimaryCursorPosition, impl.mEventData->mPrimaryCursorPosition);
659       }
660     }
661   }
662
663   return textRemoved;
664 }
665
666 void Controller::TextUpdater::ResetText(Controller& controller)
667 {
668   Controller::Impl& impl         = *controller.mImpl;
669   LogicalModelPtr&  logicalModel = impl.mModel->mLogicalModel;
670
671   // Reset buffers.
672   logicalModel->mText.Clear();
673
674   // Reset the embedded images buffer.
675   logicalModel->ClearEmbeddedImages();
676
677   // Reset the anchors buffer.
678   logicalModel->ClearAnchors();
679
680   // We have cleared everything including the placeholder-text
681   impl.PlaceholderCleared();
682
683   impl.mTextUpdateInfo.mCharacterIndex             = 0u;
684   impl.mTextUpdateInfo.mNumberOfCharactersToRemove = impl.mTextUpdateInfo.mPreviousNumberOfCharacters;
685   impl.mTextUpdateInfo.mNumberOfCharactersToAdd    = 0u;
686
687   // Clear any previous text.
688   impl.mTextUpdateInfo.mClearAll = true;
689
690   // The natural size needs to be re-calculated.
691   impl.mRecalculateNaturalSize = true;
692
693   // The text direction needs to be updated.
694   impl.mUpdateTextDirection = true;
695
696   // Apply modifications to the model
697   impl.mOperationsPending = ALL_OPERATIONS;
698 }
699
700 void Controller::TextUpdater::InsertTextAnchor(Controller& controller, int numberOfCharacters, CharacterIndex previousCursorIndex)
701 {
702   Controller::Impl& impl         = *controller.mImpl;
703   ModelPtr&         model        = impl.mModel;
704   LogicalModelPtr&  logicalModel = model->mLogicalModel;
705
706   for(auto& anchor : logicalModel->mAnchors)
707   {
708     if(anchor.endIndex < previousCursorIndex) //      [anchor]  CUR
709     {
710       continue;
711     }
712     if(anchor.startIndex < previousCursorIndex) //      [anCURr]
713     {
714       anchor.endIndex += numberOfCharacters;
715     }
716     else // CUR  [anchor]
717     {
718       anchor.startIndex += numberOfCharacters;
719       anchor.endIndex += numberOfCharacters;
720     }
721     DALI_LOG_INFO(gLogFilter, Debug::General, "Controller::InsertTextAnchor[%p] Anchor[%s] start[%d] end[%d]\n", &controller, anchor.href, anchor.startIndex, anchor.endIndex);
722   }
723 }
724
725 void Controller::TextUpdater::RemoveTextAnchor(Controller& controller, int cursorOffset, int numberOfCharacters, CharacterIndex previousCursorIndex)
726 {
727   Controller::Impl&        impl         = *controller.mImpl;
728   ModelPtr&                model        = impl.mModel;
729   LogicalModelPtr&         logicalModel = model->mLogicalModel;
730   Vector<Anchor>::Iterator it           = logicalModel->mAnchors.Begin();
731
732   while(it != logicalModel->mAnchors.End())
733   {
734     Anchor& anchor = *it;
735
736     if(anchor.endIndex <= previousCursorIndex && cursorOffset == 0) // [anchor]    CUR >>
737     {
738       // Nothing happens.
739     }
740     else if(anchor.endIndex <= previousCursorIndex && cursorOffset == -1) // [anchor] << CUR
741     {
742       int endIndex = anchor.endIndex;
743       int offset   = previousCursorIndex - endIndex;
744       int index    = endIndex - (numberOfCharacters - offset);
745
746       if(index < endIndex)
747       {
748         endIndex = index;
749       }
750
751       if((int)anchor.startIndex >= endIndex)
752       {
753         if(anchor.href)
754         {
755           delete[] anchor.href;
756         }
757         it = logicalModel->mAnchors.Erase(it);
758         continue;
759       }
760       else
761       {
762         anchor.endIndex = endIndex;
763       }
764     }
765     else if(anchor.startIndex >= previousCursorIndex && cursorOffset == -1) // << CUR    [anchor]
766     {
767       anchor.startIndex -= numberOfCharacters;
768       anchor.endIndex -= numberOfCharacters;
769     }
770     else if(anchor.startIndex >= previousCursorIndex && cursorOffset == 0) //    CUR >> [anchor]
771     {
772       int startIndex = anchor.startIndex;
773       int endIndex   = anchor.endIndex;
774       int index      = previousCursorIndex + numberOfCharacters - 1;
775
776       if(startIndex > index)
777       {
778         anchor.startIndex -= numberOfCharacters;
779         anchor.endIndex -= numberOfCharacters;
780       }
781       else if(endIndex > index + 1)
782       {
783         anchor.endIndex -= numberOfCharacters;
784       }
785       else
786       {
787         if(anchor.href)
788         {
789           delete[] anchor.href;
790         }
791         it = logicalModel->mAnchors.Erase(it);
792         continue;
793       }
794     }
795     else if(cursorOffset == -1) // [<< CUR]
796     {
797       int startIndex = anchor.startIndex;
798       int index      = previousCursorIndex - numberOfCharacters;
799
800       if(startIndex >= index)
801       {
802         anchor.startIndex = index;
803       }
804       anchor.endIndex -= numberOfCharacters;
805     }
806     else if(cursorOffset == 0) // [CUR >>]
807     {
808       anchor.endIndex -= numberOfCharacters;
809     }
810     else
811     {
812       // When this condition is reached, someting is wrong.
813       DALI_LOG_ERROR("Controller::RemoveTextAnchor[%p] Invaild state cursorOffset[%d]\n", &controller, cursorOffset);
814     }
815
816     DALI_LOG_INFO(gLogFilter, Debug::General, "Controller::RemoveTextAnchor[%p] Anchor[%s] start[%d] end[%d]\n", &controller, anchor.href, anchor.startIndex, anchor.endIndex);
817
818     it++;
819   }
820 }
821
822 } // namespace Text
823
824 } // namespace Toolkit
825
826 } // namespace Dali