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