Add GetCharacterBoundingRectangle 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()
237 {
238   // Create the implementation, temporarily owned by this handle on stack
239   IntrusivePtr<TextEditor> impl = new TextEditor();
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 string TextEditor::GetSelectedText() const
378 {
379   string selectedText = "";
380   if(mController && mController->IsShowingRealText())
381   {
382     selectedText = mController->GetSelectedText();
383   }
384   return selectedText;
385 }
386
387 InputMethodContext TextEditor::GetInputMethodContext()
388 {
389   return mInputMethodContext;
390 }
391
392 DevelTextEditor::MaxLengthReachedSignalType& TextEditor::MaxLengthReachedSignal()
393 {
394   return mMaxLengthReachedSignal;
395 }
396
397 DevelTextEditor::AnchorClickedSignalType& TextEditor::AnchorClickedSignal()
398 {
399   return mAnchorClickedSignal;
400 }
401
402 DevelTextEditor::CursorPositionChangedSignalType& TextEditor::CursorPositionChangedSignal()
403 {
404   return mCursorPositionChangedSignal;
405 }
406
407 DevelTextEditor::InputFilteredSignalType& TextEditor::InputFilteredSignal()
408 {
409   return mInputFilteredSignal;
410 }
411
412 DevelTextEditor::SelectionChangedSignalType& TextEditor::SelectionChangedSignal()
413 {
414   return mSelectionChangedSignal;
415 }
416
417 DevelTextEditor::SelectionClearedSignalType& TextEditor::SelectionClearedSignal()
418 {
419   return mSelectionClearedSignal;
420 }
421
422 DevelTextEditor::SelectionStartedSignalType& TextEditor::SelectionStartedSignal()
423 {
424   return mSelectionStartedSignal;
425 }
426
427 Text::ControllerPtr TextEditor::GetTextController()
428 {
429   return mController;
430 }
431
432 bool TextEditor::DoConnectSignal(BaseObject* object, ConnectionTrackerInterface* tracker, const std::string& signalName, FunctorDelegate* functor)
433 {
434   Dali::BaseHandle handle(object);
435
436   bool                connected(true);
437   Toolkit::TextEditor editor = Toolkit::TextEditor::DownCast(handle);
438
439   if(0 == strcmp(signalName.c_str(), SIGNAL_TEXT_CHANGED))
440   {
441     editor.TextChangedSignal().Connect(tracker, functor);
442   }
443   else if(0 == strcmp(signalName.c_str(), SIGNAL_INPUT_STYLE_CHANGED))
444   {
445     editor.InputStyleChangedSignal().Connect(tracker, functor);
446   }
447   else if(0 == strcmp(signalName.c_str(), SIGNAL_MAX_LENGTH_REACHED))
448   {
449     if(editor)
450     {
451       Internal::TextEditor& editorImpl(GetImpl(editor));
452       editorImpl.MaxLengthReachedSignal().Connect(tracker, functor);
453     }
454   }
455   else if(0 == strcmp(signalName.c_str(), SIGNAL_ANCHOR_CLICKED))
456   {
457     if(editor)
458     {
459       Internal::TextEditor& editorImpl(GetImpl(editor));
460       editorImpl.AnchorClickedSignal().Connect(tracker, functor);
461     }
462   }
463   else if(0 == strcmp(signalName.c_str(), SIGNAL_CURSOR_POSITION_CHANGED))
464   {
465     if(editor)
466     {
467       Internal::TextEditor& editorImpl(GetImpl(editor));
468       editorImpl.CursorPositionChangedSignal().Connect(tracker, functor);
469     }
470   }
471   else if(0 == strcmp(signalName.c_str(), SIGNAL_INPUT_FILTERED))
472   {
473     if(editor)
474     {
475       Internal::TextEditor& editorImpl(GetImpl(editor));
476       editorImpl.InputFilteredSignal().Connect(tracker, functor);
477     }
478   }
479   else if(0 == strcmp(signalName.c_str(), SIGNAL_SELECTION_CHANGED))
480   {
481     if(editor)
482     {
483       Internal::TextEditor& editorImpl(GetImpl(editor));
484       editorImpl.SelectionChangedSignal().Connect(tracker, functor);
485     }
486   }
487   else if(0 == strcmp(signalName.c_str(), SIGNAL_SELECTION_CLEARED))
488   {
489     if(editor)
490     {
491       Internal::TextEditor& editorImpl(GetImpl(editor));
492       editorImpl.SelectionClearedSignal().Connect(tracker, functor);
493     }
494   }
495   else if(0 == strcmp(signalName.c_str(), SIGNAL_SELECTION_STARTED))
496   {
497     if(editor)
498     {
499       Internal::TextEditor& editorImpl(GetImpl(editor));
500       editorImpl.SelectionStartedSignal().Connect(tracker, functor);
501     }
502   }
503   else
504   {
505     // signalName does not match any signal
506     connected = false;
507   }
508
509   return connected;
510 }
511
512 Toolkit::TextEditor::TextChangedSignalType& TextEditor::TextChangedSignal()
513 {
514   return mTextChangedSignal;
515 }
516
517 Toolkit::TextEditor::InputStyleChangedSignalType& TextEditor::InputStyleChangedSignal()
518 {
519   return mInputStyleChangedSignal;
520 }
521
522 Toolkit::TextEditor::ScrollStateChangedSignalType& TextEditor::ScrollStateChangedSignal()
523 {
524   return mScrollStateChangedSignal;
525 }
526
527 void TextEditor::OnAccessibilityStatusChanged()
528 {
529   CommonTextUtils::SynchronizeTextAnchorsInParent(Self(), mController, mAnchorActors);
530 }
531
532 void TextEditor::OnInitialize()
533 {
534   Actor self = Self();
535
536   mController = Text::Controller::New(this, this, this, this);
537
538   mDecorator = Text::Decorator::New(*mController,
539                                     *mController);
540
541   mInputMethodContext = InputMethodContext::New(self);
542
543   mController->GetLayoutEngine().SetLayout(Layout::Engine::MULTI_LINE_BOX);
544
545   // Enables the text input.
546   mController->EnableTextInput(mDecorator, mInputMethodContext);
547
548   // Enables the vertical scrolling after the text input has been enabled.
549   mController->SetVerticalScrollEnabled(true);
550
551   // Disables the horizontal scrolling.
552   mController->SetHorizontalScrollEnabled(false);
553
554   // Sets the maximum number of characters.
555   mController->SetMaximumNumberOfCharacters(std::numeric_limits<Length>::max());
556
557   // Enable the smooth handle panning.
558   mController->SetSmoothHandlePanEnabled(true);
559
560   mController->SetNoTextDoubleTapAction(Controller::NoTextTap::HIGHLIGHT);
561   mController->SetNoTextLongPressAction(Controller::NoTextTap::HIGHLIGHT);
562
563   // Sets layoutDirection value
564   Dali::Stage                 stage           = Dali::Stage::GetCurrent();
565   Dali::LayoutDirection::Type layoutDirection = static_cast<Dali::LayoutDirection::Type>(stage.GetRootLayer().GetProperty(Dali::Actor::Property::LAYOUT_DIRECTION).Get<int>());
566   mController->SetLayoutDirection(layoutDirection);
567
568   self.LayoutDirectionChangedSignal().Connect(this, &TextEditor::OnLayoutDirectionChanged);
569
570   // Forward input events to controller
571   EnableGestureDetection(static_cast<GestureType::Value>(GestureType::TAP | GestureType::PAN | GestureType::LONG_PRESS));
572   GetTapGestureDetector().SetMaximumTapsRequired(2);
573   GetTapGestureDetector().ReceiveAllTapEvents(true);
574
575   self.TouchedSignal().Connect(this, &TextEditor::OnTouched);
576
577   // Set BoundingBox to stage size if not already set.
578   Rect<int> boundingBox;
579   mDecorator->GetBoundingBox(boundingBox);
580
581   if(boundingBox.IsEmpty())
582   {
583     Vector2 stageSize = Dali::Stage::GetCurrent().GetSize();
584     mDecorator->SetBoundingBox(Rect<int>(0.0f, 0.0f, stageSize.width, stageSize.height));
585   }
586
587   // Whether to flip the selection handles as soon as they cross.
588   mDecorator->FlipSelectionHandlesOnCrossEnabled(true);
589
590   // Set the default scroll speed.
591   mDecorator->SetScrollSpeed(DEFAULT_SCROLL_SPEED);
592
593   // Fill-parent area by default
594   self.SetResizePolicy(ResizePolicy::FILL_TO_PARENT, Dimension::WIDTH);
595   self.SetResizePolicy(ResizePolicy::FILL_TO_PARENT, Dimension::HEIGHT);
596   self.OnSceneSignal().Connect(this, &TextEditor::OnSceneConnect);
597
598   DevelControl::SetInputMethodContext(*this, mInputMethodContext);
599
600   // Creates an extra control to be used as stencil buffer.
601   mStencil = Control::New();
602   mStencil.SetProperty(Actor::Property::ANCHOR_POINT, AnchorPoint::TOP_LEFT);
603   mStencil.SetProperty(Actor::Property::PARENT_ORIGIN, ParentOrigin::TOP_LEFT);
604
605   // Creates a background visual. Even if the color is transparent it updates the stencil.
606   mStencil.SetProperty(Toolkit::Control::Property::BACKGROUND,
607                        Property::Map().Add(Toolkit::Visual::Property::TYPE, Toolkit::Visual::COLOR).Add(ColorVisual::Property::MIX_COLOR, Color::TRANSPARENT));
608
609   // Enable the clipping property.
610   mStencil.SetProperty(Actor::Property::CLIPPING_MODE, ClippingMode::CLIP_TO_BOUNDING_BOX);
611   mStencil.SetResizePolicy(ResizePolicy::FILL_TO_PARENT, Dimension::ALL_DIMENSIONS);
612
613   self.Add(mStencil);
614
615   // Accessibility
616   self.SetProperty(DevelControl::Property::ACCESSIBILITY_ROLE, Dali::Accessibility::Role::ENTRY);
617   self.SetProperty(DevelControl::Property::ACCESSIBILITY_HIGHLIGHTABLE, true);
618
619   Accessibility::Bridge::EnabledSignal().Connect(this, &TextEditor::OnAccessibilityStatusChanged);
620   Accessibility::Bridge::DisabledSignal().Connect(this, &TextEditor::OnAccessibilityStatusChanged);
621 }
622
623 DevelControl::ControlAccessible* TextEditor::CreateAccessibleObject()
624 {
625   return new TextEditorAccessible(Self());
626 }
627
628 void TextEditor::OnStyleChange(Toolkit::StyleManager styleManager, StyleChange::Type change)
629 {
630   DALI_LOG_INFO(gTextEditorLogFilter, Debug::Verbose, "TextEditor::OnStyleChange\n");
631
632   switch(change)
633   {
634     case StyleChange::DEFAULT_FONT_CHANGE:
635     {
636       DALI_LOG_INFO(gTextEditorLogFilter, Debug::Verbose, "TextEditor::OnStyleChange DEFAULT_FONT_CHANGE\n");
637       const std::string& newFont = GetImpl(styleManager).GetDefaultFontFamily();
638       // Property system did not set the font so should update it.
639       mController->UpdateAfterFontChange(newFont);
640       RelayoutRequest();
641       break;
642     }
643
644     case StyleChange::DEFAULT_FONT_SIZE_CHANGE:
645     {
646       GetImpl(styleManager).ApplyThemeStyle(Toolkit::Control(GetOwner()));
647       RelayoutRequest();
648       break;
649     }
650     case StyleChange::THEME_CHANGE:
651     {
652       // Nothing to do, let control base class handle this
653       break;
654     }
655   }
656
657   // Up call to Control
658   Control::OnStyleChange(styleManager, change);
659 }
660
661 Vector3 TextEditor::GetNaturalSize()
662 {
663   Extents padding;
664   padding = Self().GetProperty<Extents>(Toolkit::Control::Property::PADDING);
665
666   Vector3 naturalSize = mController->GetNaturalSize();
667   naturalSize.width += (padding.start + padding.end);
668   naturalSize.height += (padding.top + padding.bottom);
669
670   return naturalSize;
671 }
672
673 float TextEditor::GetHeightForWidth(float width)
674 {
675   Extents padding;
676   padding = Self().GetProperty<Extents>(Toolkit::Control::Property::PADDING);
677   return mController->GetHeightForWidth(width) + padding.top + padding.bottom;
678 }
679
680 void TextEditor::ResizeActor(Actor& actor, const Vector2& size)
681 {
682   if(actor.GetProperty<Vector3>(Dali::Actor::Property::SIZE).GetVectorXY() != size)
683   {
684     actor.SetProperty(Actor::Property::SIZE, size);
685   }
686 }
687
688 void TextEditor::OnPropertySet(Property::Index index, const Property::Value& propertyValue)
689 {
690   DALI_LOG_INFO(gTextEditorLogFilter, Debug::Verbose, "TextEditor::OnPropertySet index[%d]\n", index);
691
692   switch(index)
693   {
694     case DevelActor::Property::USER_INTERACTION_ENABLED:
695     {
696       const bool enabled = propertyValue.Get<bool>();
697       mController->SetUserInteractionEnabled(enabled);
698       if(mStencil)
699       {
700         float opacity = enabled ? 1.0f : mController->GetDisabledColorOpacity();
701         mStencil.SetProperty(Actor::Property::OPACITY, opacity);
702       }
703       break;
704     }
705     default:
706     {
707       Control::OnPropertySet(index, propertyValue); // up call to control for non-handled properties
708       break;
709     }
710   }
711 }
712
713 void TextEditor::OnRelayout(const Vector2& size, RelayoutContainer& container)
714 {
715   DALI_LOG_INFO(gTextEditorLogFilter, Debug::Verbose, "TextEditor OnRelayout\n");
716
717   Actor self = Self();
718
719   Extents padding;
720   padding = self.GetProperty<Extents>(Toolkit::Control::Property::PADDING);
721
722   Vector2 contentSize(size.x - (padding.start + padding.end), size.y - (padding.top + padding.bottom));
723
724   // Support Right-To-Left of padding
725   Dali::LayoutDirection::Type layoutDirection = mController->GetLayoutDirection(self);
726
727   if(Dali::LayoutDirection::RIGHT_TO_LEFT == layoutDirection)
728   {
729     std::swap(padding.start, padding.end);
730   }
731
732   if(mStencil)
733   {
734     mStencil.SetProperty(Actor::Property::POSITION, Vector2(padding.start, padding.top));
735     ResizeActor(mStencil, contentSize);
736   }
737   if(mActiveLayer)
738   {
739     mActiveLayer.SetProperty(Actor::Property::POSITION, Vector2(padding.start, padding.top));
740     ResizeActor(mActiveLayer, contentSize);
741   }
742   if(mCursorLayer)
743   {
744     mCursorLayer.SetProperty(Actor::Property::POSITION, Vector2(padding.start, padding.top));
745     ResizeActor(mCursorLayer, contentSize);
746   }
747
748   // If there is text changed, callback is called.
749   if(mTextChanged)
750   {
751     EmitTextChangedSignal();
752   }
753
754   const Text::Controller::UpdateTextType updateTextType = mController->Relayout(contentSize, layoutDirection);
755
756   if((Text::Controller::NONE_UPDATED != updateTextType) ||
757      !mRenderer)
758   {
759     DALI_LOG_INFO(gTextEditorLogFilter, Debug::Verbose, "TextEditor::OnRelayout %p Displaying new contents\n", mController.Get());
760
761     if(mDecorator &&
762        (Text::Controller::NONE_UPDATED != (Text::Controller::DECORATOR_UPDATED & updateTextType)))
763     {
764       mDecorator->Relayout(contentSize);
765     }
766
767     if(!mRenderer)
768     {
769       mRenderer = Backend::Get().NewRenderer(mRenderingBackend);
770     }
771
772     RenderText(updateTextType);
773   }
774
775   if(mCursorPositionChanged)
776   {
777     EmitCursorPositionChangedSignal();
778   }
779
780   if(mSelectionStarted)
781   {
782     EmitSelectionStartedSignal();
783   }
784
785   if(mSelectionChanged)
786   {
787     EmitSelectionChangedSignal();
788   }
789
790   if(mSelectionCleared)
791   {
792     EmitSelectionClearedSignal();
793   }
794
795   // The text-editor emits signals when the input style changes. These changes of style are
796   // detected during the relayout process (size negotiation), i.e after the cursor has been moved. Signals
797   // can't be emitted during the size negotiation as the callbacks may update the UI.
798   // The text-editor adds an idle callback to the adaptor to emit the signals after the size negotiation.
799   if(!mController->IsInputStyleChangedSignalsQueueEmpty())
800   {
801     if(Adaptor::IsAvailable())
802     {
803       Adaptor& adaptor = Adaptor::Get();
804
805       if(NULL == mIdleCallback)
806       {
807         // @note: The callback manager takes the ownership of the callback object.
808         mIdleCallback = MakeCallback(this, &TextEditor::OnIdleSignal);
809         adaptor.AddIdle(mIdleCallback, false);
810       }
811     }
812   }
813 }
814
815 void TextEditor::RenderText(Text::Controller::UpdateTextType updateTextType)
816 {
817   CommonTextUtils::RenderText(Self(), mRenderer, mController, mDecorator, mAlignmentOffset, mRenderableActor, mBackgroundActor, mCursorLayer, mStencil, mClippingDecorationActors, mAnchorActors, updateTextType);
818   if(mRenderableActor)
819   {
820     ApplyScrollPosition();
821   }
822   UpdateScrollBar();
823 }
824
825 void TextEditor::OnKeyInputFocusGained()
826 {
827   DALI_LOG_INFO(gTextEditorLogFilter, Debug::Verbose, "TextEditor::OnKeyInputFocusGained %p\n", mController.Get());
828   if(mInputMethodContext && IsEditable())
829   {
830     // All input panel properties, such as layout, return key type, and input hint, should be set before input panel activates (or shows).
831     mInputMethodContext.ApplyOptions(mInputMethodOptions);
832     mInputMethodContext.NotifyTextInputMultiLine(true);
833
834     mInputMethodContext.StatusChangedSignal().Connect(this, &TextEditor::KeyboardStatusChanged);
835
836     mInputMethodContext.EventReceivedSignal().Connect(this, &TextEditor::OnInputMethodContextEvent);
837
838     // Notify that the text editing start.
839     mInputMethodContext.Activate();
840
841     // When window gain lost focus, the InputMethodContext is deactivated. Thus when window gain focus again, the InputMethodContext must be activated.
842     mInputMethodContext.SetRestoreAfterFocusLost(true);
843   }
844   ClipboardEventNotifier notifier(ClipboardEventNotifier::Get());
845
846   if(notifier)
847   {
848     notifier.ContentSelectedSignal().Connect(this, &TextEditor::OnClipboardTextSelected);
849   }
850
851   if(IsEditable() && mController->IsUserInteractionEnabled())
852   {
853     mController->KeyboardFocusGainEvent(); // Called in the case of no virtual keyboard to trigger this event
854   }
855
856   EmitKeyInputFocusSignal(true); // Calls back into the Control hence done last.
857 }
858
859 void TextEditor::OnKeyInputFocusLost()
860 {
861   DALI_LOG_INFO(gTextEditorLogFilter, Debug::Verbose, "TextEditor:OnKeyInputFocusLost %p\n", mController.Get());
862   if(mInputMethodContext)
863   {
864     mInputMethodContext.StatusChangedSignal().Disconnect(this, &TextEditor::KeyboardStatusChanged);
865
866     // The text editing is finished. Therefore the InputMethodContext don't have restore activation.
867     mInputMethodContext.SetRestoreAfterFocusLost(false);
868
869     // Notify that the text editing finish.
870     mInputMethodContext.Deactivate();
871
872     mInputMethodContext.EventReceivedSignal().Disconnect(this, &TextEditor::OnInputMethodContextEvent);
873   }
874   ClipboardEventNotifier notifier(ClipboardEventNotifier::Get());
875
876   if(notifier)
877   {
878     notifier.ContentSelectedSignal().Disconnect(this, &TextEditor::OnClipboardTextSelected);
879   }
880
881   mController->KeyboardFocusLostEvent();
882
883   EmitKeyInputFocusSignal(false); // Calls back into the Control hence done last.
884 }
885
886 bool TextEditor::OnAccessibilityActivated()
887 {
888   SetKeyInputFocus();
889   return true;
890 }
891
892 void TextEditor::OnTap(const TapGesture& gesture)
893 {
894   DALI_LOG_INFO(gTextEditorLogFilter, Debug::Verbose, "TextEditor::OnTap %p\n", mController.Get());
895   if(mInputMethodContext && IsEditable())
896   {
897     mInputMethodContext.Activate();
898   }
899   // Deliver the tap before the focus event to controller; this allows us to detect when focus is gained due to tap-gestures
900   Extents padding;
901   padding                   = Self().GetProperty<Extents>(Toolkit::Control::Property::PADDING);
902   const Vector2& localPoint = gesture.GetLocalPoint();
903   mController->TapEvent(gesture.GetNumberOfTaps(), localPoint.x - padding.start, localPoint.y - padding.top);
904   mController->AnchorEvent(localPoint.x - padding.start, localPoint.y - padding.top);
905
906   Dali::Toolkit::KeyboardFocusManager keyboardFocusManager = Dali::Toolkit::KeyboardFocusManager::Get();
907   if (keyboardFocusManager)
908   {
909     keyboardFocusManager.SetCurrentFocusActor(Self());
910   }
911   SetKeyInputFocus();
912 }
913
914 void TextEditor::OnPan(const PanGesture& gesture)
915 {
916   mController->PanEvent(gesture.GetState(), gesture.GetDisplacement());
917   if(gesture.GetState() == GestureState::STARTED && !mController->IsScrollable(gesture.GetDisplacement()))
918   {
919     Dali::DevelActor::SetNeedGesturePropagation(Self(), true);
920   }
921 }
922
923 void TextEditor::OnLongPress(const LongPressGesture& gesture)
924 {
925   if(mInputMethodContext && IsEditable())
926   {
927     mInputMethodContext.Activate();
928   }
929   Extents padding;
930   padding                   = Self().GetProperty<Extents>(Toolkit::Control::Property::PADDING);
931   const Vector2& localPoint = gesture.GetLocalPoint();
932   mController->LongPressEvent(gesture.GetState(), localPoint.x - padding.start, localPoint.y - padding.top);
933
934   SetKeyInputFocus();
935 }
936
937 bool TextEditor::OnKeyEvent(const KeyEvent& event)
938 {
939   DALI_LOG_INFO(gTextEditorLogFilter, Debug::Verbose, "TextEditor::OnKeyEvent %p keyCode %d\n", mController.Get(), event.GetKeyCode());
940
941   if(Dali::DALI_KEY_ESCAPE == event.GetKeyCode() && mController->ShouldClearFocusOnEscape())
942   {
943     // Make sure ClearKeyInputFocus when only key is up
944     if(event.GetState() == KeyEvent::UP)
945     {
946       Dali::Toolkit::KeyboardFocusManager keyboardFocusManager = Dali::Toolkit::KeyboardFocusManager::Get();
947       if (keyboardFocusManager)
948       {
949         keyboardFocusManager.ClearFocus();
950       }
951       ClearKeyInputFocus();
952     }
953
954     return true;
955   }
956
957   return mController->KeyEvent(event);
958 }
959
960 void TextEditor::RequestTextRelayout()
961 {
962   RelayoutRequest();
963 }
964
965 void TextEditor::TextInserted(unsigned int position, unsigned int length, const std::string& content)
966 {
967   GetAccessibleObject()->EmitTextInserted(position, length, content);
968 }
969
970 void TextEditor::TextDeleted(unsigned int position, unsigned int length, const std::string& content)
971 {
972   GetAccessibleObject()->EmitTextDeleted(position, length, content);
973 }
974
975 void TextEditor::CursorPositionChanged(unsigned int oldPosition, unsigned int newPosition)
976 {
977   GetAccessibleObject()->EmitTextCursorMoved(newPosition);
978
979   if((oldPosition != newPosition) && !mCursorPositionChanged)
980   {
981     mCursorPositionChanged = true;
982     mOldPosition           = oldPosition;
983   }
984 }
985
986 void TextEditor::TextChanged(bool immediate)
987 {
988   if(immediate) // Emits TextChangedSignal immediately
989   {
990     EmitTextChangedSignal();
991   }
992   else
993   {
994     mTextChanged = true;
995   }
996 }
997
998 void TextEditor::EmitTextChangedSignal()
999 {
1000   Dali::Toolkit::TextEditor handle(GetOwner());
1001   mTextChangedSignal.Emit(handle);
1002   mTextChanged = false;
1003 }
1004
1005 void TextEditor::MaxLengthReached()
1006 {
1007   Dali::Toolkit::TextEditor handle(GetOwner());
1008   mMaxLengthReachedSignal.Emit(handle);
1009 }
1010
1011 void TextEditor::InputStyleChanged(Text::InputStyle::Mask inputStyleMask)
1012 {
1013   Dali::Toolkit::TextEditor handle(GetOwner());
1014   mInputStyleChangedSignal.Emit(handle, ConvertInputStyle(inputStyleMask));
1015 }
1016
1017 void TextEditor::AnchorClicked(const std::string& href)
1018 {
1019   Dali::Toolkit::TextEditor handle(GetOwner());
1020   mAnchorClickedSignal.Emit(handle, href.c_str(), href.length());
1021 }
1022
1023 void TextEditor::EmitCursorPositionChangedSignal()
1024 {
1025   Dali::Toolkit::TextEditor handle(GetOwner());
1026   mCursorPositionChanged = false;
1027   mCursorPositionChangedSignal.Emit(handle, mOldPosition);
1028 }
1029
1030 void TextEditor::InputFiltered(Toolkit::InputFilter::Property::Type type)
1031 {
1032   Dali::Toolkit::TextEditor handle(GetOwner());
1033   mInputFilteredSignal.Emit(handle, type);
1034 }
1035
1036 void TextEditor::EmitSelectionChangedSignal()
1037 {
1038   Dali::Toolkit::TextEditor handle(GetOwner());
1039   mSelectionChangedSignal.Emit(handle, mOldSelectionStart, mOldSelectionEnd);
1040   mSelectionChanged = false;
1041 }
1042
1043 void TextEditor::EmitSelectionClearedSignal()
1044 {
1045   Dali::Toolkit::TextEditor handle(GetOwner());
1046   mSelectionClearedSignal.Emit(handle);
1047   mSelectionCleared = false;
1048 }
1049
1050 void TextEditor::EmitSelectionStartedSignal()
1051 {
1052   Dali::Toolkit::TextEditor handle(GetOwner());
1053   mSelectionStartedSignal.Emit(handle);
1054   mSelectionStarted = false;
1055 }
1056
1057 void TextEditor::SelectionChanged(uint32_t oldStart, uint32_t oldEnd, uint32_t newStart, uint32_t newEnd)
1058 {
1059   if(((oldStart != newStart) || (oldEnd != newEnd)) && !mSelectionChanged)
1060   {
1061     if(newStart == newEnd)
1062     {
1063       mSelectionCleared = true;
1064     }
1065     else
1066     {
1067       if(oldStart == oldEnd)
1068       {
1069         mSelectionStarted = true;
1070       }
1071     }
1072
1073     mSelectionChanged  = true;
1074     mOldSelectionStart = oldStart;
1075     mOldSelectionEnd   = oldEnd;
1076
1077     if(mOldSelectionStart > mOldSelectionEnd)
1078     {
1079       //swap
1080       uint32_t temp      = mOldSelectionStart;
1081       mOldSelectionStart = mOldSelectionEnd;
1082       mOldSelectionEnd   = temp;
1083     }
1084   }
1085 }
1086
1087 void TextEditor::AddDecoration(Actor& actor, DecorationType type, bool needsClipping)
1088 {
1089   if(actor)
1090   {
1091     if(needsClipping)
1092     {
1093       mClippingDecorationActors.push_back(actor);
1094     }
1095
1096     // If the actor is a layer type, add it.
1097     if(type == DecorationType::ACTIVE_LAYER)
1098     {
1099       AddLayer(mActiveLayer, actor);
1100     }
1101     else if(type == DecorationType::CURSOR_LAYER)
1102     {
1103       AddLayer(mCursorLayer, actor);
1104     }
1105   }
1106 }
1107
1108 void TextEditor::AddLayer(Actor& layer, Actor& actor)
1109 {
1110   actor.SetProperty(Actor::Property::PARENT_ORIGIN, ParentOrigin::TOP_LEFT);
1111   actor.SetProperty(Actor::Property::ANCHOR_POINT, AnchorPoint::TOP_LEFT);
1112   Self().Add(actor);
1113   layer = actor;
1114 }
1115
1116 void TextEditor::SetTextSelectionRange(const uint32_t* start, const uint32_t* end)
1117 {
1118   if(mController && mController->IsShowingRealText())
1119   {
1120     mController->SetTextSelectionRange(start, end);
1121     SetKeyInputFocus();
1122   }
1123 }
1124
1125 Uint32Pair TextEditor::GetTextSelectionRange() const
1126 {
1127   Uint32Pair range(0, 0);
1128   if(mController && mController->IsShowingRealText())
1129   {
1130     range = mController->GetTextSelectionRange();
1131   }
1132   return range;
1133 }
1134
1135 void TextEditor::GetControlBackgroundColor(Vector4& color) const
1136 {
1137   Property::Value propValue = Self().GetProperty(Toolkit::Control::Property::BACKGROUND);
1138   Property::Map*  resultMap = propValue.GetMap();
1139
1140   Property::Value* colorValue = nullptr;
1141   if(resultMap && (colorValue = resultMap->Find(ColorVisual::Property::MIX_COLOR)))
1142   {
1143     colorValue->Get(color);
1144   }
1145 }
1146
1147 void TextEditor::UpdateScrollBar()
1148 {
1149   using namespace Dali;
1150
1151   float scrollPosition;
1152   float controlSize;
1153   float layoutSize;
1154   bool  latestScrolled;
1155
1156   if(!mScrollBarEnabled)
1157   {
1158     return;
1159   }
1160   latestScrolled = mController->GetTextScrollInfo(scrollPosition, controlSize, layoutSize);
1161   if(!latestScrolled || controlSize > layoutSize)
1162   {
1163     return;
1164   }
1165
1166   CustomActor self = Self();
1167   if(!mScrollBar)
1168   {
1169     mScrollBar = Toolkit::ScrollBar::New(Toolkit::ScrollBar::VERTICAL);
1170     mScrollBar.SetIndicatorHeightPolicy(Toolkit::ScrollBar::VARIABLE);
1171     mScrollBar.SetProperty(Actor::Property::PARENT_ORIGIN, ParentOrigin::TOP_RIGHT);
1172     mScrollBar.SetProperty(Actor::Property::ANCHOR_POINT, AnchorPoint::TOP_RIGHT);
1173     mScrollBar.SetResizePolicy(ResizePolicy::FILL_TO_PARENT, Dimension::HEIGHT);
1174     mScrollBar.SetResizePolicy(ResizePolicy::FIT_TO_CHILDREN, Dimension::WIDTH);
1175
1176     // Register the scroll position property
1177     Property::Index propertyScrollPosition = self.RegisterProperty(SCROLL_BAR_POSITION, scrollPosition);
1178     // Register the minimum scroll position property
1179     Property::Index propertyMinScrollPosition = self.RegisterProperty(SCROLL_BAR_POSITION_MIN, 0.0f);
1180     // Register the maximum scroll position property
1181     Property::Index propertyMaxScrollPosition = self.RegisterProperty(SCROLL_BAR_POSITION_MAX, (layoutSize - controlSize));
1182     // Register the scroll content size property
1183     Property::Index propertyScrollContentSize = self.RegisterProperty(SCROLL_BAR_CONTENT_SIZE, layoutSize);
1184
1185     mScrollBar.SetScrollPropertySource(self, propertyScrollPosition, propertyMinScrollPosition, propertyMaxScrollPosition, propertyScrollContentSize);
1186
1187     // Set style name of ScrollBar for styling
1188     mScrollBar.SetStyleName("TextEditorScrollBar");
1189     Toolkit::Control scrollIndicator = Toolkit::Control::DownCast(mScrollBar.GetScrollIndicator());
1190     if(scrollIndicator)
1191     {
1192       // Set style name of ScrollBarIndicator for styling
1193       scrollIndicator.SetStyleName("TextEditorScrollBarIndicator");
1194     }
1195
1196     self.Add(mScrollBar);
1197   }
1198   else
1199   {
1200     Property::Index propertyScrollPosition    = self.GetPropertyIndex(SCROLL_BAR_POSITION);
1201     Property::Index propertyMaxScrollPosition = self.GetPropertyIndex(SCROLL_BAR_POSITION_MAX);
1202     Property::Index propertyScrollContentSize = self.GetPropertyIndex(SCROLL_BAR_CONTENT_SIZE);
1203
1204     self.SetProperty(propertyScrollPosition, scrollPosition);
1205     self.SetProperty(propertyMaxScrollPosition, (layoutSize - controlSize));
1206     self.SetProperty(propertyScrollContentSize, layoutSize);
1207   }
1208
1209   // If scrolling is not started, start scrolling and emit ScrollStateChangedSignal
1210   if(!mScrollStarted)
1211   {
1212     mScrollStarted = true;
1213     Dali::Toolkit::TextEditor handle(GetOwner());
1214     mScrollStateChangedSignal.Emit(handle, Toolkit::TextEditor::Scroll::STARTED);
1215   }
1216
1217   Actor indicator = mScrollBar.GetScrollIndicator();
1218   if(mAnimation)
1219   {
1220     mAnimation.Stop(); // Cancel any animation
1221   }
1222   else
1223   {
1224     mAnimation = Animation::New(mAnimationPeriod.durationSeconds);
1225   }
1226   indicator.SetProperty(Actor::Property::OPACITY, 1.0f);
1227   mAnimation.AnimateTo(Property(indicator, Actor::Property::COLOR_ALPHA), 0.0f, AlphaFunction::EASE_IN, mAnimationPeriod);
1228   mAnimation.Play();
1229   mAnimation.FinishedSignal().Connect(this, &TextEditor::OnScrollIndicatorAnimationFinished);
1230 }
1231
1232 void TextEditor::OnScrollIndicatorAnimationFinished(Animation& animation)
1233 {
1234   // If animation is successfully ended, then emit ScrollStateChangedSignal
1235   if(animation.GetCurrentProgress() == 0.0f)
1236   {
1237     mScrollStarted = false;
1238     Dali::Toolkit::TextEditor handle(GetOwner());
1239     mScrollStateChangedSignal.Emit(handle, Toolkit::TextEditor::Scroll::FINISHED);
1240   }
1241 }
1242
1243 void TextEditor::OnSceneConnect(Dali::Actor actor)
1244 {
1245   if(mHasBeenStaged)
1246   {
1247     RenderText(static_cast<Text::Controller::UpdateTextType>(Text::Controller::MODEL_UPDATED | Text::Controller::DECORATOR_UPDATED));
1248   }
1249   else
1250   {
1251     mHasBeenStaged = true;
1252   }
1253 }
1254
1255 InputMethodContext::CallbackData TextEditor::OnInputMethodContextEvent(Dali::InputMethodContext& inputMethodContext, const InputMethodContext::EventData& inputMethodContextEvent)
1256 {
1257   DALI_LOG_INFO(gTextEditorLogFilter, Debug::Verbose, "TextEditor::OnInputMethodContextEvent %p eventName %d\n", mController.Get(), inputMethodContextEvent.eventName);
1258   return mController->OnInputMethodContextEvent(inputMethodContext, inputMethodContextEvent);
1259 }
1260
1261 void TextEditor::GetHandleImagePropertyValue(Property::Value& value, Text::HandleType handleType, Text::HandleImageType handleImageType)
1262 {
1263   if(mDecorator)
1264   {
1265     Property::Map map;
1266     map[TextEditor::PropertyHandler::IMAGE_MAP_FILENAME_STRING] = mDecorator->GetHandleImage(handleType, handleImageType);
1267
1268     value = map;
1269   }
1270 }
1271
1272 void TextEditor::OnClipboardTextSelected(ClipboardEventNotifier& clipboard)
1273 {
1274   mController->PasteClipboardItemEvent();
1275 }
1276
1277 void TextEditor::KeyboardStatusChanged(bool keyboardShown)
1278 {
1279   DALI_LOG_INFO(gTextEditorLogFilter, Debug::Verbose, "TextEditor::KeyboardStatusChanged %p keyboardShown %d\n", mController.Get(), keyboardShown);
1280
1281   // Just hide the grab handle when keyboard is hidden.
1282   if(!keyboardShown)
1283   {
1284     mController->KeyboardFocusLostEvent();
1285   }
1286   else
1287   {
1288     mController->KeyboardFocusGainEvent(); // Initially called by OnKeyInputFocusGained
1289   }
1290 }
1291
1292 void TextEditor::OnSceneConnection(int depth)
1293 {
1294   // Sets the depth to the visuals inside the text's decorator.
1295   mDecorator->SetTextDepth(depth);
1296
1297   // The depth of the text renderer is set in the RenderText() called from OnRelayout().
1298
1299   // Call the Control::OnSceneConnection() to set the depth of the background.
1300   Control::OnSceneConnection(depth);
1301 }
1302
1303 bool TextEditor::OnTouched(Actor actor, const TouchEvent& touch)
1304 {
1305   return false;
1306 }
1307
1308 void TextEditor::OnIdleSignal()
1309 {
1310   // Emits the change of input style signals.
1311   mController->ProcessInputStyleChangedSignals();
1312
1313   // Set the pointer to null as the callback manager deletes the callback after execute it.
1314   mIdleCallback = NULL;
1315 }
1316
1317 void TextEditor::ApplyScrollPosition()
1318 {
1319   const Vector2& scrollOffset = mController->GetTextModel()->GetScrollPosition();
1320   float          scrollAmount = 0.0f;
1321
1322   if(mScrollAnimationEnabled)
1323   {
1324     scrollAmount = mController->GetScrollAmountByUserInput();
1325   }
1326   if(mTextVerticalScroller)
1327   {
1328     mTextVerticalScroller->CheckStartAnimation(mRenderableActor, scrollOffset.x + mAlignmentOffset, scrollOffset.y - scrollAmount, scrollAmount);
1329   }
1330   else if(Equals(scrollAmount, 0.0f, Math::MACHINE_EPSILON_1))
1331   {
1332     mRenderableActor.SetProperty(Actor::Property::POSITION, Vector2(scrollOffset.x + mAlignmentOffset, scrollOffset.y - scrollAmount));
1333   }
1334   else
1335   {
1336     mTextVerticalScroller = Text::TextVerticalScroller::New();
1337     if(!Equals(mScrollAnimationDuration, 0.0f, Math::MACHINE_EPSILON_1))
1338     {
1339       mTextVerticalScroller->SetDuration(mScrollAnimationDuration);
1340     }
1341     mTextVerticalScroller->CheckStartAnimation(mRenderableActor, scrollOffset.x + mAlignmentOffset, scrollOffset.y - scrollAmount, scrollAmount);
1342   }
1343 }
1344
1345 bool TextEditor::IsEditable() const
1346 {
1347   return mController->IsEditable();
1348 }
1349
1350 void TextEditor::SetEditable(bool editable)
1351 {
1352   mController->SetEditable(editable);
1353   if(mInputMethodContext && !editable)
1354   {
1355     mInputMethodContext.Deactivate();
1356   }
1357 }
1358
1359 void TextEditor::OnLayoutDirectionChanged(Actor actor, LayoutDirection::Type type)
1360 {
1361   mController->ChangedLayoutDirection();
1362 }
1363
1364 TextEditor::TextEditor()
1365 : Control(ControlBehaviour(CONTROL_BEHAVIOUR_DEFAULT)),
1366   mAnimationPeriod(0.0f, 0.0f),
1367   mIdleCallback(NULL),
1368   mAlignmentOffset(0.f),
1369   mScrollAnimationDuration(0.f),
1370   mLineSpacing(0.f),
1371   mRenderingBackend(DEFAULT_RENDERING_BACKEND),
1372   mHasBeenStaged(false),
1373   mScrollAnimationEnabled(false),
1374   mScrollBarEnabled(false),
1375   mScrollStarted(false),
1376   mTextChanged(false),
1377   mCursorPositionChanged(false),
1378   mSelectionChanged(false),
1379   mSelectionCleared(false),
1380   mOldPosition(0u),
1381   mOldSelectionStart(0u),
1382   mOldSelectionEnd(0u),
1383   mSelectionStarted(false)
1384 {
1385 }
1386
1387 TextEditor::~TextEditor()
1388 {
1389   UnparentAndReset(mStencil);
1390
1391   if((NULL != mIdleCallback) && Adaptor::IsAvailable())
1392   {
1393     // Removes the callback from the callback manager in case the text-editor is destroyed before the callback is executed.
1394     Adaptor::Get().RemoveIdle(mIdleCallback);
1395   }
1396 }
1397
1398 std::string TextEditor::TextEditorAccessible::GetName() const
1399 {
1400   return GetWholeText();
1401 }
1402
1403 const std::vector<Toolkit::TextAnchor>& TextEditor::TextEditorAccessible::GetTextAnchors() const
1404 {
1405   auto self = Toolkit::TextEditor::DownCast(Self());
1406
1407   return Toolkit::GetImpl(self).mAnchorActors;
1408 }
1409
1410 Toolkit::Text::ControllerPtr TextEditor::TextEditorAccessible::GetTextController() const
1411 {
1412   auto self = Toolkit::TextEditor::DownCast(Self());
1413
1414   return Toolkit::GetImpl(self).GetTextController();
1415 }
1416
1417 void TextEditor::TextEditorAccessible::RequestTextRelayout()
1418 {
1419   auto  self     = Toolkit::TextEditor::DownCast(Self());
1420   auto& selfImpl = Toolkit::GetImpl(self);
1421
1422   selfImpl.RequestTextRelayout();
1423 }
1424
1425 } // namespace Internal
1426
1427 } // namespace Toolkit
1428
1429 } // namespace Dali