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