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