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