Add GetCharacterIndexAtPosition API
[platform/core/uifw/dali-toolkit.git] / dali-toolkit / internal / controls / text-controls / text-editor-impl.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/controls/text-controls/text-editor-impl.h>
20
21 // EXTERNAL INCLUDES
22 #include <dali/devel-api/actors/actor-devel.h>
23 #include <dali/devel-api/common/stage.h>
24 #include <dali/devel-api/object/property-helper-devel.h>
25 #include <dali/integration-api/adaptor-framework/adaptor.h>
26 #include <dali/integration-api/debug.h>
27 #include <dali/public-api/actors/layer.h>
28 #include <dali/public-api/adaptor-framework/key.h>
29 #include <dali/public-api/common/dali-common.h>
30 #include <dali/public-api/object/type-registry-helper.h>
31 #include <cstring>
32 #include <limits>
33
34 // INTERNAL INCLUDES
35 #include <dali-toolkit/devel-api/controls/control-devel.h>
36 #include <dali-toolkit/devel-api/text/rendering-backend.h>
37 #include <dali-toolkit/internal/controls/control/control-data-impl.h>
38 #include <dali-toolkit/internal/controls/text-controls/common-text-utils.h>
39 #include <dali-toolkit/internal/controls/text-controls/text-editor-property-handler.h>
40 #include <dali-toolkit/internal/focus-manager/keyboard-focus-manager-impl.h>
41 #include <dali-toolkit/internal/styling/style-manager-impl.h>
42 #include <dali-toolkit/internal/text/rendering/text-backend.h>
43 #include <dali-toolkit/internal/text/text-effects-style.h>
44 #include <dali-toolkit/internal/text/text-enumerations-impl.h>
45 #include <dali-toolkit/internal/text/text-font-style.h>
46 #include <dali-toolkit/internal/text/text-view.h>
47 #include <dali-toolkit/public-api/text/text-enumerations.h>
48 #include <dali-toolkit/public-api/visuals/color-visual-properties.h>
49 #include <dali-toolkit/public-api/visuals/visual-properties.h>
50
51 using namespace Dali::Toolkit::Text;
52
53 #if defined(DEBUG_ENABLED)
54 Debug::Filter* gTextEditorLogFilter = Debug::Filter::New(Debug::Concise, true, "LOG_TEXT_CONTROLS");
55 #endif
56
57 namespace Dali
58 {
59 namespace Toolkit
60 {
61 namespace Internal
62 {
63 namespace // unnamed namespace
64 {
65 const unsigned int DEFAULT_RENDERING_BACKEND = Dali::Toolkit::DevelText::DEFAULT_RENDERING_BACKEND;
66 const float        DEFAULT_SCROLL_SPEED      = 1200.f; ///< The default scroll speed for the text editor in pixels/second.
67 } // unnamed namespace
68
69 namespace
70 {
71 const char* const SCROLL_BAR_POSITION("sourcePosition");
72 const char* const SCROLL_BAR_POSITION_MIN("sourcePositionMin");
73 const char* const SCROLL_BAR_POSITION_MAX("sourcePositionMax");
74 const char* const SCROLL_BAR_CONTENT_SIZE("sourceContentSize");
75
76 // Type registration
77 BaseHandle Create()
78 {
79   return Toolkit::TextEditor::New();
80 }
81
82 // clang-format off
83 // Setup properties, signals and actions using the type-registry.
84 DALI_TYPE_REGISTRATION_BEGIN(Toolkit::TextEditor, Toolkit::Control, Create);
85
86 DALI_PROPERTY_REGISTRATION(Toolkit,                 TextEditor, "text",                                 STRING,    TEXT                                )
87 DALI_PROPERTY_REGISTRATION(Toolkit,                 TextEditor, "textColor",                            VECTOR4,   TEXT_COLOR                          )
88 DALI_PROPERTY_REGISTRATION(Toolkit,                 TextEditor, "fontFamily",                           STRING,    FONT_FAMILY                         )
89 DALI_PROPERTY_REGISTRATION(Toolkit,                 TextEditor, "fontStyle",                            MAP,       FONT_STYLE                          )
90 DALI_PROPERTY_REGISTRATION(Toolkit,                 TextEditor, "pointSize",                            FLOAT,     POINT_SIZE                          )
91 DALI_PROPERTY_REGISTRATION(Toolkit,                 TextEditor, "horizontalAlignment",                  STRING,    HORIZONTAL_ALIGNMENT                )
92 DALI_PROPERTY_REGISTRATION(Toolkit,                 TextEditor, "scrollThreshold",                      FLOAT,     SCROLL_THRESHOLD                    )
93 DALI_PROPERTY_REGISTRATION(Toolkit,                 TextEditor, "scrollSpeed",                          FLOAT,     SCROLL_SPEED                        )
94 DALI_PROPERTY_REGISTRATION(Toolkit,                 TextEditor, "primaryCursorColor",                   VECTOR4,   PRIMARY_CURSOR_COLOR                )
95 DALI_PROPERTY_REGISTRATION(Toolkit,                 TextEditor, "secondaryCursorColor",                 VECTOR4,   SECONDARY_CURSOR_COLOR              )
96 DALI_PROPERTY_REGISTRATION(Toolkit,                 TextEditor, "enableCursorBlink",                    BOOLEAN,   ENABLE_CURSOR_BLINK                 )
97 DALI_PROPERTY_REGISTRATION(Toolkit,                 TextEditor, "cursorBlinkInterval",                  FLOAT,     CURSOR_BLINK_INTERVAL               )
98 DALI_PROPERTY_REGISTRATION(Toolkit,                 TextEditor, "cursorBlinkDuration",                  FLOAT,     CURSOR_BLINK_DURATION               )
99 DALI_PROPERTY_REGISTRATION(Toolkit,                 TextEditor, "cursorWidth",                          INTEGER,   CURSOR_WIDTH                        )
100 DALI_PROPERTY_REGISTRATION(Toolkit,                 TextEditor, "grabHandleImage",                      STRING,    GRAB_HANDLE_IMAGE                   )
101 DALI_PROPERTY_REGISTRATION(Toolkit,                 TextEditor, "grabHandlePressedImage",               STRING,    GRAB_HANDLE_PRESSED_IMAGE           )
102 DALI_PROPERTY_REGISTRATION(Toolkit,                 TextEditor, "selectionHandleImageLeft",             MAP,       SELECTION_HANDLE_IMAGE_LEFT         )
103 DALI_PROPERTY_REGISTRATION(Toolkit,                 TextEditor, "selectionHandleImageRight",            MAP,       SELECTION_HANDLE_IMAGE_RIGHT        )
104 DALI_PROPERTY_REGISTRATION(Toolkit,                 TextEditor, "selectionHandlePressedImageLeft",      MAP,       SELECTION_HANDLE_PRESSED_IMAGE_LEFT )
105 DALI_PROPERTY_REGISTRATION(Toolkit,                 TextEditor, "selectionHandlePressedImageRight",     MAP,       SELECTION_HANDLE_PRESSED_IMAGE_RIGHT)
106 DALI_PROPERTY_REGISTRATION(Toolkit,                 TextEditor, "selectionHandleMarkerImageLeft",       MAP,       SELECTION_HANDLE_MARKER_IMAGE_LEFT  )
107 DALI_PROPERTY_REGISTRATION(Toolkit,                 TextEditor, "selectionHandleMarkerImageRight",      MAP,       SELECTION_HANDLE_MARKER_IMAGE_RIGHT )
108 DALI_PROPERTY_REGISTRATION(Toolkit,                 TextEditor, "selectionHighlightColor",              VECTOR4,   SELECTION_HIGHLIGHT_COLOR           )
109 DALI_PROPERTY_REGISTRATION(Toolkit,                 TextEditor, "decorationBoundingBox",                RECTANGLE, DECORATION_BOUNDING_BOX             )
110 DALI_PROPERTY_REGISTRATION(Toolkit,                 TextEditor, "enableMarkup",                         BOOLEAN,   ENABLE_MARKUP                       )
111 DALI_PROPERTY_REGISTRATION(Toolkit,                 TextEditor, "inputColor",                           VECTOR4,   INPUT_COLOR                         )
112 DALI_PROPERTY_REGISTRATION(Toolkit,                 TextEditor, "inputFontFamily",                      STRING,    INPUT_FONT_FAMILY                   )
113 DALI_PROPERTY_REGISTRATION(Toolkit,                 TextEditor, "inputFontStyle",                       MAP,       INPUT_FONT_STYLE                    )
114 DALI_PROPERTY_REGISTRATION(Toolkit,                 TextEditor, "inputPointSize",                       FLOAT,     INPUT_POINT_SIZE                    )
115 DALI_PROPERTY_REGISTRATION(Toolkit,                 TextEditor, "lineSpacing",                          FLOAT,     LINE_SPACING                        )
116 DALI_PROPERTY_REGISTRATION(Toolkit,                 TextEditor, "inputLineSpacing",                     FLOAT,     INPUT_LINE_SPACING                  )
117 DALI_PROPERTY_REGISTRATION(Toolkit,                 TextEditor, "underline",                            MAP,       UNDERLINE                           )
118 DALI_PROPERTY_REGISTRATION(Toolkit,                 TextEditor, "inputUnderline",                       MAP,       INPUT_UNDERLINE                     )
119 DALI_PROPERTY_REGISTRATION(Toolkit,                 TextEditor, "shadow",                               MAP,       SHADOW                              )
120 DALI_PROPERTY_REGISTRATION(Toolkit,                 TextEditor, "inputShadow",                          MAP,       INPUT_SHADOW                        )
121 DALI_PROPERTY_REGISTRATION(Toolkit,                 TextEditor, "emboss",                               MAP,       EMBOSS                              )
122 DALI_PROPERTY_REGISTRATION(Toolkit,                 TextEditor, "inputEmboss",                          MAP,       INPUT_EMBOSS                        )
123 DALI_PROPERTY_REGISTRATION(Toolkit,                 TextEditor, "outline",                              MAP,       OUTLINE                             )
124 DALI_PROPERTY_REGISTRATION(Toolkit,                 TextEditor, "inputOutline",                         MAP,       INPUT_OUTLINE                       )
125 DALI_PROPERTY_REGISTRATION(Toolkit,                 TextEditor, "smoothScroll",                         BOOLEAN,   SMOOTH_SCROLL                       )
126 DALI_PROPERTY_REGISTRATION(Toolkit,                 TextEditor, "smoothScrollDuration",                 FLOAT,     SMOOTH_SCROLL_DURATION              )
127 DALI_PROPERTY_REGISTRATION(Toolkit,                 TextEditor, "enableScrollBar",                      BOOLEAN,   ENABLE_SCROLL_BAR                   )
128 DALI_PROPERTY_REGISTRATION(Toolkit,                 TextEditor, "scrollBarShowDuration",                FLOAT,     SCROLL_BAR_SHOW_DURATION            )
129 DALI_PROPERTY_REGISTRATION(Toolkit,                 TextEditor, "scrollBarFadeDuration",                FLOAT,     SCROLL_BAR_FADE_DURATION            )
130 DALI_PROPERTY_REGISTRATION(Toolkit,                 TextEditor, "pixelSize",                            FLOAT,     PIXEL_SIZE                          )
131 DALI_PROPERTY_REGISTRATION_READ_ONLY(Toolkit,       TextEditor, "lineCount",                            INTEGER,   LINE_COUNT                          )
132 DALI_PROPERTY_REGISTRATION(Toolkit,                 TextEditor, "enableSelection",                      BOOLEAN,   ENABLE_SELECTION                    )
133 DALI_PROPERTY_REGISTRATION(Toolkit,                 TextEditor, "placeholder",                          MAP,       PLACEHOLDER                         )
134 DALI_PROPERTY_REGISTRATION(Toolkit,                 TextEditor, "lineWrapMode",                         INTEGER,   LINE_WRAP_MODE                      )
135 DALI_DEVEL_PROPERTY_REGISTRATION(Toolkit,           TextEditor, "placeholderText",                      STRING,    PLACEHOLDER_TEXT                    )
136 DALI_DEVEL_PROPERTY_REGISTRATION(Toolkit,           TextEditor, "placeholderTextColor",                 VECTOR4,   PLACEHOLDER_TEXT_COLOR              )
137 DALI_DEVEL_PROPERTY_REGISTRATION(Toolkit,           TextEditor, "enableShiftSelection",                 BOOLEAN,   ENABLE_SHIFT_SELECTION              )
138 DALI_DEVEL_PROPERTY_REGISTRATION(Toolkit,           TextEditor, "enableGrabHandle",                     BOOLEAN,   ENABLE_GRAB_HANDLE                  )
139 DALI_DEVEL_PROPERTY_REGISTRATION(Toolkit,           TextEditor, "matchSystemLanguageDirection",         BOOLEAN,   MATCH_SYSTEM_LANGUAGE_DIRECTION     )
140 DALI_DEVEL_PROPERTY_REGISTRATION(Toolkit,           TextEditor, "renderingBackend",                     INTEGER,   RENDERING_BACKEND                   )
141 DALI_DEVEL_PROPERTY_REGISTRATION(Toolkit,           TextEditor, "maxLength",                            INTEGER,   MAX_LENGTH                          )
142 DALI_DEVEL_PROPERTY_REGISTRATION(Toolkit,           TextEditor, "selectedTextStart",                    INTEGER,   SELECTED_TEXT_START                 )
143 DALI_DEVEL_PROPERTY_REGISTRATION(Toolkit,           TextEditor, "selectedTextEnd",                      INTEGER,   SELECTED_TEXT_END                   )
144 DALI_DEVEL_PROPERTY_REGISTRATION(Toolkit,           TextEditor, "horizontalScrollPosition",             FLOAT,     HORIZONTAL_SCROLL_POSITION          )
145 DALI_DEVEL_PROPERTY_REGISTRATION(Toolkit,           TextEditor, "verticalScrollPosition",               INTEGER,   VERTICAL_SCROLL_POSITION            )
146 DALI_DEVEL_PROPERTY_REGISTRATION(Toolkit,           TextEditor, "enableEditing",                        BOOLEAN,   ENABLE_EDITING                      )
147 DALI_DEVEL_PROPERTY_REGISTRATION_READ_ONLY(Toolkit, TextEditor, "selectedText",                         STRING,    SELECTED_TEXT                       )
148 DALI_DEVEL_PROPERTY_REGISTRATION(Toolkit,           TextEditor, "fontSizeScale",                        FLOAT,     FONT_SIZE_SCALE                     )
149 DALI_DEVEL_PROPERTY_REGISTRATION(Toolkit,           TextEditor, "enableFontSizeScale",                  BOOLEAN,   ENABLE_FONT_SIZE_SCALE              )
150 DALI_DEVEL_PROPERTY_REGISTRATION(Toolkit,           TextEditor, "primaryCursorPosition",                INTEGER,   PRIMARY_CURSOR_POSITION             )
151 DALI_DEVEL_PROPERTY_REGISTRATION(Toolkit,           TextEditor, "grabHandleColor",                      VECTOR4,   GRAB_HANDLE_COLOR                   )
152 DALI_DEVEL_PROPERTY_REGISTRATION(Toolkit,           TextEditor, "enableGrabHandlePopup",                BOOLEAN,   ENABLE_GRAB_HANDLE_POPUP            )
153 DALI_DEVEL_PROPERTY_REGISTRATION(Toolkit,           TextEditor, "inputMethodSettings",                  MAP,       INPUT_METHOD_SETTINGS               )
154 DALI_DEVEL_PROPERTY_REGISTRATION(Toolkit,           TextEditor, "inputFilter",                          MAP,       INPUT_FILTER                        )
155 DALI_DEVEL_PROPERTY_REGISTRATION(Toolkit,           TextEditor, "ellipsis",                             BOOLEAN,   ELLIPSIS                            )
156 DALI_DEVEL_PROPERTY_REGISTRATION(Toolkit,           TextEditor, "ellipsisPosition",                     INTEGER,   ELLIPSIS_POSITION                   )
157 DALI_DEVEL_PROPERTY_REGISTRATION(Toolkit,           TextEditor, "minLineSize",                          FLOAT,     MIN_LINE_SIZE                       )
158 DALI_DEVEL_PROPERTY_REGISTRATION(Toolkit,           TextEditor, "strikethrough",                        MAP,       STRIKETHROUGH                       )
159 DALI_DEVEL_PROPERTY_REGISTRATION(Toolkit,           TextEditor, "inputStrikethrough",                   MAP,       INPUT_STRIKETHROUGH                 )
160 DALI_DEVEL_PROPERTY_REGISTRATION(Toolkit,           TextEditor, "characterSpacing",                     FLOAT,     CHARACTER_SPACING                   )
161 DALI_DEVEL_PROPERTY_REGISTRATION(Toolkit,           TextEditor, "relativeLineSize",                     FLOAT,     RELATIVE_LINE_SIZE                  )
162 DALI_DEVEL_PROPERTY_REGISTRATION(Toolkit,           TextEditor, "verticalAlignment",                    STRING,    VERTICAL_ALIGNMENT                  )
163 DALI_DEVEL_PROPERTY_REGISTRATION(Toolkit,           TextEditor, "selectionPopupStyle",                  MAP,       SELECTION_POPUP_STYLE               )
164
165 DALI_SIGNAL_REGISTRATION(Toolkit, TextEditor, "textChanged",           SIGNAL_TEXT_CHANGED           )
166 DALI_SIGNAL_REGISTRATION(Toolkit, TextEditor, "inputStyleChanged",     SIGNAL_INPUT_STYLE_CHANGED    )
167 DALI_SIGNAL_REGISTRATION(Toolkit, TextEditor, "maxLengthReached",      SIGNAL_MAX_LENGTH_REACHED     )
168 DALI_SIGNAL_REGISTRATION(Toolkit, TextEditor, "anchorClicked",         SIGNAL_ANCHOR_CLICKED         )
169 DALI_SIGNAL_REGISTRATION(Toolkit, TextEditor, "inputFiltered",         SIGNAL_INPUT_FILTERED         )
170 DALI_SIGNAL_REGISTRATION(Toolkit, TextEditor, "cursorPositionChanged", SIGNAL_CURSOR_POSITION_CHANGED)
171 DALI_SIGNAL_REGISTRATION(Toolkit, TextEditor, "selectionChanged",      SIGNAL_SELECTION_CHANGED      )
172 DALI_SIGNAL_REGISTRATION(Toolkit, TextEditor, "selectionCleared",      SIGNAL_SELECTION_CLEARED      )
173 DALI_SIGNAL_REGISTRATION(Toolkit, TextEditor, "selectionStarted",      SIGNAL_SELECTION_STARTED      )
174
175 DALI_TYPE_REGISTRATION_END()
176 // clang-format on
177
178 Toolkit::TextEditor::InputStyle::Mask ConvertInputStyle(Text::InputStyle::Mask inputStyleMask)
179 {
180   Toolkit::TextEditor::InputStyle::Mask editorInputStyleMask = Toolkit::TextEditor::InputStyle::NONE;
181
182   if(InputStyle::NONE != static_cast<InputStyle::Mask>(inputStyleMask & InputStyle::INPUT_COLOR))
183   {
184     editorInputStyleMask = static_cast<Toolkit::TextEditor::InputStyle::Mask>(editorInputStyleMask | Toolkit::TextEditor::InputStyle::COLOR);
185   }
186   if(InputStyle::NONE != static_cast<InputStyle::Mask>(inputStyleMask & InputStyle::INPUT_FONT_FAMILY))
187   {
188     editorInputStyleMask = static_cast<Toolkit::TextEditor::InputStyle::Mask>(editorInputStyleMask | Toolkit::TextEditor::InputStyle::FONT_FAMILY);
189   }
190   if(InputStyle::NONE != static_cast<InputStyle::Mask>(inputStyleMask & InputStyle::INPUT_POINT_SIZE))
191   {
192     editorInputStyleMask = static_cast<Toolkit::TextEditor::InputStyle::Mask>(editorInputStyleMask | Toolkit::TextEditor::InputStyle::POINT_SIZE);
193   }
194   if(InputStyle::NONE != static_cast<InputStyle::Mask>(inputStyleMask & InputStyle::INPUT_FONT_WEIGHT))
195   {
196     editorInputStyleMask = static_cast<Toolkit::TextEditor::InputStyle::Mask>(editorInputStyleMask | Toolkit::TextEditor::InputStyle::FONT_STYLE);
197   }
198   if(InputStyle::NONE != static_cast<InputStyle::Mask>(inputStyleMask & InputStyle::INPUT_FONT_WIDTH))
199   {
200     editorInputStyleMask = static_cast<Toolkit::TextEditor::InputStyle::Mask>(editorInputStyleMask | Toolkit::TextEditor::InputStyle::FONT_STYLE);
201   }
202   if(InputStyle::NONE != static_cast<InputStyle::Mask>(inputStyleMask & InputStyle::INPUT_FONT_SLANT))
203   {
204     editorInputStyleMask = static_cast<Toolkit::TextEditor::InputStyle::Mask>(editorInputStyleMask | Toolkit::TextEditor::InputStyle::FONT_STYLE);
205   }
206   if(InputStyle::NONE != static_cast<InputStyle::Mask>(inputStyleMask & InputStyle::INPUT_LINE_SPACING))
207   {
208     editorInputStyleMask = static_cast<Toolkit::TextEditor::InputStyle::Mask>(editorInputStyleMask | Toolkit::TextEditor::InputStyle::LINE_SPACING);
209   }
210   if(InputStyle::NONE != static_cast<InputStyle::Mask>(inputStyleMask & InputStyle::INPUT_UNDERLINE))
211   {
212     editorInputStyleMask = static_cast<Toolkit::TextEditor::InputStyle::Mask>(editorInputStyleMask | Toolkit::TextEditor::InputStyle::UNDERLINE);
213   }
214   if(InputStyle::NONE != static_cast<InputStyle::Mask>(inputStyleMask & InputStyle::INPUT_SHADOW))
215   {
216     editorInputStyleMask = static_cast<Toolkit::TextEditor::InputStyle::Mask>(editorInputStyleMask | Toolkit::TextEditor::InputStyle::SHADOW);
217   }
218   if(InputStyle::NONE != static_cast<InputStyle::Mask>(inputStyleMask & InputStyle::INPUT_EMBOSS))
219   {
220     editorInputStyleMask = static_cast<Toolkit::TextEditor::InputStyle::Mask>(editorInputStyleMask | Toolkit::TextEditor::InputStyle::EMBOSS);
221   }
222   if(InputStyle::NONE != static_cast<InputStyle::Mask>(inputStyleMask & InputStyle::INPUT_OUTLINE))
223   {
224     editorInputStyleMask = static_cast<Toolkit::TextEditor::InputStyle::Mask>(editorInputStyleMask | Toolkit::TextEditor::InputStyle::OUTLINE);
225   }
226   if(InputStyle::NONE != static_cast<InputStyle::Mask>(inputStyleMask & InputStyle::INPUT_STRIKETHROUGH))
227   {
228     editorInputStyleMask = static_cast<Toolkit::TextEditor::InputStyle::Mask>(editorInputStyleMask | Toolkit::TextEditor::InputStyle::STRIKETHROUGH);
229   }
230
231   return editorInputStyleMask;
232 }
233
234 } // namespace
235
236 Toolkit::TextEditor TextEditor::New(ControlBehaviour additionalBehaviour)
237 {
238   // Create the implementation, temporarily owned by this handle on stack
239   IntrusivePtr<TextEditor> impl = new TextEditor(additionalBehaviour);
240
241   // Pass ownership to CustomActor handle
242   Toolkit::TextEditor handle(*impl);
243
244   // Second-phase init of the implementation
245   // This can only be done after the CustomActor connection has been made...
246   impl->Initialize();
247
248   return handle;
249 }
250
251 void TextEditor::SetProperty(BaseObject* object, Property::Index index, const Property::Value& value)
252 {
253   Toolkit::TextEditor textEditor = Toolkit::TextEditor::DownCast(Dali::BaseHandle(object));
254
255   DALI_LOG_INFO(gTextEditorLogFilter, Debug::Verbose, "TextEditor SetProperty\n");
256
257   if(textEditor)
258   {
259     PropertyHandler::SetProperty(textEditor, index, value);
260   }
261 }
262
263 Property::Value TextEditor::GetProperty(BaseObject* object, Property::Index index)
264 {
265   Property::Value value;
266
267   Toolkit::TextEditor textEditor = Toolkit::TextEditor::DownCast(Dali::BaseHandle(object));
268
269   if(textEditor)
270   {
271     value = PropertyHandler::GetProperty(textEditor, index);
272   }
273   return value;
274 }
275
276 void TextEditor::SelectWholeText()
277 {
278   if(mController && mController->IsShowingRealText())
279   {
280     mController->SelectWholeText();
281     SetKeyInputFocus();
282   }
283 }
284
285 void TextEditor::SelectNone()
286 {
287   if(mController && mController->IsShowingRealText())
288   {
289     mController->SelectNone();
290   }
291 }
292
293 void TextEditor::SelectText(const uint32_t start, const uint32_t end)
294 {
295   if(mController && mController->IsShowingRealText())
296   {
297     mController->SelectText(start, end);
298     SetKeyInputFocus();
299   }
300 }
301
302 string TextEditor::CopyText()
303 {
304   string copiedText = "";
305   if(mController && mController->IsShowingRealText())
306   {
307     copiedText = mController->CopyText();
308   }
309   return copiedText;
310 }
311
312 string TextEditor::CutText()
313 {
314   string cutText = "";
315   if(mController && mController->IsShowingRealText())
316   {
317     cutText = mController->CutText();
318   }
319   return cutText;
320 }
321
322 void TextEditor::PasteText()
323 {
324   if(mController)
325   {
326     SetKeyInputFocus(); //Giving focus to the editor that was passed to the PasteText in case the passed editor (current editor) doesn't have focus.
327     mController->PasteText();
328   }
329 }
330
331 void TextEditor::ScrollBy(Vector2 scroll)
332 {
333   if(mController && mController->IsShowingRealText())
334   {
335     mController->ScrollBy(scroll);
336   }
337 }
338
339 float TextEditor::GetHorizontalScrollPosition()
340 {
341   if(mController && mController->IsShowingRealText())
342   {
343     return mController->GetHorizontalScrollPosition();
344   }
345   return 0;
346 }
347
348 float TextEditor::GetVerticalScrollPosition()
349 {
350   if(mController && mController->IsShowingRealText())
351   {
352     return mController->GetVerticalScrollPosition();
353   }
354   return 0;
355 }
356
357 Vector<Vector2> TextEditor::GetTextSize(const uint32_t startIndex, const uint32_t endIndex) const
358 {
359   return mController->GetTextSize(startIndex, endIndex);
360 }
361
362 Vector<Vector2> TextEditor::GetTextPosition(const uint32_t startIndex, const uint32_t endIndex) const
363 {
364   return mController->GetTextPosition(startIndex, endIndex);
365 }
366
367 Rect<float> TextEditor::GetLineBoundingRectangle(const uint32_t lineIndex) const
368 {
369   return mController->GetLineBoundingRectangle(lineIndex);
370 }
371
372 Rect<float> TextEditor::GetCharacterBoundingRectangle(const uint32_t charIndex) const
373 {
374   return mController->GetCharacterBoundingRectangle(charIndex);
375 }
376
377 int TextEditor::GetCharacterIndexAtPosition(float visualX, float visualY) const
378 {
379   return mController->GetCharacterIndexAtPosition(visualX, visualY);
380 }
381
382 void TextEditor::SetSpannedText(const Text::Spanned& spannedText)
383 {
384   mController->SetSpannedText(spannedText);
385 }
386
387 string TextEditor::GetSelectedText() const
388 {
389   string selectedText = "";
390   if(mController && mController->IsShowingRealText())
391   {
392     selectedText = mController->GetSelectedText();
393   }
394   return selectedText;
395 }
396
397 InputMethodContext TextEditor::GetInputMethodContext()
398 {
399   return mInputMethodContext;
400 }
401
402 DevelTextEditor::MaxLengthReachedSignalType& TextEditor::MaxLengthReachedSignal()
403 {
404   return mMaxLengthReachedSignal;
405 }
406
407 DevelTextEditor::AnchorClickedSignalType& TextEditor::AnchorClickedSignal()
408 {
409   return mAnchorClickedSignal;
410 }
411
412 DevelTextEditor::CursorPositionChangedSignalType& TextEditor::CursorPositionChangedSignal()
413 {
414   return mCursorPositionChangedSignal;
415 }
416
417 DevelTextEditor::InputFilteredSignalType& TextEditor::InputFilteredSignal()
418 {
419   return mInputFilteredSignal;
420 }
421
422 DevelTextEditor::SelectionChangedSignalType& TextEditor::SelectionChangedSignal()
423 {
424   return mSelectionChangedSignal;
425 }
426
427 DevelTextEditor::SelectionClearedSignalType& TextEditor::SelectionClearedSignal()
428 {
429   return mSelectionClearedSignal;
430 }
431
432 DevelTextEditor::SelectionStartedSignalType& TextEditor::SelectionStartedSignal()
433 {
434   return mSelectionStartedSignal;
435 }
436
437 Text::ControllerPtr TextEditor::GetTextController()
438 {
439   return mController;
440 }
441
442 bool TextEditor::DoConnectSignal(BaseObject* object, ConnectionTrackerInterface* tracker, const std::string& signalName, FunctorDelegate* functor)
443 {
444   Dali::BaseHandle handle(object);
445
446   bool                connected(true);
447   Toolkit::TextEditor editor = Toolkit::TextEditor::DownCast(handle);
448
449   if(0 == strcmp(signalName.c_str(), SIGNAL_TEXT_CHANGED))
450   {
451     editor.TextChangedSignal().Connect(tracker, functor);
452   }
453   else if(0 == strcmp(signalName.c_str(), SIGNAL_INPUT_STYLE_CHANGED))
454   {
455     editor.InputStyleChangedSignal().Connect(tracker, functor);
456   }
457   else if(0 == strcmp(signalName.c_str(), SIGNAL_MAX_LENGTH_REACHED))
458   {
459     if(editor)
460     {
461       Internal::TextEditor& editorImpl(GetImpl(editor));
462       editorImpl.MaxLengthReachedSignal().Connect(tracker, functor);
463     }
464   }
465   else if(0 == strcmp(signalName.c_str(), SIGNAL_ANCHOR_CLICKED))
466   {
467     if(editor)
468     {
469       Internal::TextEditor& editorImpl(GetImpl(editor));
470       editorImpl.AnchorClickedSignal().Connect(tracker, functor);
471     }
472   }
473   else if(0 == strcmp(signalName.c_str(), SIGNAL_CURSOR_POSITION_CHANGED))
474   {
475     if(editor)
476     {
477       Internal::TextEditor& editorImpl(GetImpl(editor));
478       editorImpl.CursorPositionChangedSignal().Connect(tracker, functor);
479     }
480   }
481   else if(0 == strcmp(signalName.c_str(), SIGNAL_INPUT_FILTERED))
482   {
483     if(editor)
484     {
485       Internal::TextEditor& editorImpl(GetImpl(editor));
486       editorImpl.InputFilteredSignal().Connect(tracker, functor);
487     }
488   }
489   else if(0 == strcmp(signalName.c_str(), SIGNAL_SELECTION_CHANGED))
490   {
491     if(editor)
492     {
493       Internal::TextEditor& editorImpl(GetImpl(editor));
494       editorImpl.SelectionChangedSignal().Connect(tracker, functor);
495     }
496   }
497   else if(0 == strcmp(signalName.c_str(), SIGNAL_SELECTION_CLEARED))
498   {
499     if(editor)
500     {
501       Internal::TextEditor& editorImpl(GetImpl(editor));
502       editorImpl.SelectionClearedSignal().Connect(tracker, functor);
503     }
504   }
505   else if(0 == strcmp(signalName.c_str(), SIGNAL_SELECTION_STARTED))
506   {
507     if(editor)
508     {
509       Internal::TextEditor& editorImpl(GetImpl(editor));
510       editorImpl.SelectionStartedSignal().Connect(tracker, functor);
511     }
512   }
513   else
514   {
515     // signalName does not match any signal
516     connected = false;
517   }
518
519   return connected;
520 }
521
522 Toolkit::TextEditor::TextChangedSignalType& TextEditor::TextChangedSignal()
523 {
524   return mTextChangedSignal;
525 }
526
527 Toolkit::TextEditor::InputStyleChangedSignalType& TextEditor::InputStyleChangedSignal()
528 {
529   return mInputStyleChangedSignal;
530 }
531
532 Toolkit::TextEditor::ScrollStateChangedSignalType& TextEditor::ScrollStateChangedSignal()
533 {
534   return mScrollStateChangedSignal;
535 }
536
537 void TextEditor::OnAccessibilityStatusChanged()
538 {
539   CommonTextUtils::SynchronizeTextAnchorsInParent(Self(), mController, mAnchorActors);
540 }
541
542 void TextEditor::OnInitialize()
543 {
544   Actor self = Self();
545
546   mController = Text::Controller::New(this, this, this, this);
547
548   mDecorator = Text::Decorator::New(*mController,
549                                     *mController);
550
551   mInputMethodContext = InputMethodContext::New(self);
552
553   mController->GetLayoutEngine().SetLayout(Layout::Engine::MULTI_LINE_BOX);
554
555   // Enables the text input.
556   mController->EnableTextInput(mDecorator, mInputMethodContext);
557
558   // Enables the vertical scrolling after the text input has been enabled.
559   mController->SetVerticalScrollEnabled(true);
560
561   // Disables the horizontal scrolling.
562   mController->SetHorizontalScrollEnabled(false);
563
564   // Sets the maximum number of characters.
565   mController->SetMaximumNumberOfCharacters(std::numeric_limits<Length>::max());
566
567   // Enable the smooth handle panning.
568   mController->SetSmoothHandlePanEnabled(true);
569
570   mController->SetNoTextDoubleTapAction(Controller::NoTextTap::HIGHLIGHT);
571   mController->SetNoTextLongPressAction(Controller::NoTextTap::HIGHLIGHT);
572
573   // Sets layoutDirection value
574   Dali::Stage                 stage           = Dali::Stage::GetCurrent();
575   Dali::LayoutDirection::Type layoutDirection = static_cast<Dali::LayoutDirection::Type>(stage.GetRootLayer().GetProperty(Dali::Actor::Property::LAYOUT_DIRECTION).Get<int>());
576   mController->SetLayoutDirection(layoutDirection);
577
578   self.LayoutDirectionChangedSignal().Connect(this, &TextEditor::OnLayoutDirectionChanged);
579
580   // Forward input events to controller
581   EnableGestureDetection(static_cast<GestureType::Value>(GestureType::TAP | GestureType::PAN | GestureType::LONG_PRESS));
582   GetTapGestureDetector().SetMaximumTapsRequired(2);
583   GetTapGestureDetector().ReceiveAllTapEvents(true);
584
585   self.TouchedSignal().Connect(this, &TextEditor::OnTouched);
586
587   // Set BoundingBox to stage size if not already set.
588   Rect<int> boundingBox;
589   mDecorator->GetBoundingBox(boundingBox);
590
591   if(boundingBox.IsEmpty())
592   {
593     Vector2 stageSize = Dali::Stage::GetCurrent().GetSize();
594     mDecorator->SetBoundingBox(Rect<int>(0.0f, 0.0f, stageSize.width, stageSize.height));
595   }
596
597   // Whether to flip the selection handles as soon as they cross.
598   mDecorator->FlipSelectionHandlesOnCrossEnabled(true);
599
600   // Set the default scroll speed.
601   mDecorator->SetScrollSpeed(DEFAULT_SCROLL_SPEED);
602
603   // Fill-parent area by default
604   self.SetResizePolicy(ResizePolicy::FILL_TO_PARENT, Dimension::WIDTH);
605   self.SetResizePolicy(ResizePolicy::FILL_TO_PARENT, Dimension::HEIGHT);
606   self.OnSceneSignal().Connect(this, &TextEditor::OnSceneConnect);
607
608   DevelControl::SetInputMethodContext(*this, mInputMethodContext);
609
610   // Creates an extra control to be used as stencil buffer.
611   mStencil = Control::New();
612   mStencil.SetProperty(Actor::Property::ANCHOR_POINT, AnchorPoint::TOP_LEFT);
613   mStencil.SetProperty(Actor::Property::PARENT_ORIGIN, ParentOrigin::TOP_LEFT);
614
615   // Creates a background visual. Even if the color is transparent it updates the stencil.
616   mStencil.SetProperty(Toolkit::Control::Property::BACKGROUND,
617                        Property::Map().Add(Toolkit::Visual::Property::TYPE, Toolkit::Visual::COLOR).Add(ColorVisual::Property::MIX_COLOR, Color::TRANSPARENT));
618
619   // Enable the clipping property.
620   mStencil.SetProperty(Actor::Property::CLIPPING_MODE, ClippingMode::CLIP_TO_BOUNDING_BOX);
621   mStencil.SetResizePolicy(ResizePolicy::FILL_TO_PARENT, Dimension::ALL_DIMENSIONS);
622
623   self.Add(mStencil);
624
625   // Accessibility
626   self.SetProperty(DevelControl::Property::ACCESSIBILITY_ROLE, Dali::Accessibility::Role::ENTRY);
627   self.SetProperty(DevelControl::Property::ACCESSIBILITY_HIGHLIGHTABLE, true);
628
629   Accessibility::Bridge::EnabledSignal().Connect(this, &TextEditor::OnAccessibilityStatusChanged);
630   Accessibility::Bridge::DisabledSignal().Connect(this, &TextEditor::OnAccessibilityStatusChanged);
631 }
632
633 DevelControl::ControlAccessible* TextEditor::CreateAccessibleObject()
634 {
635   return new TextEditorAccessible(Self());
636 }
637
638 void TextEditor::OnStyleChange(Toolkit::StyleManager styleManager, StyleChange::Type change)
639 {
640   DALI_LOG_INFO(gTextEditorLogFilter, Debug::Verbose, "TextEditor::OnStyleChange\n");
641
642   switch(change)
643   {
644     case StyleChange::DEFAULT_FONT_CHANGE:
645     {
646       DALI_LOG_INFO(gTextEditorLogFilter, Debug::Verbose, "TextEditor::OnStyleChange DEFAULT_FONT_CHANGE\n");
647       const std::string& newFont = GetImpl(styleManager).GetDefaultFontFamily();
648       // Property system did not set the font so should update it.
649       mController->UpdateAfterFontChange(newFont);
650       RelayoutRequest();
651       break;
652     }
653
654     case StyleChange::DEFAULT_FONT_SIZE_CHANGE:
655     {
656       GetImpl(styleManager).ApplyThemeStyle(Toolkit::Control(GetOwner()));
657       RelayoutRequest();
658       break;
659     }
660     case StyleChange::THEME_CHANGE:
661     {
662       // Nothing to do, let control base class handle this
663       break;
664     }
665   }
666
667   // Up call to Control
668   Control::OnStyleChange(styleManager, change);
669 }
670
671 Vector3 TextEditor::GetNaturalSize()
672 {
673   Extents padding;
674   padding = Self().GetProperty<Extents>(Toolkit::Control::Property::PADDING);
675
676   Vector3 naturalSize = mController->GetNaturalSize();
677   naturalSize.width += (padding.start + padding.end);
678   naturalSize.height += (padding.top + padding.bottom);
679
680   return naturalSize;
681 }
682
683 float TextEditor::GetHeightForWidth(float width)
684 {
685   Extents padding;
686   padding = Self().GetProperty<Extents>(Toolkit::Control::Property::PADDING);
687   return mController->GetHeightForWidth(width) + padding.top + padding.bottom;
688 }
689
690 void TextEditor::ResizeActor(Actor& actor, const Vector2& size)
691 {
692   if(actor.GetProperty<Vector3>(Dali::Actor::Property::SIZE).GetVectorXY() != size)
693   {
694     actor.SetProperty(Actor::Property::SIZE, size);
695   }
696 }
697
698 void TextEditor::OnPropertySet(Property::Index index, const Property::Value& propertyValue)
699 {
700   DALI_LOG_INFO(gTextEditorLogFilter, Debug::Verbose, "TextEditor::OnPropertySet index[%d]\n", index);
701
702   switch(index)
703   {
704     case DevelActor::Property::USER_INTERACTION_ENABLED:
705     {
706       const bool enabled = propertyValue.Get<bool>();
707       mController->SetUserInteractionEnabled(enabled);
708       if(mStencil)
709       {
710         float opacity = enabled ? 1.0f : mController->GetDisabledColorOpacity();
711         mStencil.SetProperty(Actor::Property::OPACITY, opacity);
712       }
713       break;
714     }
715     default:
716     {
717       Control::OnPropertySet(index, propertyValue); // up call to control for non-handled properties
718       break;
719     }
720   }
721 }
722
723 void TextEditor::OnRelayout(const Vector2& size, RelayoutContainer& container)
724 {
725   DALI_LOG_INFO(gTextEditorLogFilter, Debug::Verbose, "TextEditor OnRelayout\n");
726
727   Actor self = Self();
728
729   Extents padding;
730   padding = self.GetProperty<Extents>(Toolkit::Control::Property::PADDING);
731
732   Vector2 contentSize(size.x - (padding.start + padding.end), size.y - (padding.top + padding.bottom));
733
734   // Support Right-To-Left of padding
735   Dali::LayoutDirection::Type layoutDirection = mController->GetLayoutDirection(self);
736
737   if(Dali::LayoutDirection::RIGHT_TO_LEFT == layoutDirection)
738   {
739     std::swap(padding.start, padding.end);
740   }
741
742   if(mStencil)
743   {
744     mStencil.SetProperty(Actor::Property::POSITION, Vector2(padding.start, padding.top));
745     ResizeActor(mStencil, contentSize);
746   }
747   if(mActiveLayer)
748   {
749     mActiveLayer.SetProperty(Actor::Property::POSITION, Vector2(padding.start, padding.top));
750     ResizeActor(mActiveLayer, contentSize);
751   }
752   if(mCursorLayer)
753   {
754     mCursorLayer.SetProperty(Actor::Property::POSITION, Vector2(padding.start, padding.top));
755     ResizeActor(mCursorLayer, contentSize);
756   }
757
758   // If there is text changed, callback is called.
759   if(mTextChanged)
760   {
761     EmitTextChangedSignal();
762   }
763
764   const Text::Controller::UpdateTextType updateTextType = mController->Relayout(contentSize, layoutDirection);
765
766   if((Text::Controller::NONE_UPDATED != updateTextType) ||
767      !mRenderer)
768   {
769     DALI_LOG_INFO(gTextEditorLogFilter, Debug::Verbose, "TextEditor::OnRelayout %p Displaying new contents\n", mController.Get());
770
771     if(mDecorator &&
772        (Text::Controller::NONE_UPDATED != (Text::Controller::DECORATOR_UPDATED & updateTextType)))
773     {
774       mDecorator->Relayout(contentSize);
775     }
776
777     if(!mRenderer)
778     {
779       mRenderer = Backend::Get().NewRenderer(mRenderingBackend);
780     }
781
782     RenderText(updateTextType);
783   }
784
785   if(mCursorPositionChanged)
786   {
787     EmitCursorPositionChangedSignal();
788   }
789
790   if(mSelectionStarted)
791   {
792     EmitSelectionStartedSignal();
793   }
794
795   if(mSelectionChanged)
796   {
797     EmitSelectionChangedSignal();
798   }
799
800   if(mSelectionCleared)
801   {
802     EmitSelectionClearedSignal();
803   }
804
805   // The text-editor emits signals when the input style changes. These changes of style are
806   // detected during the relayout process (size negotiation), i.e after the cursor has been moved. Signals
807   // can't be emitted during the size negotiation as the callbacks may update the UI.
808   // The text-editor adds an idle callback to the adaptor to emit the signals after the size negotiation.
809   if(!mController->IsInputStyleChangedSignalsQueueEmpty())
810   {
811     if(Adaptor::IsAvailable())
812     {
813       Adaptor& adaptor = Adaptor::Get();
814
815       if(NULL == mIdleCallback)
816       {
817         // @note: The callback manager takes the ownership of the callback object.
818         mIdleCallback = MakeCallback(this, &TextEditor::OnIdleSignal);
819         adaptor.AddIdle(mIdleCallback, false);
820       }
821     }
822   }
823 }
824
825 void TextEditor::RenderText(Text::Controller::UpdateTextType updateTextType)
826 {
827   CommonTextUtils::RenderText(Self(), mRenderer, mController, mDecorator, mAlignmentOffset, mRenderableActor, mBackgroundActor, mCursorLayer, mStencil, mClippingDecorationActors, mAnchorActors, updateTextType);
828   if(mRenderableActor)
829   {
830     ApplyScrollPosition();
831   }
832   UpdateScrollBar();
833 }
834
835 void TextEditor::OnKeyInputFocusGained()
836 {
837   DALI_LOG_INFO(gTextEditorLogFilter, Debug::Verbose, "TextEditor::OnKeyInputFocusGained %p\n", mController.Get());
838   if(mInputMethodContext && IsEditable())
839   {
840     // All input panel properties, such as layout, return key type, and input hint, should be set before input panel activates (or shows).
841     mInputMethodContext.ApplyOptions(mInputMethodOptions);
842     mInputMethodContext.NotifyTextInputMultiLine(true);
843
844     mInputMethodContext.StatusChangedSignal().Connect(this, &TextEditor::KeyboardStatusChanged);
845
846     mInputMethodContext.EventReceivedSignal().Connect(this, &TextEditor::OnInputMethodContextEvent);
847
848     // Notify that the text editing start.
849     mInputMethodContext.Activate();
850
851     // When window gain lost focus, the InputMethodContext is deactivated. Thus when window gain focus again, the InputMethodContext must be activated.
852     mInputMethodContext.SetRestoreAfterFocusLost(true);
853   }
854   ClipboardEventNotifier notifier(ClipboardEventNotifier::Get());
855
856   if(notifier)
857   {
858     notifier.ContentSelectedSignal().Connect(this, &TextEditor::OnClipboardTextSelected);
859   }
860
861   if(IsEditable() && mController->IsUserInteractionEnabled())
862   {
863     mController->KeyboardFocusGainEvent(); // Called in the case of no virtual keyboard to trigger this event
864   }
865
866   EmitKeyInputFocusSignal(true); // Calls back into the Control hence done last.
867 }
868
869 void TextEditor::OnKeyInputFocusLost()
870 {
871   DALI_LOG_INFO(gTextEditorLogFilter, Debug::Verbose, "TextEditor:OnKeyInputFocusLost %p\n", mController.Get());
872   if(mInputMethodContext)
873   {
874     mInputMethodContext.StatusChangedSignal().Disconnect(this, &TextEditor::KeyboardStatusChanged);
875
876     // The text editing is finished. Therefore the InputMethodContext don't have restore activation.
877     mInputMethodContext.SetRestoreAfterFocusLost(false);
878
879     // Notify that the text editing finish.
880     mInputMethodContext.Deactivate();
881
882     mInputMethodContext.EventReceivedSignal().Disconnect(this, &TextEditor::OnInputMethodContextEvent);
883   }
884   ClipboardEventNotifier notifier(ClipboardEventNotifier::Get());
885
886   if(notifier)
887   {
888     notifier.ContentSelectedSignal().Disconnect(this, &TextEditor::OnClipboardTextSelected);
889   }
890
891   mController->KeyboardFocusLostEvent();
892
893   EmitKeyInputFocusSignal(false); // Calls back into the Control hence done last.
894 }
895
896 bool TextEditor::OnAccessibilityActivated()
897 {
898   SetKeyInputFocus();
899   return true;
900 }
901
902 void TextEditor::OnTap(const TapGesture& gesture)
903 {
904   DALI_LOG_INFO(gTextEditorLogFilter, Debug::Verbose, "TextEditor::OnTap %p\n", mController.Get());
905   if(mInputMethodContext && IsEditable())
906   {
907     mInputMethodContext.Activate();
908   }
909   // Deliver the tap before the focus event to controller; this allows us to detect when focus is gained due to tap-gestures
910   Extents padding;
911   padding                   = Self().GetProperty<Extents>(Toolkit::Control::Property::PADDING);
912   const Vector2& localPoint = gesture.GetLocalPoint();
913   mController->TapEvent(gesture.GetNumberOfTaps(), localPoint.x - padding.start, localPoint.y - padding.top);
914   mController->AnchorEvent(localPoint.x - padding.start, localPoint.y - padding.top);
915
916   Dali::Toolkit::KeyboardFocusManager keyboardFocusManager = Dali::Toolkit::KeyboardFocusManager::Get();
917   if(keyboardFocusManager)
918   {
919     keyboardFocusManager.SetCurrentFocusActor(Self());
920   }
921   SetKeyInputFocus();
922 }
923
924 void TextEditor::OnPan(const PanGesture& gesture)
925 {
926   mController->PanEvent(gesture.GetState(), gesture.GetDisplacement());
927   if(gesture.GetState() == GestureState::STARTED && !mController->IsScrollable(gesture.GetDisplacement()))
928   {
929     Dali::DevelActor::SetNeedGesturePropagation(Self(), true);
930   }
931 }
932
933 void TextEditor::OnLongPress(const LongPressGesture& gesture)
934 {
935   if(mInputMethodContext && IsEditable())
936   {
937     mInputMethodContext.Activate();
938   }
939   Extents padding;
940   padding                   = Self().GetProperty<Extents>(Toolkit::Control::Property::PADDING);
941   const Vector2& localPoint = gesture.GetLocalPoint();
942   mController->LongPressEvent(gesture.GetState(), localPoint.x - padding.start, localPoint.y - padding.top);
943
944   SetKeyInputFocus();
945 }
946
947 bool TextEditor::OnKeyEvent(const KeyEvent& event)
948 {
949   DALI_LOG_INFO(gTextEditorLogFilter, Debug::Verbose, "TextEditor::OnKeyEvent %p keyCode %d\n", mController.Get(), event.GetKeyCode());
950
951   if(Dali::DALI_KEY_ESCAPE == event.GetKeyCode() && mController->ShouldClearFocusOnEscape())
952   {
953     // Make sure ClearKeyInputFocus when only key is up
954     if(event.GetState() == KeyEvent::UP)
955     {
956       Dali::Toolkit::KeyboardFocusManager keyboardFocusManager = Dali::Toolkit::KeyboardFocusManager::Get();
957       if(keyboardFocusManager)
958       {
959         keyboardFocusManager.ClearFocus();
960       }
961       ClearKeyInputFocus();
962     }
963
964     return true;
965   }
966
967   return mController->KeyEvent(event);
968 }
969
970 void TextEditor::RequestTextRelayout()
971 {
972   RelayoutRequest();
973 }
974
975 void TextEditor::TextInserted(unsigned int position, unsigned int length, const std::string& content)
976 {
977   GetAccessibleObject()->EmitTextInserted(position, length, content);
978 }
979
980 void TextEditor::TextDeleted(unsigned int position, unsigned int length, const std::string& content)
981 {
982   GetAccessibleObject()->EmitTextDeleted(position, length, content);
983 }
984
985 void TextEditor::CursorPositionChanged(unsigned int oldPosition, unsigned int newPosition)
986 {
987   GetAccessibleObject()->EmitTextCursorMoved(newPosition);
988
989   if((oldPosition != newPosition) && !mCursorPositionChanged)
990   {
991     mCursorPositionChanged = true;
992     mOldPosition           = oldPosition;
993   }
994 }
995
996 void TextEditor::TextChanged(bool immediate)
997 {
998   if(immediate) // Emits TextChangedSignal immediately
999   {
1000     EmitTextChangedSignal();
1001   }
1002   else
1003   {
1004     mTextChanged = true;
1005   }
1006 }
1007
1008 void TextEditor::EmitTextChangedSignal()
1009 {
1010   Dali::Toolkit::TextEditor handle(GetOwner());
1011   mTextChangedSignal.Emit(handle);
1012   mTextChanged = false;
1013 }
1014
1015 void TextEditor::MaxLengthReached()
1016 {
1017   Dali::Toolkit::TextEditor handle(GetOwner());
1018   mMaxLengthReachedSignal.Emit(handle);
1019 }
1020
1021 void TextEditor::InputStyleChanged(Text::InputStyle::Mask inputStyleMask)
1022 {
1023   Dali::Toolkit::TextEditor handle(GetOwner());
1024   mInputStyleChangedSignal.Emit(handle, ConvertInputStyle(inputStyleMask));
1025 }
1026
1027 void TextEditor::AnchorClicked(const std::string& href)
1028 {
1029   Dali::Toolkit::TextEditor handle(GetOwner());
1030   mAnchorClickedSignal.Emit(handle, href.c_str(), href.length());
1031 }
1032
1033 void TextEditor::EmitCursorPositionChangedSignal()
1034 {
1035   Dali::Toolkit::TextEditor handle(GetOwner());
1036   mCursorPositionChanged = false;
1037   mCursorPositionChangedSignal.Emit(handle, mOldPosition);
1038 }
1039
1040 void TextEditor::InputFiltered(Toolkit::InputFilter::Property::Type type)
1041 {
1042   Dali::Toolkit::TextEditor handle(GetOwner());
1043   mInputFilteredSignal.Emit(handle, type);
1044 }
1045
1046 void TextEditor::EmitSelectionChangedSignal()
1047 {
1048   Dali::Toolkit::TextEditor handle(GetOwner());
1049   mSelectionChangedSignal.Emit(handle, mOldSelectionStart, mOldSelectionEnd);
1050   mSelectionChanged = false;
1051 }
1052
1053 void TextEditor::EmitSelectionClearedSignal()
1054 {
1055   Dali::Toolkit::TextEditor handle(GetOwner());
1056   mSelectionClearedSignal.Emit(handle);
1057   mSelectionCleared = false;
1058 }
1059
1060 void TextEditor::EmitSelectionStartedSignal()
1061 {
1062   Dali::Toolkit::TextEditor handle(GetOwner());
1063   mSelectionStartedSignal.Emit(handle);
1064   mSelectionStarted = false;
1065 }
1066
1067 void TextEditor::SelectionChanged(uint32_t oldStart, uint32_t oldEnd, uint32_t newStart, uint32_t newEnd)
1068 {
1069   if(((oldStart != newStart) || (oldEnd != newEnd)) && !mSelectionChanged)
1070   {
1071     if(newStart == newEnd)
1072     {
1073       mSelectionCleared = true;
1074     }
1075     else
1076     {
1077       if(oldStart == oldEnd)
1078       {
1079         mSelectionStarted = true;
1080       }
1081     }
1082
1083     mSelectionChanged  = true;
1084     mOldSelectionStart = oldStart;
1085     mOldSelectionEnd   = oldEnd;
1086
1087     if(mOldSelectionStart > mOldSelectionEnd)
1088     {
1089       //swap
1090       uint32_t temp      = mOldSelectionStart;
1091       mOldSelectionStart = mOldSelectionEnd;
1092       mOldSelectionEnd   = temp;
1093     }
1094   }
1095 }
1096
1097 void TextEditor::AddDecoration(Actor& actor, DecorationType type, bool needsClipping)
1098 {
1099   if(actor)
1100   {
1101     if(needsClipping)
1102     {
1103       mClippingDecorationActors.push_back(actor);
1104     }
1105
1106     // If the actor is a layer type, add it.
1107     if(type == DecorationType::ACTIVE_LAYER)
1108     {
1109       AddLayer(mActiveLayer, actor);
1110     }
1111     else if(type == DecorationType::CURSOR_LAYER)
1112     {
1113       AddLayer(mCursorLayer, actor);
1114     }
1115   }
1116 }
1117
1118 void TextEditor::AddLayer(Actor& layer, Actor& actor)
1119 {
1120   actor.SetProperty(Actor::Property::PARENT_ORIGIN, ParentOrigin::TOP_LEFT);
1121   actor.SetProperty(Actor::Property::ANCHOR_POINT, AnchorPoint::TOP_LEFT);
1122   Self().Add(actor);
1123   layer = actor;
1124 }
1125
1126 void TextEditor::SetTextSelectionRange(const uint32_t* start, const uint32_t* end)
1127 {
1128   if(mController && mController->IsShowingRealText())
1129   {
1130     mController->SetTextSelectionRange(start, end);
1131     SetKeyInputFocus();
1132   }
1133 }
1134
1135 Uint32Pair TextEditor::GetTextSelectionRange() const
1136 {
1137   Uint32Pair range(0, 0);
1138   if(mController && mController->IsShowingRealText())
1139   {
1140     range = mController->GetTextSelectionRange();
1141   }
1142   return range;
1143 }
1144
1145 void TextEditor::GetControlBackgroundColor(Vector4& color) const
1146 {
1147   Property::Value propValue = Self().GetProperty(Toolkit::Control::Property::BACKGROUND);
1148   Property::Map*  resultMap = propValue.GetMap();
1149
1150   Property::Value* colorValue = nullptr;
1151   if(resultMap && (colorValue = resultMap->Find(ColorVisual::Property::MIX_COLOR)))
1152   {
1153     colorValue->Get(color);
1154   }
1155 }
1156
1157 void TextEditor::UpdateScrollBar()
1158 {
1159   using namespace Dali;
1160
1161   float scrollPosition;
1162   float controlSize;
1163   float layoutSize;
1164   bool  latestScrolled;
1165
1166   if(!mScrollBarEnabled)
1167   {
1168     return;
1169   }
1170   latestScrolled = mController->GetTextScrollInfo(scrollPosition, controlSize, layoutSize);
1171   if(!latestScrolled || controlSize > layoutSize)
1172   {
1173     return;
1174   }
1175
1176   CustomActor self = Self();
1177   if(!mScrollBar)
1178   {
1179     mScrollBar = Toolkit::ScrollBar::New(Toolkit::ScrollBar::VERTICAL);
1180     mScrollBar.SetIndicatorHeightPolicy(Toolkit::ScrollBar::VARIABLE);
1181     mScrollBar.SetProperty(Actor::Property::PARENT_ORIGIN, ParentOrigin::TOP_RIGHT);
1182     mScrollBar.SetProperty(Actor::Property::ANCHOR_POINT, AnchorPoint::TOP_RIGHT);
1183     mScrollBar.SetResizePolicy(ResizePolicy::FILL_TO_PARENT, Dimension::HEIGHT);
1184     mScrollBar.SetResizePolicy(ResizePolicy::FIT_TO_CHILDREN, Dimension::WIDTH);
1185
1186     // Register the scroll position property
1187     Property::Index propertyScrollPosition = self.RegisterProperty(SCROLL_BAR_POSITION, scrollPosition);
1188     // Register the minimum scroll position property
1189     Property::Index propertyMinScrollPosition = self.RegisterProperty(SCROLL_BAR_POSITION_MIN, 0.0f);
1190     // Register the maximum scroll position property
1191     Property::Index propertyMaxScrollPosition = self.RegisterProperty(SCROLL_BAR_POSITION_MAX, (layoutSize - controlSize));
1192     // Register the scroll content size property
1193     Property::Index propertyScrollContentSize = self.RegisterProperty(SCROLL_BAR_CONTENT_SIZE, layoutSize);
1194
1195     mScrollBar.SetScrollPropertySource(self, propertyScrollPosition, propertyMinScrollPosition, propertyMaxScrollPosition, propertyScrollContentSize);
1196
1197     // Set style name of ScrollBar for styling
1198     mScrollBar.SetStyleName("TextEditorScrollBar");
1199     Toolkit::Control scrollIndicator = Toolkit::Control::DownCast(mScrollBar.GetScrollIndicator());
1200     if(scrollIndicator)
1201     {
1202       // Set style name of ScrollBarIndicator for styling
1203       scrollIndicator.SetStyleName("TextEditorScrollBarIndicator");
1204     }
1205
1206     self.Add(mScrollBar);
1207   }
1208   else
1209   {
1210     Property::Index propertyScrollPosition    = self.GetPropertyIndex(SCROLL_BAR_POSITION);
1211     Property::Index propertyMaxScrollPosition = self.GetPropertyIndex(SCROLL_BAR_POSITION_MAX);
1212     Property::Index propertyScrollContentSize = self.GetPropertyIndex(SCROLL_BAR_CONTENT_SIZE);
1213
1214     self.SetProperty(propertyScrollPosition, scrollPosition);
1215     self.SetProperty(propertyMaxScrollPosition, (layoutSize - controlSize));
1216     self.SetProperty(propertyScrollContentSize, layoutSize);
1217   }
1218
1219   // If scrolling is not started, start scrolling and emit ScrollStateChangedSignal
1220   if(!mScrollStarted)
1221   {
1222     mScrollStarted = true;
1223     Dali::Toolkit::TextEditor handle(GetOwner());
1224     mScrollStateChangedSignal.Emit(handle, Toolkit::TextEditor::Scroll::STARTED);
1225   }
1226
1227   Actor indicator = mScrollBar.GetScrollIndicator();
1228   if(mAnimation)
1229   {
1230     mAnimation.Stop(); // Cancel any animation
1231   }
1232   else
1233   {
1234     mAnimation = Animation::New(mAnimationPeriod.durationSeconds);
1235   }
1236   indicator.SetProperty(Actor::Property::OPACITY, 1.0f);
1237   mAnimation.AnimateTo(Property(indicator, Actor::Property::COLOR_ALPHA), 0.0f, AlphaFunction::EASE_IN, mAnimationPeriod);
1238   mAnimation.Play();
1239   mAnimation.FinishedSignal().Connect(this, &TextEditor::OnScrollIndicatorAnimationFinished);
1240 }
1241
1242 void TextEditor::OnScrollIndicatorAnimationFinished(Animation& animation)
1243 {
1244   // If animation is successfully ended, then emit ScrollStateChangedSignal
1245   if(animation.GetCurrentProgress() == 0.0f)
1246   {
1247     mScrollStarted = false;
1248     Dali::Toolkit::TextEditor handle(GetOwner());
1249     mScrollStateChangedSignal.Emit(handle, Toolkit::TextEditor::Scroll::FINISHED);
1250   }
1251 }
1252
1253 void TextEditor::OnSceneConnect(Dali::Actor actor)
1254 {
1255   if(mHasBeenStaged)
1256   {
1257     RenderText(static_cast<Text::Controller::UpdateTextType>(Text::Controller::MODEL_UPDATED | Text::Controller::DECORATOR_UPDATED));
1258   }
1259   else
1260   {
1261     mHasBeenStaged = true;
1262   }
1263 }
1264
1265 InputMethodContext::CallbackData TextEditor::OnInputMethodContextEvent(Dali::InputMethodContext& inputMethodContext, const InputMethodContext::EventData& inputMethodContextEvent)
1266 {
1267   DALI_LOG_INFO(gTextEditorLogFilter, Debug::Verbose, "TextEditor::OnInputMethodContextEvent %p eventName %d\n", mController.Get(), inputMethodContextEvent.eventName);
1268   return mController->OnInputMethodContextEvent(inputMethodContext, inputMethodContextEvent);
1269 }
1270
1271 void TextEditor::GetHandleImagePropertyValue(Property::Value& value, Text::HandleType handleType, Text::HandleImageType handleImageType)
1272 {
1273   if(mDecorator)
1274   {
1275     Property::Map map;
1276     map[TextEditor::PropertyHandler::IMAGE_MAP_FILENAME_STRING] = mDecorator->GetHandleImage(handleType, handleImageType);
1277
1278     value = map;
1279   }
1280 }
1281
1282 void TextEditor::OnClipboardTextSelected(ClipboardEventNotifier& clipboard)
1283 {
1284   mController->PasteClipboardItemEvent();
1285 }
1286
1287 void TextEditor::KeyboardStatusChanged(bool keyboardShown)
1288 {
1289   DALI_LOG_INFO(gTextEditorLogFilter, Debug::Verbose, "TextEditor::KeyboardStatusChanged %p keyboardShown %d\n", mController.Get(), keyboardShown);
1290
1291   // Just hide the grab handle when keyboard is hidden.
1292   if(!keyboardShown)
1293   {
1294     mController->KeyboardFocusLostEvent();
1295   }
1296   else
1297   {
1298     mController->KeyboardFocusGainEvent(); // Initially called by OnKeyInputFocusGained
1299   }
1300 }
1301
1302 void TextEditor::OnSceneConnection(int depth)
1303 {
1304   // Sets the depth to the visuals inside the text's decorator.
1305   mDecorator->SetTextDepth(depth);
1306
1307   // The depth of the text renderer is set in the RenderText() called from OnRelayout().
1308
1309   // Call the Control::OnSceneConnection() to set the depth of the background.
1310   Control::OnSceneConnection(depth);
1311 }
1312
1313 bool TextEditor::OnTouched(Actor actor, const TouchEvent& touch)
1314 {
1315   return false;
1316 }
1317
1318 void TextEditor::OnIdleSignal()
1319 {
1320   // Emits the change of input style signals.
1321   mController->ProcessInputStyleChangedSignals();
1322
1323   // Set the pointer to null as the callback manager deletes the callback after execute it.
1324   mIdleCallback = NULL;
1325 }
1326
1327 void TextEditor::ApplyScrollPosition()
1328 {
1329   const Vector2& scrollOffset = mController->GetTextModel()->GetScrollPosition();
1330   float          scrollAmount = 0.0f;
1331
1332   if(mScrollAnimationEnabled)
1333   {
1334     scrollAmount = mController->GetScrollAmountByUserInput();
1335   }
1336   if(mTextVerticalScroller)
1337   {
1338     mTextVerticalScroller->CheckStartAnimation(mRenderableActor, scrollOffset.x + mAlignmentOffset, scrollOffset.y - scrollAmount, scrollAmount);
1339   }
1340   else if(Equals(scrollAmount, 0.0f, Math::MACHINE_EPSILON_1))
1341   {
1342     mRenderableActor.SetProperty(Actor::Property::POSITION, Vector2(scrollOffset.x + mAlignmentOffset, scrollOffset.y - scrollAmount));
1343   }
1344   else
1345   {
1346     mTextVerticalScroller = Text::TextVerticalScroller::New();
1347     if(!Equals(mScrollAnimationDuration, 0.0f, Math::MACHINE_EPSILON_1))
1348     {
1349       mTextVerticalScroller->SetDuration(mScrollAnimationDuration);
1350     }
1351     mTextVerticalScroller->CheckStartAnimation(mRenderableActor, scrollOffset.x + mAlignmentOffset, scrollOffset.y - scrollAmount, scrollAmount);
1352   }
1353 }
1354
1355 bool TextEditor::IsEditable() const
1356 {
1357   return mController->IsEditable();
1358 }
1359
1360 void TextEditor::SetEditable(bool editable)
1361 {
1362   mController->SetEditable(editable);
1363   if(mInputMethodContext && !editable)
1364   {
1365     mInputMethodContext.Deactivate();
1366   }
1367 }
1368
1369 void TextEditor::OnLayoutDirectionChanged(Actor actor, LayoutDirection::Type type)
1370 {
1371   mController->ChangedLayoutDirection();
1372 }
1373
1374 TextEditor::TextEditor(ControlBehaviour additionalBehaviour)
1375 : Control(ControlBehaviour(CONTROL_BEHAVIOUR_DEFAULT | additionalBehaviour)),
1376   mAnimationPeriod(0.0f, 0.0f),
1377   mIdleCallback(NULL),
1378   mAlignmentOffset(0.f),
1379   mScrollAnimationDuration(0.f),
1380   mLineSpacing(0.f),
1381   mRenderingBackend(DEFAULT_RENDERING_BACKEND),
1382   mHasBeenStaged(false),
1383   mScrollAnimationEnabled(false),
1384   mScrollBarEnabled(false),
1385   mScrollStarted(false),
1386   mTextChanged(false),
1387   mCursorPositionChanged(false),
1388   mSelectionChanged(false),
1389   mSelectionCleared(false),
1390   mOldPosition(0u),
1391   mOldSelectionStart(0u),
1392   mOldSelectionEnd(0u),
1393   mSelectionStarted(false)
1394 {
1395 }
1396
1397 TextEditor::~TextEditor()
1398 {
1399   UnparentAndReset(mStencil);
1400
1401   if((NULL != mIdleCallback) && Adaptor::IsAvailable())
1402   {
1403     // Removes the callback from the callback manager in case the text-editor is destroyed before the callback is executed.
1404     Adaptor::Get().RemoveIdle(mIdleCallback);
1405   }
1406 }
1407
1408 std::string TextEditor::TextEditorAccessible::GetName() const
1409 {
1410   return GetWholeText();
1411 }
1412
1413 const std::vector<Toolkit::TextAnchor>& TextEditor::TextEditorAccessible::GetTextAnchors() const
1414 {
1415   auto self = Toolkit::TextEditor::DownCast(Self());
1416
1417   return Toolkit::GetImpl(self).mAnchorActors;
1418 }
1419
1420 Toolkit::Text::ControllerPtr TextEditor::TextEditorAccessible::GetTextController() const
1421 {
1422   auto self = Toolkit::TextEditor::DownCast(Self());
1423
1424   return Toolkit::GetImpl(self).GetTextController();
1425 }
1426
1427 void TextEditor::TextEditorAccessible::RequestTextRelayout()
1428 {
1429   auto  self     = Toolkit::TextEditor::DownCast(Self());
1430   auto& selfImpl = Toolkit::GetImpl(self);
1431
1432   selfImpl.RequestTextRelayout();
1433 }
1434
1435 } // namespace Internal
1436
1437 } // namespace Toolkit
1438
1439 } // namespace Dali